blob: bfdf94ce42946be537a9d0707af9a976c187dafa [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
38namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105
106
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107/// GetConversionCategory - Retrieve the implicit conversion
108/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000109ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110GetConversionCategory(ImplicitConversionKind Kind) {
111 static const ImplicitConversionCategory
112 Category[(int)ICK_Num_Conversion_Kinds] = {
113 ICC_Identity,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
116 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000117 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICC_Qualification_Adjustment,
119 ICC_Promotion,
120 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000121 ICC_Promotion,
122 ICC_Conversion,
123 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
128 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000129 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000130 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000131 ICC_Conversion,
132 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICC_Conversion
135 };
136 return Category[(int)Kind];
137}
138
139/// GetConversionRank - Retrieve the implicit conversion rank
140/// corresponding to the given implicit conversion kind.
141ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
142 static const ImplicitConversionRank
143 Rank[(int)ICK_Num_Conversion_Kinds] = {
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
148 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000149 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 ICR_Promotion,
151 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000152 ICR_Promotion,
153 ICR_Conversion,
154 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
159 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000160 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000161 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000162 ICR_Conversion,
163 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000164 ICR_Complex_Real_Conversion,
165 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000166 ICR_Conversion,
167 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000168 };
169 return Rank[(int)Kind];
170}
171
172/// GetImplicitConversionName - Return the name of this kind of
173/// implicit conversion.
174const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000175 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000176 "No conversion",
177 "Lvalue-to-rvalue",
178 "Array-to-pointer",
179 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000180 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000181 "Qualification",
182 "Integral promotion",
183 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000184 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185 "Integral conversion",
186 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000187 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188 "Floating-integral conversion",
189 "Pointer conversion",
190 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000191 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000192 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000193 "Derived-to-base conversion",
194 "Vector conversion",
195 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000196 "Complex-real conversion",
197 "Block Pointer conversion",
198 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000199 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200 };
201 return Name[Kind];
202}
203
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000204/// StandardConversionSequence - Set the standard conversion
205/// sequence to the identity conversion.
206void StandardConversionSequence::setAsIdentityConversion() {
207 First = ICK_Identity;
208 Second = ICK_Identity;
209 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000210 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000211 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000212 ReferenceBinding = false;
213 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000214 IsLvalueReference = true;
215 BindsToFunctionLvalue = false;
216 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000217 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000218 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000220}
221
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// getRank - Retrieve the rank of this standard conversion sequence
223/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224/// implicit conversions.
225ImplicitConversionRank StandardConversionSequence::getRank() const {
226 ImplicitConversionRank Rank = ICR_Exact_Match;
227 if (GetConversionRank(First) > Rank)
228 Rank = GetConversionRank(First);
229 if (GetConversionRank(Second) > Rank)
230 Rank = GetConversionRank(Second);
231 if (GetConversionRank(Third) > Rank)
232 Rank = GetConversionRank(Third);
233 return Rank;
234}
235
236/// isPointerConversionToBool - Determines whether this conversion is
237/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000238/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000239/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000240bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241 // Note that FromType has not necessarily been transformed by the
242 // array-to-pointer or function-to-pointer implicit conversions, so
243 // check for their presence as well as checking whether FromType is
244 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000245 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000246 (getFromType()->isPointerType() ||
247 getFromType()->isObjCObjectPointerType() ||
248 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000249 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251 return true;
252
253 return false;
254}
255
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256/// isPointerConversionToVoidPointer - Determines whether this
257/// conversion is a conversion of a pointer to a void pointer. This is
258/// used as part of the ranking of standard conversion sequences (C++
259/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000260bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000261StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000262isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000263 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000264 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000265
266 // Note that FromType has not necessarily been transformed by the
267 // array-to-pointer implicit conversion, so check for its presence
268 // and redo the conversion to get a pointer.
269 if (First == ICK_Array_To_Pointer)
270 FromType = Context.getArrayDecayedType(FromType);
271
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000272 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000273 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000274 return ToPtrType->getPointeeType()->isVoidType();
275
276 return false;
277}
278
Richard Smith66e05fe2012-01-18 05:21:49 +0000279/// Skip any implicit casts which could be either part of a narrowing conversion
280/// or after one in an implicit conversion.
281static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
282 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283 switch (ICE->getCastKind()) {
284 case CK_NoOp:
285 case CK_IntegralCast:
286 case CK_IntegralToBoolean:
287 case CK_IntegralToFloating:
288 case CK_FloatingToIntegral:
289 case CK_FloatingToBoolean:
290 case CK_FloatingCast:
291 Converted = ICE->getSubExpr();
292 continue;
293
294 default:
295 return Converted;
296 }
297 }
298
299 return Converted;
300}
301
302/// Check if this standard conversion sequence represents a narrowing
303/// conversion, according to C++11 [dcl.init.list]p7.
304///
305/// \param Ctx The AST context.
306/// \param Converted The result of applying this standard conversion sequence.
307/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
308/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000309/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
310/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000311NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000312StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
313 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000314 APValue &ConstantValue,
315 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000316 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000317
318 // C++11 [dcl.init.list]p7:
319 // A narrowing conversion is an implicit conversion ...
320 QualType FromType = getToType(0);
321 QualType ToType = getToType(1);
322 switch (Second) {
323 // -- from a floating-point type to an integer type, or
324 //
325 // -- from an integer type or unscoped enumeration type to a floating-point
326 // type, except where the source is a constant expression and the actual
327 // value after conversion will fit into the target type and will produce
328 // the original value when converted back to the original type, or
329 case ICK_Floating_Integral:
330 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
331 return NK_Type_Narrowing;
332 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
333 llvm::APSInt IntConstantValue;
334 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
335 if (Initializer &&
336 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
337 // Convert the integer to the floating type.
338 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
339 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
340 llvm::APFloat::rmNearestTiesToEven);
341 // And back.
342 llvm::APSInt ConvertedValue = IntConstantValue;
343 bool ignored;
344 Result.convertToInteger(ConvertedValue,
345 llvm::APFloat::rmTowardZero, &ignored);
346 // If the resulting value is different, this was a narrowing conversion.
347 if (IntConstantValue != ConvertedValue) {
348 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000349 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000350 return NK_Constant_Narrowing;
351 }
352 } else {
353 // Variables are always narrowings.
354 return NK_Variable_Narrowing;
355 }
356 }
357 return NK_Not_Narrowing;
358
359 // -- from long double to double or float, or from double to float, except
360 // where the source is a constant expression and the actual value after
361 // conversion is within the range of values that can be represented (even
362 // if it cannot be represented exactly), or
363 case ICK_Floating_Conversion:
364 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
365 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
366 // FromType is larger than ToType.
367 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
368 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
369 // Constant!
370 assert(ConstantValue.isFloat());
371 llvm::APFloat FloatVal = ConstantValue.getFloat();
372 // Convert the source value into the target type.
373 bool ignored;
374 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
375 Ctx.getFloatTypeSemantics(ToType),
376 llvm::APFloat::rmNearestTiesToEven, &ignored);
377 // If there was no overflow, the source value is within the range of
378 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000379 if (ConvertStatus & llvm::APFloat::opOverflow) {
380 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000381 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000382 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 } else {
384 return NK_Variable_Narrowing;
385 }
386 }
387 return NK_Not_Narrowing;
388
389 // -- from an integer type or unscoped enumeration type to an integer type
390 // that cannot represent all the values of the original type, except where
391 // the source is a constant expression and the actual value after
392 // conversion will fit into the target type and will produce the original
393 // value when converted back to the original type.
394 case ICK_Boolean_Conversion: // Bools are integers too.
395 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
396 // Boolean conversions can be from pointers and pointers to members
397 // [conv.bool], and those aren't considered narrowing conversions.
398 return NK_Not_Narrowing;
399 } // Otherwise, fall through to the integral case.
400 case ICK_Integral_Conversion: {
401 assert(FromType->isIntegralOrUnscopedEnumerationType());
402 assert(ToType->isIntegralOrUnscopedEnumerationType());
403 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
404 const unsigned FromWidth = Ctx.getIntWidth(FromType);
405 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
406 const unsigned ToWidth = Ctx.getIntWidth(ToType);
407
408 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000409 (FromWidth == ToWidth && FromSigned != ToSigned) ||
410 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000411 // Not all values of FromType can be represented in ToType.
412 llvm::APSInt InitializerValue;
413 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000414 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
415 // Such conversions on variables are always narrowing.
416 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000417 }
418 bool Narrowing = false;
419 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000420 // Negative -> unsigned is narrowing. Otherwise, more bits is never
421 // narrowing.
422 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000423 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000424 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000425 // Add a bit to the InitializerValue so we don't have to worry about
426 // signed vs. unsigned comparisons.
427 InitializerValue = InitializerValue.extend(
428 InitializerValue.getBitWidth() + 1);
429 // Convert the initializer to and from the target width and signed-ness.
430 llvm::APSInt ConvertedValue = InitializerValue;
431 ConvertedValue = ConvertedValue.trunc(ToWidth);
432 ConvertedValue.setIsSigned(ToSigned);
433 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
434 ConvertedValue.setIsSigned(InitializerValue.isSigned());
435 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000436 if (ConvertedValue != InitializerValue)
437 Narrowing = true;
438 }
439 if (Narrowing) {
440 ConstantType = Initializer->getType();
441 ConstantValue = APValue(InitializerValue);
442 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000443 }
444 }
445 return NK_Not_Narrowing;
446 }
447
448 default:
449 // Other kinds of conversions are not narrowings.
450 return NK_Not_Narrowing;
451 }
452}
453
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000454/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000456void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458 bool PrintedSomething = false;
459 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Second != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000469
470 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000472 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000474 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000476 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 PrintedSomething = true;
478 }
479
480 if (Third != ICK_Identity) {
481 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000484 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
491}
492
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000493/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000495void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000498 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000501 if (ConversionFunction)
502 OS << '\'' << *ConversionFunction << '\'';
503 else
504 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
509}
510
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000511/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000513void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000514 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000515 if (isStdInitializerListElement())
516 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 switch (ConversionKind) {
518 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000521 break;
522 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000523 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000524 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 break;
526 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 break;
John McCall0d1da222010-01-12 00:44:57 +0000529 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000530 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000531 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000533 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 break;
535 }
536
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000537 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538}
539
John McCall0d1da222010-01-12 00:44:57 +0000540void AmbiguousConversionSequence::construct() {
541 new (&conversions()) ConversionSet();
542}
543
544void AmbiguousConversionSequence::destruct() {
545 conversions().~ConversionSet();
546}
547
548void
549AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
550 FromTypePtr = O.FromTypePtr;
551 ToTypePtr = O.ToTypePtr;
552 new (&conversions()) ConversionSet(O.conversions());
553}
554
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000556 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000557 // template argument information.
558 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 TemplateArgument FirstArg;
560 TemplateArgument SecondArg;
561 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000562 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000563 // template parameter and template argument information.
564 struct DFIParamWithArguments : DFIArguments {
565 TemplateParameter Param;
566 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569/// \brief Convert from Sema's representation of template deduction information
570/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000571DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
572 Sema::TemplateDeductionResult TDK,
573 TemplateDeductionInfo &Info) {
574 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000575 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000576 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000577 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000578 switch (TDK) {
579 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000580 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000582 case Sema::TDK_TooManyArguments:
583 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 Result.Data = Info.Param.getOpaqueValue();
589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith44ecdbd2013-01-31 05:19:49 +0000591 case Sema::TDK_NonDeducedMismatch: {
592 // FIXME: Should allocate from normal heap so that we can free this later.
593 DFIArguments *Saved = new (Context) DFIArguments;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
596 Result.Data = Saved;
597 break;
598 }
599
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000601 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000602 // FIXME: Should allocate from normal heap so that we can free this later.
603 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Saved->Param = Info.Param;
605 Saved->FirstArg = Info.FirstArg;
606 Saved->SecondArg = Info.SecondArg;
607 Result.Data = Saved;
608 break;
609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000612 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000613 if (Info.hasSFINAEDiagnostic()) {
614 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
615 SourceLocation(), PartialDiagnostic::NullDiagnostic());
616 Info.takeSFINAEDiagnostic(*Diag);
617 Result.HasDiagnostic = true;
618 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000622 Result.Data = Info.Expression;
623 break;
624
Richard Smith44ecdbd2013-01-31 05:19:49 +0000625 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 return Result;
630}
John McCall0d1da222010-01-12 00:44:57 +0000631
Larisse Voufo98b20f12013-07-19 23:00:19 +0000632void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
634 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000635 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000636 case Sema::TDK_InstantiationDepth:
637 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000638 case Sema::TDK_TooManyArguments:
639 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000640 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000641 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000646 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000647 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000648 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000650
651 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000652 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000653 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000654 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
655 Diag->~PartialDiagnosticAt();
656 HasDiagnostic = false;
657 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000658 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor461761d2010-05-08 18:20:53 +0000660 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000661 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 break;
663 }
664}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Larisse Voufo98b20f12013-07-19 23:00:19 +0000666PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000667 if (HasDiagnostic)
668 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000669 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000670}
671
Larisse Voufo98b20f12013-07-19 23:00:19 +0000672TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000675 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000676 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000677 case Sema::TDK_TooManyArguments:
678 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000680 case Sema::TDK_NonDeducedMismatch:
681 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000685 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687
688 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000693 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 break;
695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 return TemplateParameter();
698}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_Incomplete:
708 case Sema::TDK_InvalidExplicitArguments:
709 case Sema::TDK_Inconsistent:
710 case Sema::TDK_Underqualified:
711 case Sema::TDK_NonDeducedMismatch:
712 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000713 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000714
Richard Smith44ecdbd2013-01-31 05:19:49 +0000715 case Sema::TDK_SubstitutionFailure:
716 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 // Unhandled
719 case Sema::TDK_MiscellaneousDeductionFailure:
720 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000721 }
722
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000724}
725
Larisse Voufo98b20f12013-07-19 23:00:19 +0000726const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000729 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730 case Sema::TDK_InstantiationDepth:
731 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000732 case Sema::TDK_TooManyArguments:
733 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000734 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000735 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000736 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000737 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000740 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000741 case Sema::TDK_NonDeducedMismatch:
742 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743
Douglas Gregor461761d2010-05-08 18:20:53 +0000744 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000745 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000746 break;
747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748
Craig Topperc3ec1492014-05-26 06:22:03 +0000749 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000751
Larisse Voufo98b20f12013-07-19 23:00:19 +0000752const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000755 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000760 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000761 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000762 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000766 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000769
Douglas Gregor461761d2010-05-08 18:20:53 +0000770 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000771 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 break;
773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
Craig Topperc3ec1492014-05-26 06:22:03 +0000775 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776}
777
Larisse Voufo98b20f12013-07-19 23:00:19 +0000778Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000779 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
780 Sema::TDK_FailedOverloadResolution)
781 return static_cast<Expr*>(Data);
782
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000784}
785
Benjamin Kramer97e59492012-10-09 15:52:25 +0000786void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000787 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000788 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
789 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000790 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
791 i->DeductionFailure.Destroy();
792 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000793}
794
795void OverloadCandidateSet::clear() {
796 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000797 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000798 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000799 Functions.clear();
800}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
John McCall4124c492011-10-17 18:40:02 +0000802namespace {
803 class UnbridgedCastsSet {
804 struct Entry {
805 Expr **Addr;
806 Expr *Saved;
807 };
808 SmallVector<Entry, 2> Entries;
809
810 public:
811 void save(Sema &S, Expr *&E) {
812 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
813 Entry entry = { &E, E };
814 Entries.push_back(entry);
815 E = S.stripARCUnbridgedCast(E);
816 }
817
818 void restore() {
819 for (SmallVectorImpl<Entry>::iterator
820 i = Entries.begin(), e = Entries.end(); i != e; ++i)
821 *i->Addr = i->Saved;
822 }
823 };
824}
825
826/// checkPlaceholderForOverload - Do any interesting placeholder-like
827/// preprocessing on the given expression.
828///
829/// \param unbridgedCasts a collection to which to add unbridged casts;
830/// without this, they will be immediately diagnosed as errors
831///
832/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000833static bool
834checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844 unbridgedCasts) {
845 unbridgedCasts->save(S, E);
846 return false;
847 }
848
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
852 return true;
853
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000854 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000855 return false;
856 }
857
858 // Nothing to do.
859 return false;
860}
861
862/// checkArgPlaceholdersForOverload - Check a set of call operands for
863/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000864static bool checkArgPlaceholdersForOverload(Sema &S,
865 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000866 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000869 return true;
870
871 return false;
872}
873
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000875// overload of the declarations in Old. This routine returns false if
876// New and Old cannot be overloaded, e.g., if New has the same
877// signature as some function in Old (C++ 1.3.10) or if the Old
878// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000879// it does return false, MatchedDecl will point to the decl that New
880// cannot be overloaded with. This decl may be a UsingShadowDecl on
881// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882//
883// Example: Given the following input:
884//
885// void f(int, float); // #1
886// void f(int, int); // #2
887// int f(int, int); // #3
888//
889// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000890// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000891//
John McCall3d988d92009-12-02 08:47:38 +0000892// When we process #2, Old contains only the FunctionDecl for #1. By
893// comparing the parameter types, we see that #1 and #2 are overloaded
894// (since they have different signatures), so this routine returns
895// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896//
John McCall3d988d92009-12-02 08:47:38 +0000897// When we process #3, Old is an overload set containing #1 and #2. We
898// compare the signatures of #3 to #1 (they're overloaded, so we do
899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000901// signature), IsOverload returns false and MatchedDecl will be set to
902// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000903//
904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905// into a class by a using declaration. The rules for whether to hide
906// shadow declarations ignore some properties which otherwise figure
907// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000908Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000912 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000913 NamedDecl *OldD = *I;
914
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
918
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
922
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924 }
925
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000934
Alp Tokera2794f92014-01-22 07:29:52 +0000935 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
Alp Tokera2794f92014-01-22 07:29:52 +0000942 if (!isa<FunctionTemplateDecl>(OldD) &&
943 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000944 continue;
945
John McCalldaa3d6b2009-12-09 03:35:25 +0000946 Match = *I;
947 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000948 }
John McCalla8987a2942010-11-10 03:01:53 +0000949 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000950 // We can overload with these, which can show up when doing
951 // redeclaration checks for UsingDecls.
952 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000953 } else if (isa<TagDecl>(OldD)) {
954 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956 // Optimistically assume that an unresolved using decl will
957 // overload; if it doesn't, we'll have to diagnose during
958 // template instantiation.
959 } else {
John McCall1f82f242009-11-18 22:49:29 +0000960 // (C++ 13p1):
961 // Only function declarations can be overloaded; object and type
962 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000963 Match = *I;
964 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000965 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 }
John McCall1f82f242009-11-18 22:49:29 +0000967
John McCalldaa3d6b2009-12-09 03:35:25 +0000968 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000969}
970
Richard Smithac974a32013-06-30 09:48:50 +0000971bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
972 bool UseUsingDeclRules) {
973 // C++ [basic.start.main]p2: This function shall not be overloaded.
974 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000975 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000976
David Majnemerc729b0b2013-09-16 22:44:20 +0000977 // MSVCRT user defined entry points cannot be overloaded.
978 if (New->isMSVCRTEntryPoint())
979 return false;
980
John McCall1f82f242009-11-18 22:49:29 +0000981 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
982 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
983
984 // C++ [temp.fct]p2:
985 // A function template can be overloaded with other function templates
986 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000987 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000988 return true;
989
990 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000991 QualType OldQType = Context.getCanonicalType(Old->getType());
992 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000993
994 // Compare the signatures (C++ 1.3.10) of the two functions to
995 // determine whether they are overloads. If we find any mismatch
996 // in the signature, they are overloads.
997
998 // If either of these functions is a K&R-style function (no
999 // prototype), then we consider them to have matching signatures.
1000 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1001 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1002 return false;
1003
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001004 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1005 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001006
1007 // The signature of a function includes the types of its
1008 // parameters (C++ 1.3.10), which includes the presence or absence
1009 // of the ellipsis; see C++ DR 357).
1010 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001011 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001012 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001013 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001014 return true;
1015
1016 // C++ [temp.over.link]p4:
1017 // The signature of a function template consists of its function
1018 // signature, its return type and its template parameter list. The names
1019 // of the template parameters are significant only for establishing the
1020 // relationship between the template parameters and the rest of the
1021 // signature.
1022 //
1023 // We check the return type and template parameter lists for function
1024 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001025 //
1026 // However, we don't consider either of these when deciding whether
1027 // a member introduced by a shadow declaration is hidden.
1028 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001029 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1030 OldTemplate->getTemplateParameters(),
1031 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001032 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001033 return true;
1034
1035 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001036 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001037 //
1038 // As part of this, also check whether one of the member functions
1039 // is static, in which case they are not overloads (C++
1040 // 13.1p2). While not part of the definition of the signature,
1041 // this check is important to determine whether these functions
1042 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001043 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1044 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001045 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001046 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1047 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1048 if (!UseUsingDeclRules &&
1049 (OldMethod->getRefQualifier() == RQ_None ||
1050 NewMethod->getRefQualifier() == RQ_None)) {
1051 // C++0x [over.load]p2:
1052 // - Member function declarations with the same name and the same
1053 // parameter-type-list as well as member function template
1054 // declarations with the same name, the same parameter-type-list, and
1055 // the same template parameter lists cannot be overloaded if any of
1056 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001057 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001058 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001059 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001060 }
1061 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Richard Smith574f4f62013-01-14 05:37:29 +00001064 // We may not have applied the implicit const for a constexpr member
1065 // function yet (because we haven't yet resolved whether this is a static
1066 // or non-static member function). Add it now, on the assumption that this
1067 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001068 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001069 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001070 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001071 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001072 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001073
1074 // We do not allow overloading based off of '__restrict'.
1075 OldQuals &= ~Qualifiers::Restrict;
1076 NewQuals &= ~Qualifiers::Restrict;
1077 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001078 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001081 // enable_if attributes are an order-sensitive part of the signature.
1082 for (specific_attr_iterator<EnableIfAttr>
1083 NewI = New->specific_attr_begin<EnableIfAttr>(),
1084 NewE = New->specific_attr_end<EnableIfAttr>(),
1085 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1086 OldE = Old->specific_attr_end<EnableIfAttr>();
1087 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1088 if (NewI == NewE || OldI == OldE)
1089 return true;
1090 llvm::FoldingSetNodeID NewID, OldID;
1091 NewI->getCond()->Profile(NewID, Context, true);
1092 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001093 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001094 return true;
1095 }
1096
John McCall1f82f242009-11-18 22:49:29 +00001097 // The signatures match; this is not an overload.
1098 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099}
1100
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001101/// \brief Checks availability of the function depending on the current
1102/// function context. Inside an unavailable function, unavailability is ignored.
1103///
1104/// \returns true if \arg FD is unavailable and current context is inside
1105/// an available function, false otherwise.
1106bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1107 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1108}
1109
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001110/// \brief Tries a user-defined conversion from From to ToType.
1111///
1112/// Produces an implicit conversion sequence for when a standard conversion
1113/// is not an option. See TryImplicitConversion for more information.
1114static ImplicitConversionSequence
1115TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1116 bool SuppressUserConversions,
1117 bool AllowExplicit,
1118 bool InOverloadResolution,
1119 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001120 bool AllowObjCWritebackConversion,
1121 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001122 ImplicitConversionSequence ICS;
1123
1124 if (SuppressUserConversions) {
1125 // We're not in the case above, so there is no conversion that
1126 // we can perform.
1127 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1128 return ICS;
1129 }
1130
1131 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001132 OverloadCandidateSet Conversions(From->getExprLoc(),
1133 OverloadCandidateSet::CSK_Normal);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 OverloadingResult UserDefResult
1135 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001136 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001137
1138 if (UserDefResult == OR_Success) {
1139 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001140 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001141 // C++ [over.ics.user]p4:
1142 // A conversion of an expression of class type to the same class
1143 // type is given Exact Match rank, and a conversion of an
1144 // expression of class type to a base class of that type is
1145 // given Conversion rank, in spite of the fact that a copy
1146 // constructor (i.e., a user-defined conversion function) is
1147 // called for those cases.
1148 if (CXXConstructorDecl *Constructor
1149 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1150 QualType FromCanon
1151 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1152 QualType ToCanon
1153 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1154 if (Constructor->isCopyConstructor() &&
1155 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1156 // Turn this into a "standard" conversion sequence, so that it
1157 // gets ranked with standard conversion sequences.
1158 ICS.setStandard();
1159 ICS.Standard.setAsIdentityConversion();
1160 ICS.Standard.setFromType(From->getType());
1161 ICS.Standard.setAllToTypes(ToType);
1162 ICS.Standard.CopyConstructor = Constructor;
1163 if (ToCanon != FromCanon)
1164 ICS.Standard.Second = ICK_Derived_To_Base;
1165 }
1166 }
1167
1168 // C++ [over.best.ics]p4:
1169 // However, when considering the argument of a user-defined
1170 // conversion function that is a candidate by 13.3.1.3 when
1171 // invoked for the copying of the temporary in the second step
1172 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1173 // 13.3.1.6 in all cases, only standard conversion sequences and
1174 // ellipsis conversion sequences are allowed.
1175 if (SuppressUserConversions && ICS.isUserDefined()) {
1176 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1177 }
1178 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1179 ICS.setAmbiguous();
1180 ICS.Ambiguous.setFromType(From->getType());
1181 ICS.Ambiguous.setToType(ToType);
1182 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1183 Cand != Conversions.end(); ++Cand)
1184 if (Cand->Viable)
1185 ICS.Ambiguous.addConversion(Cand->Function);
1186 } else {
1187 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1188 }
1189
1190 return ICS;
1191}
1192
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001193/// TryImplicitConversion - Attempt to perform an implicit conversion
1194/// from the given expression (Expr) to the given type (ToType). This
1195/// function returns an implicit conversion sequence that can be used
1196/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197///
1198/// void f(float f);
1199/// void g(int i) { f(i); }
1200///
1201/// this routine would produce an implicit conversion sequence to
1202/// describe the initialization of f from i, which will be a standard
1203/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1204/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1205//
1206/// Note that this routine only determines how the conversion can be
1207/// performed; it does not actually perform the conversion. As such,
1208/// it will not produce any diagnostics if no conversion is available,
1209/// but will instead return an implicit conversion sequence of kind
1210/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001211///
1212/// If @p SuppressUserConversions, then user-defined conversions are
1213/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001214/// If @p AllowExplicit, then explicit user-defined conversions are
1215/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001216///
1217/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1218/// writeback conversion, which allows __autoreleasing id* parameters to
1219/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001220static ImplicitConversionSequence
1221TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1222 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001224 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001225 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001226 bool AllowObjCWritebackConversion,
1227 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001229 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001230 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001231 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001232 return ICS;
1233 }
1234
David Blaikiebbafb8a2012-03-11 07:00:24 +00001235 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001236 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001237 return ICS;
1238 }
1239
Douglas Gregor836a7e82010-08-11 02:15:33 +00001240 // C++ [over.ics.user]p4:
1241 // A conversion of an expression of class type to the same class
1242 // type is given Exact Match rank, and a conversion of an
1243 // expression of class type to a base class of that type is
1244 // given Conversion rank, in spite of the fact that a copy/move
1245 // constructor (i.e., a user-defined conversion function) is
1246 // called for those cases.
1247 QualType FromType = From->getType();
1248 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001249 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1250 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001251 ICS.setStandard();
1252 ICS.Standard.setAsIdentityConversion();
1253 ICS.Standard.setFromType(FromType);
1254 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001255
Douglas Gregor5ab11652010-04-17 22:01:05 +00001256 // We don't actually check at this point whether there is a valid
1257 // copy/move constructor, since overloading just assumes that it
1258 // exists. When we actually perform initialization, we'll find the
1259 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001260 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261
Douglas Gregor5ab11652010-04-17 22:01:05 +00001262 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001263 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001264 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor836a7e82010-08-11 02:15:33 +00001266 return ICS;
1267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001269 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1270 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001271 AllowObjCWritebackConversion,
1272 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001273}
1274
John McCall31168b02011-06-15 23:02:42 +00001275ImplicitConversionSequence
1276Sema::TryImplicitConversion(Expr *From, QualType ToType,
1277 bool SuppressUserConversions,
1278 bool AllowExplicit,
1279 bool InOverloadResolution,
1280 bool CStyle,
1281 bool AllowObjCWritebackConversion) {
1282 return clang::TryImplicitConversion(*this, From, ToType,
1283 SuppressUserConversions, AllowExplicit,
1284 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001285 AllowObjCWritebackConversion,
1286 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001287}
1288
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001289/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001290/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001291/// converted expression. Flavor is the kind of conversion we're
1292/// performing, used in the error message. If @p AllowExplicit,
1293/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001294ExprResult
1295Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001296 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001297 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001298 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001299}
1300
John Wiegley01296292011-04-08 18:41:53 +00001301ExprResult
1302Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001303 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001304 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001305 if (checkPlaceholderForOverload(*this, From))
1306 return ExprError();
1307
John McCall31168b02011-06-15 23:02:42 +00001308 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1309 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001310 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001311 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001312 if (getLangOpts().ObjC1)
1313 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1314 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001315 ICS = clang::TryImplicitConversion(*this, From, ToType,
1316 /*SuppressUserConversions=*/false,
1317 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001318 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001319 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001320 AllowObjCWritebackConversion,
1321 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001322 return PerformImplicitConversion(From, ToType, ICS, Action);
1323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324
1325/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001326/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001327bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1328 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001329 if (Context.hasSameUnqualifiedType(FromType, ToType))
1330 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331
John McCall991eb4b2010-12-21 00:44:39 +00001332 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1333 // where F adds one of the following at most once:
1334 // - a pointer
1335 // - a member pointer
1336 // - a block pointer
1337 CanQualType CanTo = Context.getCanonicalType(ToType);
1338 CanQualType CanFrom = Context.getCanonicalType(FromType);
1339 Type::TypeClass TyClass = CanTo->getTypeClass();
1340 if (TyClass != CanFrom->getTypeClass()) return false;
1341 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1342 if (TyClass == Type::Pointer) {
1343 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1344 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1345 } else if (TyClass == Type::BlockPointer) {
1346 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1347 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1348 } else if (TyClass == Type::MemberPointer) {
1349 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1350 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1351 } else {
1352 return false;
1353 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001354
John McCall991eb4b2010-12-21 00:44:39 +00001355 TyClass = CanTo->getTypeClass();
1356 if (TyClass != CanFrom->getTypeClass()) return false;
1357 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1358 return false;
1359 }
1360
1361 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1362 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1363 if (!EInfo.getNoReturn()) return false;
1364
1365 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1366 assert(QualType(FromFn, 0).isCanonical());
1367 if (QualType(FromFn, 0) != CanTo) return false;
1368
1369 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001370 return true;
1371}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001372
Douglas Gregor46188682010-05-18 22:42:18 +00001373/// \brief Determine whether the conversion from FromType to ToType is a valid
1374/// vector conversion.
1375///
1376/// \param ICK Will be set to the vector conversion kind, if this is a vector
1377/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001378static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001380 // We need at least one of these types to be a vector type to have a vector
1381 // conversion.
1382 if (!ToType->isVectorType() && !FromType->isVectorType())
1383 return false;
1384
1385 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001386 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001387 return false;
1388
1389 // There are no conversions between extended vector types, only identity.
1390 if (ToType->isExtVectorType()) {
1391 // There are no conversions between extended vector types other than the
1392 // identity conversion.
1393 if (FromType->isExtVectorType())
1394 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395
Douglas Gregor46188682010-05-18 22:42:18 +00001396 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001397 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001398 ICK = ICK_Vector_Splat;
1399 return true;
1400 }
1401 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001402
1403 // We can perform the conversion between vector types in the following cases:
1404 // 1)vector types are equivalent AltiVec and GCC vector types
1405 // 2)lax vector conversions are permitted and the vector types are of the
1406 // same size
1407 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001408 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1409 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001410 ICK = ICK_Vector_Conversion;
1411 return true;
1412 }
Douglas Gregor46188682010-05-18 22:42:18 +00001413 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001414
Douglas Gregor46188682010-05-18 22:42:18 +00001415 return false;
1416}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001418static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1419 bool InOverloadResolution,
1420 StandardConversionSequence &SCS,
1421 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001422
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001423/// IsStandardConversion - Determines whether there is a standard
1424/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1425/// expression From to the type ToType. Standard conversion sequences
1426/// only consider non-class types; for conversions that involve class
1427/// types, use TryImplicitConversion. If a conversion exists, SCS will
1428/// contain the standard conversion sequence required to perform this
1429/// conversion and this routine will return true. Otherwise, this
1430/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001431static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1432 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001433 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001434 bool CStyle,
1435 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001436 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001437
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001438 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001439 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001440 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001441 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001444 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001445 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001446 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001448 return false;
1449
Mike Stump11289f42009-09-09 15:08:12 +00001450 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001451 }
1452
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 // The first conversion can be an lvalue-to-rvalue conversion,
1454 // array-to-pointer conversion, or function-to-pointer conversion
1455 // (C++ 4p1).
1456
John McCall5c32be02010-08-24 20:38:10 +00001457 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001458 DeclAccessPair AccessPair;
1459 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001461 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001462 // We were able to resolve the address of the overloaded function,
1463 // so we can convert to the type of that function.
1464 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001465
1466 // we can sometimes resolve &foo<int> regardless of ToType, so check
1467 // if the type matches (identity) or we are converting to bool
1468 if (!S.Context.hasSameUnqualifiedType(
1469 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1470 QualType resultTy;
1471 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001472 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001473 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1474 // otherwise, only a boolean conversion is standard
1475 if (!ToType->isBooleanType())
1476 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478
Chandler Carruthffce2452011-03-29 08:08:18 +00001479 // Check if the "from" expression is taking the address of an overloaded
1480 // function and recompute the FromType accordingly. Take advantage of the
1481 // fact that non-static member functions *must* have such an address-of
1482 // expression.
1483 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1484 if (Method && !Method->isStatic()) {
1485 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1486 "Non-unary operator on non-static member address");
1487 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1488 == UO_AddrOf &&
1489 "Non-address-of operator on non-static member address");
1490 const Type *ClassType
1491 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1492 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001493 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1494 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1495 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001496 "Non-address-of operator for overloaded function expression");
1497 FromType = S.Context.getPointerType(FromType);
1498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499
Douglas Gregor980fb162010-04-29 18:24:40 +00001500 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001501 assert(S.Context.hasSameType(
1502 FromType,
1503 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001504 } else {
1505 return false;
1506 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001507 }
John McCall154a2fd2011-08-30 00:57:29 +00001508 // Lvalue-to-rvalue conversion (C++11 4.1):
1509 // A glvalue (3.10) of a non-function, non-array type T can
1510 // be converted to a prvalue.
1511 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001512 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001513 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001514 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001515 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001516
Douglas Gregorc79862f2012-04-12 17:51:55 +00001517 // C11 6.3.2.1p2:
1518 // ... if the lvalue has atomic type, the value has the non-atomic version
1519 // of the type of the lvalue ...
1520 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1521 FromType = Atomic->getValueType();
1522
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 // If T is a non-class type, the type of the rvalue is the
1524 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001525 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1526 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001528 } else if (FromType->isArrayType()) {
1529 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531
1532 // An lvalue or rvalue of type "array of N T" or "array of unknown
1533 // bound of T" can be converted to an rvalue of type "pointer to
1534 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001535 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536
John McCall5c32be02010-08-24 20:38:10 +00001537 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001538 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001539 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001540
1541 // For the purpose of ranking in overload resolution
1542 // (13.3.3.1.1), this conversion is considered an
1543 // array-to-pointer conversion followed by a qualification
1544 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 SCS.Second = ICK_Identity;
1546 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001547 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001548 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001549 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550 }
John McCall086a4642010-11-24 05:12:34 +00001551 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001552 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554
1555 // An lvalue of function type T can be converted to an rvalue of
1556 // type "pointer to T." The result is a pointer to the
1557 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001558 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001559 } else {
1560 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001561 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001562 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001563 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564
1565 // The second conversion can be an integral promotion, floating
1566 // point promotion, integral conversion, floating point conversion,
1567 // floating-integral conversion, pointer conversion,
1568 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001569 // For overloading in C, this can also be a "compatible-type"
1570 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001571 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001572 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001573 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574 // The unqualified versions of the types are the same: there's no
1575 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001577 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001578 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001579 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001581 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001582 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001585 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001586 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001587 SCS.Second = ICK_Complex_Promotion;
1588 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001589 } else if (ToType->isBooleanType() &&
1590 (FromType->isArithmeticType() ||
1591 FromType->isAnyPointerType() ||
1592 FromType->isBlockPointerType() ||
1593 FromType->isMemberPointerType() ||
1594 FromType->isNullPtrType())) {
1595 // Boolean conversions (C++ 4.12).
1596 SCS.Second = ICK_Boolean_Conversion;
1597 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001598 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001599 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001600 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001601 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001603 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001604 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001605 SCS.Second = ICK_Complex_Conversion;
1606 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001607 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1608 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001609 // Complex-real conversions (C99 6.3.1.7)
1610 SCS.Second = ICK_Complex_Real;
1611 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001612 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001613 // Floating point conversions (C++ 4.8).
1614 SCS.Second = ICK_Floating_Conversion;
1615 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001617 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001618 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001619 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001620 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001622 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001623 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001624 SCS.Second = ICK_Block_Pointer_Conversion;
1625 } else if (AllowObjCWritebackConversion &&
1626 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1627 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001628 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1629 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001630 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001631 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001632 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001633 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001635 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001637 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001638 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001639 SCS.Second = SecondICK;
1640 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001641 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001642 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001645 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001646 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001647 // Treat a conversion that strips "noreturn" as an identity conversion.
1648 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001649 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1650 InOverloadResolution,
1651 SCS, CStyle)) {
1652 SCS.Second = ICK_TransparentUnionConversion;
1653 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001654 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1655 CStyle)) {
1656 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001657 // appropriately.
1658 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001659 } else if (ToType->isEventT() &&
1660 From->isIntegerConstantExpr(S.getASTContext()) &&
1661 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1662 SCS.Second = ICK_Zero_Event_Conversion;
1663 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 } else {
1665 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001668 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001670 QualType CanonFrom;
1671 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001673 bool ObjCLifetimeConversion;
1674 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1675 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001677 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001679 CanonFrom = S.Context.getCanonicalType(FromType);
1680 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681 } else {
1682 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 SCS.Third = ICK_Identity;
1684
Mike Stump11289f42009-09-09 15:08:12 +00001685 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001686 // [...] Any difference in top-level cv-qualification is
1687 // subsumed by the initialization itself and does not constitute
1688 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001689 CanonFrom = S.Context.getCanonicalType(FromType);
1690 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001692 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001693 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001694 FromType = ToType;
1695 CanonFrom = CanonTo;
1696 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001698 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699
1700 // If we have not converted the argument type to the parameter type,
1701 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001702 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001703 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001705 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001707
1708static bool
1709IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1710 QualType &ToType,
1711 bool InOverloadResolution,
1712 StandardConversionSequence &SCS,
1713 bool CStyle) {
1714
1715 const RecordType *UT = ToType->getAsUnionType();
1716 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1717 return false;
1718 // The field to initialize within the transparent union.
1719 RecordDecl *UD = UT->getDecl();
1720 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001721 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001722 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1723 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001724 ToType = it->getType();
1725 return true;
1726 }
1727 }
1728 return false;
1729}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730
1731/// IsIntegralPromotion - Determines whether the conversion from the
1732/// expression From (whose potentially-adjusted type is FromType) to
1733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1734/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001736 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001737 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001738 if (!To) {
1739 return false;
1740 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001741
1742 // An rvalue of type char, signed char, unsigned char, short int, or
1743 // unsigned short int can be converted to an rvalue of type int if
1744 // int can represent all the values of the source type; otherwise,
1745 // the source rvalue can be converted to an rvalue of type unsigned
1746 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1748 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749 if (// We can promote any signed, promotable integer type to an int
1750 (FromType->isSignedIntegerType() ||
1751 // We can promote any unsigned integer type whose size is
1752 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001753 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001755 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001756 }
1757
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 return To->getKind() == BuiltinType::UInt;
1759 }
1760
Richard Smithb9c5a602012-09-13 21:18:54 +00001761 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 // A prvalue of an unscoped enumeration type whose underlying type is not
1763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1764 // following types that can represent all the values of the enumeration
1765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1766 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001767 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // with lowest integer conversion rank (4.13) greater than the rank of long
1771 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001772 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001773 // C++11 [conv.prom]p4:
1774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1775 // can be converted to a prvalue of its underlying type. Moreover, if
1776 // integral promotion can be applied to its underlying type, a prvalue of an
1777 // unscoped enumeration type whose underlying type is fixed can also be
1778 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001779 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1781 // provided for a scoped enumeration.
1782 if (FromEnumType->getDecl()->isScoped())
1783 return false;
1784
Richard Smithb9c5a602012-09-13 21:18:54 +00001785 // We can perform an integral promotion to the underlying type of the enum,
1786 // even if that's not the promoted type.
1787 if (FromEnumType->getDecl()->isFixed()) {
1788 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1789 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1790 IsIntegralPromotion(From, Underlying, ToType);
1791 }
1792
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001793 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001794 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001795 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001796 return Context.hasSameUnqualifiedType(ToType,
1797 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001798 }
John McCall56774992009-12-09 09:09:27 +00001799
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001800 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001801 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1802 // to an rvalue a prvalue of the first of the following types that can
1803 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001804 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001806 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001808 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001810 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 // Determine whether the type we're converting from is signed or
1812 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001813 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001816 // The types we'll try to promote to, in the appropriate
1817 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001818 QualType PromoteTypes[6] = {
1819 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001820 Context.LongTy, Context.UnsignedLongTy ,
1821 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001823 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1825 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001826 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1828 // We found the type that we can promote to. If this is the
1829 // type we wanted, we have a promotion. Otherwise, no
1830 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001831 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832 }
1833 }
1834 }
1835
1836 // An rvalue for an integral bit-field (9.6) can be converted to an
1837 // rvalue of type int if int can represent all the values of the
1838 // bit-field; otherwise, it can be converted to unsigned int if
1839 // unsigned int can represent all the values of the bit-field. If
1840 // the bit-field is larger yet, no integral promotion applies to
1841 // it. If the bit-field has an enumerated type, it is treated as any
1842 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001843 // FIXME: We should delay checking of bit-fields until we actually perform the
1844 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001845 using llvm::APSInt;
1846 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001847 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001848 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001849 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001850 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1851 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1852 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001854 // Are we promoting to an int from a bitfield that fits in an int?
1855 if (BitWidth < ToSize ||
1856 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1857 return To->getKind() == BuiltinType::Int;
1858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001860 // Are we promoting to an unsigned int from an unsigned bitfield
1861 // that fits into an unsigned int?
1862 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1863 return To->getKind() == BuiltinType::UInt;
1864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001866 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001867 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001868 }
Mike Stump11289f42009-09-09 15:08:12 +00001869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870 // An rvalue of type bool can be converted to an rvalue of type int,
1871 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001872 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001873 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001874 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001875
1876 return false;
1877}
1878
1879/// IsFloatingPointPromotion - Determines whether the conversion from
1880/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1881/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001882bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001883 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1884 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001885 /// An rvalue of type float can be converted to an rvalue of type
1886 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001887 if (FromBuiltin->getKind() == BuiltinType::Float &&
1888 ToBuiltin->getKind() == BuiltinType::Double)
1889 return true;
1890
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001891 // C99 6.3.1.5p1:
1892 // When a float is promoted to double or long double, or a
1893 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001894 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001895 (FromBuiltin->getKind() == BuiltinType::Float ||
1896 FromBuiltin->getKind() == BuiltinType::Double) &&
1897 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1898 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001899
1900 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001901 if (!getLangOpts().NativeHalfType &&
1902 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001903 ToBuiltin->getKind() == BuiltinType::Float)
1904 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001905 }
1906
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001907 return false;
1908}
1909
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001910/// \brief Determine if a conversion is a complex promotion.
1911///
1912/// A complex promotion is defined as a complex -> complex conversion
1913/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001914/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001915bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001916 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001917 if (!FromComplex)
1918 return false;
1919
John McCall9dd450b2009-09-21 23:43:11 +00001920 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001921 if (!ToComplex)
1922 return false;
1923
1924 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001925 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001926 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001927 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001928}
1929
Douglas Gregor237f96c2008-11-26 23:31:11 +00001930/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1931/// the pointer type FromPtr to a pointer to type ToPointee, with the
1932/// same type qualifiers as FromPtr has on its pointee type. ToType,
1933/// if non-empty, will be a pointer to ToType that may or may not have
1934/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001935///
Mike Stump11289f42009-09-09 15:08:12 +00001936static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001937BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001939 ASTContext &Context,
1940 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001941 assert((FromPtr->getTypeClass() == Type::Pointer ||
1942 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1943 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
John McCall31168b02011-06-15 23:02:42 +00001945 /// Conversions to 'id' subsume cv-qualifier conversions.
1946 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001947 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
1949 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001950 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001951 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001952 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001953
John McCall31168b02011-06-15 23:02:42 +00001954 if (StripObjCLifetime)
1955 Quals.removeObjCLifetime();
1956
Mike Stump11289f42009-09-09 15:08:12 +00001957 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001958 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001959 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001960 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001961 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001962
1963 // Build a pointer to ToPointee. It has the right qualifiers
1964 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001965 if (isa<ObjCObjectPointerType>(ToType))
1966 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 return Context.getPointerType(ToPointee);
1968 }
1969
1970 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001971 QualType QualifiedCanonToPointee
1972 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001974 if (isa<ObjCObjectPointerType>(ToType))
1975 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1976 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001977}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978
Mike Stump11289f42009-09-09 15:08:12 +00001979static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001980 bool InOverloadResolution,
1981 ASTContext &Context) {
1982 // Handle value-dependent integral null pointer constants correctly.
1983 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1984 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001985 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001986 return !InOverloadResolution;
1987
Douglas Gregor56751b52009-09-25 04:25:58 +00001988 return Expr->isNullPointerConstant(Context,
1989 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1990 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001991}
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001993/// IsPointerConversion - Determines whether the conversion of the
1994/// expression From, which has the (possibly adjusted) type FromType,
1995/// can be converted to the type ToType via a pointer conversion (C++
1996/// 4.10). If so, returns true and places the converted type (that
1997/// might differ from ToType in its cv-qualifiers at some level) into
1998/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001999///
Douglas Gregora29dc052008-11-27 01:19:21 +00002000/// This routine also supports conversions to and from block pointers
2001/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2002/// pointers to interfaces. FIXME: Once we've determined the
2003/// appropriate overloading rules for Objective-C, we may want to
2004/// split the Objective-C checks into a different routine; however,
2005/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002006/// conversions, so for now they live here. IncompatibleObjC will be
2007/// set if the conversion is an allowed Objective-C conversion that
2008/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002010 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002011 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002012 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002013 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002014 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2015 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002016 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002017
Mike Stump11289f42009-09-09 15:08:12 +00002018 // Conversion from a null pointer constant to any Objective-C pointer type.
2019 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002020 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002021 ConvertedType = ToType;
2022 return true;
2023 }
2024
Douglas Gregor231d1c62008-11-27 00:15:41 +00002025 // Blocks: Block pointers can be converted to void*.
2026 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002027 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002028 ConvertedType = ToType;
2029 return true;
2030 }
2031 // Blocks: A null pointer constant can be converted to a block
2032 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002033 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002034 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002035 ConvertedType = ToType;
2036 return true;
2037 }
2038
Sebastian Redl576fd422009-05-10 18:38:11 +00002039 // If the left-hand-side is nullptr_t, the right side can be a null
2040 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002041 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
2046
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002047 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002048 if (!ToTypePtr)
2049 return false;
2050
2051 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002052 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053 ConvertedType = ToType;
2054 return true;
2055 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002056
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002057 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002058 // , including objective-c pointers.
2059 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002060 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002061 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002062 ConvertedType = BuildSimilarlyQualifiedPointerType(
2063 FromType->getAs<ObjCObjectPointerType>(),
2064 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002065 ToType, Context);
2066 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002067 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002069 if (!FromTypePtr)
2070 return false;
2071
2072 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002073
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002075 // pointer conversion, so don't do all of the work below.
2076 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2077 return false;
2078
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002079 // An rvalue of type "pointer to cv T," where T is an object type,
2080 // can be converted to an rvalue of type "pointer to cv void" (C++
2081 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002082 if (FromPointeeType->isIncompleteOrObjectType() &&
2083 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002085 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002086 ToType, Context,
2087 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002088 return true;
2089 }
2090
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002091 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002092 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002093 ToPointeeType->isVoidType()) {
2094 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2095 ToPointeeType,
2096 ToType, Context);
2097 return true;
2098 }
2099
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002100 // When we're overloading in C, we allow a special kind of pointer
2101 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002102 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002103 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002104 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002105 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002106 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002107 return true;
2108 }
2109
Douglas Gregor5c407d92008-10-23 00:40:37 +00002110 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002111 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002112 // An rvalue of type "pointer to cv D," where D is a class type,
2113 // can be converted to an rvalue of type "pointer to cv B," where
2114 // B is a base class (clause 10) of D. If B is an inaccessible
2115 // (clause 11) or ambiguous (10.2) base class of D, a program that
2116 // necessitates this conversion is ill-formed. The result of the
2117 // conversion is a pointer to the base class sub-object of the
2118 // derived class object. The null pointer value is converted to
2119 // the null pointer value of the destination type.
2120 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002121 // Note that we do not check for ambiguity or inaccessibility
2122 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002123 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002124 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002125 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002126 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002127 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002129 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002130 ToType, Context);
2131 return true;
2132 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002133
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002134 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2135 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2137 ToPointeeType,
2138 ToType, Context);
2139 return true;
2140 }
2141
Douglas Gregora119f102008-12-19 19:13:09 +00002142 return false;
2143}
Douglas Gregoraec25842011-04-26 23:16:46 +00002144
2145/// \brief Adopt the given qualifiers for the given type.
2146static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2147 Qualifiers TQs = T.getQualifiers();
2148
2149 // Check whether qualifiers already match.
2150 if (TQs == Qs)
2151 return T;
2152
2153 if (Qs.compatiblyIncludes(TQs))
2154 return Context.getQualifiedType(T, Qs);
2155
2156 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2157}
Douglas Gregora119f102008-12-19 19:13:09 +00002158
2159/// isObjCPointerConversion - Determines whether this is an
2160/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2161/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002162bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002163 QualType& ConvertedType,
2164 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002165 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002166 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
Douglas Gregoraec25842011-04-26 23:16:46 +00002168 // The set of qualifiers on the type we're converting from.
2169 Qualifiers FromQualifiers = FromType.getQualifiers();
2170
Steve Naroff7cae42b2009-07-10 23:34:53 +00002171 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002172 const ObjCObjectPointerType* ToObjCPtr =
2173 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002174 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002175 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002176
Steve Naroff7cae42b2009-07-10 23:34:53 +00002177 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002178 // If the pointee types are the same (ignoring qualifications),
2179 // then this is not a pointer conversion.
2180 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2181 FromObjCPtr->getPointeeType()))
2182 return false;
2183
Douglas Gregoraec25842011-04-26 23:16:46 +00002184 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002185 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002187 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002189 return true;
2190 }
2191 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002192 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002193 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002194 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002195 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002197 return true;
2198 }
2199 // Objective C++: We're able to convert from a pointer to an
2200 // interface to a pointer to a different interface.
2201 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002202 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2203 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002204 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002205 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2206 FromObjCPtr->getPointeeType()))
2207 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002209 ToObjCPtr->getPointeeType(),
2210 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002212 return true;
2213 }
2214
2215 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2216 // Okay: this is some kind of implicit downcast of Objective-C
2217 // interfaces, which is permitted. However, we're going to
2218 // complain about it.
2219 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002221 ToObjCPtr->getPointeeType(),
2222 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002224 return true;
2225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002227 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002228 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002229 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002230 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002231 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002232 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002233 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002234 // to a block pointer type.
2235 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002237 return true;
2238 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002239 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002241 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002242 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002244 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002245 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002246 return true;
2247 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002248 else
Douglas Gregora119f102008-12-19 19:13:09 +00002249 return false;
2250
Douglas Gregor033f56d2008-12-23 00:53:59 +00002251 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002252 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002253 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002254 else if (const BlockPointerType *FromBlockPtr =
2255 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002256 FromPointeeType = FromBlockPtr->getPointeeType();
2257 else
Douglas Gregora119f102008-12-19 19:13:09 +00002258 return false;
2259
Douglas Gregora119f102008-12-19 19:13:09 +00002260 // If we have pointers to pointers, recursively check whether this
2261 // is an Objective-C conversion.
2262 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2264 IncompatibleObjC)) {
2265 // We always complain about this conversion.
2266 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002267 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002268 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002269 return true;
2270 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002271 // Allow conversion of pointee being objective-c pointer to another one;
2272 // as in I* to id.
2273 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2274 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2275 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2276 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002277
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002278 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002279 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002280 return true;
2281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282
Douglas Gregor033f56d2008-12-23 00:53:59 +00002283 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002284 // differences in the argument and result types are in Objective-C
2285 // pointer conversions. If so, we permit the conversion (but
2286 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002287 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002288 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002289 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002290 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002291 if (FromFunctionType && ToFunctionType) {
2292 // If the function types are exactly the same, this isn't an
2293 // Objective-C pointer conversion.
2294 if (Context.getCanonicalType(FromPointeeType)
2295 == Context.getCanonicalType(ToPointeeType))
2296 return false;
2297
2298 // Perform the quick checks that will tell us whether these
2299 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002300 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002301 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2302 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2303 return false;
2304
2305 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002306 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2307 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002308 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002309 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2310 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002311 ConvertedType, IncompatibleObjC)) {
2312 // Okay, we have an Objective-C pointer conversion.
2313 HasObjCConversion = true;
2314 } else {
2315 // Function types are too different. Abort.
2316 return false;
2317 }
Mike Stump11289f42009-09-09 15:08:12 +00002318
Douglas Gregora119f102008-12-19 19:13:09 +00002319 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002320 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002321 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002322 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2323 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002324 if (Context.getCanonicalType(FromArgType)
2325 == Context.getCanonicalType(ToArgType)) {
2326 // Okay, the types match exactly. Nothing to do.
2327 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2328 ConvertedType, IncompatibleObjC)) {
2329 // Okay, we have an Objective-C pointer conversion.
2330 HasObjCConversion = true;
2331 } else {
2332 // Argument types are too different. Abort.
2333 return false;
2334 }
2335 }
2336
2337 if (HasObjCConversion) {
2338 // We had an Objective-C conversion. Allow this pointer
2339 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002340 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002341 IncompatibleObjC = true;
2342 return true;
2343 }
2344 }
2345
Sebastian Redl72b597d2009-01-25 19:43:20 +00002346 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002347}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348
John McCall31168b02011-06-15 23:02:42 +00002349/// \brief Determine whether this is an Objective-C writeback conversion,
2350/// used for parameter passing when performing automatic reference counting.
2351///
2352/// \param FromType The type we're converting form.
2353///
2354/// \param ToType The type we're converting to.
2355///
2356/// \param ConvertedType The type that will be produced after applying
2357/// this conversion.
2358bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2359 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002360 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002361 Context.hasSameUnqualifiedType(FromType, ToType))
2362 return false;
2363
2364 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2365 QualType ToPointee;
2366 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2367 ToPointee = ToPointer->getPointeeType();
2368 else
2369 return false;
2370
2371 Qualifiers ToQuals = ToPointee.getQualifiers();
2372 if (!ToPointee->isObjCLifetimeType() ||
2373 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002374 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002375 return false;
2376
2377 // Argument must be a pointer to __strong to __weak.
2378 QualType FromPointee;
2379 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2380 FromPointee = FromPointer->getPointeeType();
2381 else
2382 return false;
2383
2384 Qualifiers FromQuals = FromPointee.getQualifiers();
2385 if (!FromPointee->isObjCLifetimeType() ||
2386 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2387 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2388 return false;
2389
2390 // Make sure that we have compatible qualifiers.
2391 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2392 if (!ToQuals.compatiblyIncludes(FromQuals))
2393 return false;
2394
2395 // Remove qualifiers from the pointee type we're converting from; they
2396 // aren't used in the compatibility check belong, and we'll be adding back
2397 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2398 FromPointee = FromPointee.getUnqualifiedType();
2399
2400 // The unqualified form of the pointee types must be compatible.
2401 ToPointee = ToPointee.getUnqualifiedType();
2402 bool IncompatibleObjC;
2403 if (Context.typesAreCompatible(FromPointee, ToPointee))
2404 FromPointee = ToPointee;
2405 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2406 IncompatibleObjC))
2407 return false;
2408
2409 /// \brief Construct the type we're converting to, which is a pointer to
2410 /// __autoreleasing pointee.
2411 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2412 ConvertedType = Context.getPointerType(FromPointee);
2413 return true;
2414}
2415
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002416bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2417 QualType& ConvertedType) {
2418 QualType ToPointeeType;
2419 if (const BlockPointerType *ToBlockPtr =
2420 ToType->getAs<BlockPointerType>())
2421 ToPointeeType = ToBlockPtr->getPointeeType();
2422 else
2423 return false;
2424
2425 QualType FromPointeeType;
2426 if (const BlockPointerType *FromBlockPtr =
2427 FromType->getAs<BlockPointerType>())
2428 FromPointeeType = FromBlockPtr->getPointeeType();
2429 else
2430 return false;
2431 // We have pointer to blocks, check whether the only
2432 // differences in the argument and result types are in Objective-C
2433 // pointer conversions. If so, we permit the conversion.
2434
2435 const FunctionProtoType *FromFunctionType
2436 = FromPointeeType->getAs<FunctionProtoType>();
2437 const FunctionProtoType *ToFunctionType
2438 = ToPointeeType->getAs<FunctionProtoType>();
2439
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002440 if (!FromFunctionType || !ToFunctionType)
2441 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002442
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002443 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002444 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002445
2446 // Perform the quick checks that will tell us whether these
2447 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002448 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002449 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2450 return false;
2451
2452 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2453 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2454 if (FromEInfo != ToEInfo)
2455 return false;
2456
2457 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002458 if (Context.hasSameType(FromFunctionType->getReturnType(),
2459 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002460 // Okay, the types match exactly. Nothing to do.
2461 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002462 QualType RHS = FromFunctionType->getReturnType();
2463 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002464 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002465 !RHS.hasQualifiers() && LHS.hasQualifiers())
2466 LHS = LHS.getUnqualifiedType();
2467
2468 if (Context.hasSameType(RHS,LHS)) {
2469 // OK exact match.
2470 } else if (isObjCPointerConversion(RHS, LHS,
2471 ConvertedType, IncompatibleObjC)) {
2472 if (IncompatibleObjC)
2473 return false;
2474 // Okay, we have an Objective-C pointer conversion.
2475 }
2476 else
2477 return false;
2478 }
2479
2480 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002481 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002482 ArgIdx != NumArgs; ++ArgIdx) {
2483 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002484 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2485 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002486 if (Context.hasSameType(FromArgType, ToArgType)) {
2487 // Okay, the types match exactly. Nothing to do.
2488 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2489 ConvertedType, IncompatibleObjC)) {
2490 if (IncompatibleObjC)
2491 return false;
2492 // Okay, we have an Objective-C pointer conversion.
2493 } else
2494 // Argument types are too different. Abort.
2495 return false;
2496 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002497 if (LangOpts.ObjCAutoRefCount &&
2498 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2499 ToFunctionType))
2500 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002501
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002502 ConvertedType = ToType;
2503 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002504}
2505
Richard Trieucaff2472011-11-23 22:32:32 +00002506enum {
2507 ft_default,
2508 ft_different_class,
2509 ft_parameter_arity,
2510 ft_parameter_mismatch,
2511 ft_return_type,
2512 ft_qualifer_mismatch
2513};
2514
2515/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2516/// function types. Catches different number of parameter, mismatch in
2517/// parameter types, and different return types.
2518void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2519 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002520 // If either type is not valid, include no extra info.
2521 if (FromType.isNull() || ToType.isNull()) {
2522 PDiag << ft_default;
2523 return;
2524 }
2525
Richard Trieucaff2472011-11-23 22:32:32 +00002526 // Get the function type from the pointers.
2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2529 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002530 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2532 << QualType(FromMember->getClass(), 0);
2533 return;
2534 }
2535 FromType = FromMember->getPointeeType();
2536 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002537 }
2538
Richard Trieu96ed5b62011-12-13 23:19:45 +00002539 if (FromType->isPointerType())
2540 FromType = FromType->getPointeeType();
2541 if (ToType->isPointerType())
2542 ToType = ToType->getPointeeType();
2543
2544 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002545 FromType = FromType.getNonReferenceType();
2546 ToType = ToType.getNonReferenceType();
2547
Richard Trieucaff2472011-11-23 22:32:32 +00002548 // Don't print extra info for non-specialized template functions.
2549 if (FromType->isInstantiationDependentType() &&
2550 !FromType->getAs<TemplateSpecializationType>()) {
2551 PDiag << ft_default;
2552 return;
2553 }
2554
Richard Trieu96ed5b62011-12-13 23:19:45 +00002555 // No extra info for same types.
2556 if (Context.hasSameType(FromType, ToType)) {
2557 PDiag << ft_default;
2558 return;
2559 }
2560
Richard Trieucaff2472011-11-23 22:32:32 +00002561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2562 *ToFunction = ToType->getAs<FunctionProtoType>();
2563
2564 // Both types need to be function types.
2565 if (!FromFunction || !ToFunction) {
2566 PDiag << ft_default;
2567 return;
2568 }
2569
Alp Toker9cacbab2014-01-20 20:26:09 +00002570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2571 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2572 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002573 return;
2574 }
2575
2576 // Handle different parameter types.
2577 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002579 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002580 << ToFunction->getParamType(ArgPos)
2581 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002582 return;
2583 }
2584
2585 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002586 if (!Context.hasSameType(FromFunction->getReturnType(),
2587 ToFunction->getReturnType())) {
2588 PDiag << ft_return_type << ToFunction->getReturnType()
2589 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002590 return;
2591 }
2592
2593 unsigned FromQuals = FromFunction->getTypeQuals(),
2594 ToQuals = ToFunction->getTypeQuals();
2595 if (FromQuals != ToQuals) {
2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2597 return;
2598 }
2599
2600 // Unable to find a difference, so add no extra info.
2601 PDiag << ft_default;
2602}
2603
Alp Toker9cacbab2014-01-20 20:26:09 +00002604/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002605/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002606/// they have same number of arguments. If the parameters are different,
2607/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002608bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2609 const FunctionProtoType *NewType,
2610 unsigned *ArgPos) {
2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2612 N = NewType->param_type_begin(),
2613 E = OldType->param_type_end();
2614 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002615 if (!Context.hasSameType(O->getUnqualifiedType(),
2616 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002617 if (ArgPos)
2618 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002619 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002620 }
2621 }
2622 return true;
2623}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002624
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625/// CheckPointerConversion - Check the pointer conversion from the
2626/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002627/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002628/// conversions for which IsPointerConversion has already returned
2629/// true. It returns true and produces a diagnostic if there was an
2630/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002631bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002632 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002633 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002634 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002635 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002637
John McCall8cb679e2010-11-15 09:13:47 +00002638 Kind = CK_BitCast;
2639
David Blaikie1c7c8f72012-08-08 17:33:31 +00002640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002642 Expr::NPCK_ZeroExpression) {
2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2644 DiagRuntimeBehavior(From->getExprLoc(), From,
2645 PDiag(diag::warn_impcast_bool_to_null_pointer)
2646 << ToType << From->getSourceRange());
2647 else if (!isUnevaluatedContext())
2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2649 << ToType << From->getSourceRange();
2650 }
John McCall9320b872011-09-09 05:25:32 +00002651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002653 QualType FromPointeeType = FromPtrType->getPointeeType(),
2654 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002655
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002658 // We must have a derived-to-base conversion. Check an
2659 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2661 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002662 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002663 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002664 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002666 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002667 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002668 }
2669 }
John McCall9320b872011-09-09 05:25:32 +00002670 } else if (const ObjCObjectPointerType *ToPtrType =
2671 ToType->getAs<ObjCObjectPointerType>()) {
2672 if (const ObjCObjectPointerType *FromPtrType =
2673 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002674 // Objective-C++ conversions are always okay.
2675 // FIXME: We should have a different class of conversions for the
2676 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002677 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002678 return false;
John McCall9320b872011-09-09 05:25:32 +00002679 } else if (FromType->isBlockPointerType()) {
2680 Kind = CK_BlockPointerToObjCPointerCast;
2681 } else {
2682 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002683 }
John McCall9320b872011-09-09 05:25:32 +00002684 } else if (ToType->isBlockPointerType()) {
2685 if (!FromType->isBlockPointerType())
2686 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002687 }
John McCall8cb679e2010-11-15 09:13:47 +00002688
2689 // We shouldn't fall into this case unless it's valid for other
2690 // reasons.
2691 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2692 Kind = CK_NullToPointer;
2693
Douglas Gregor39c16d42008-10-24 04:54:22 +00002694 return false;
2695}
2696
Sebastian Redl72b597d2009-01-25 19:43:20 +00002697/// IsMemberPointerConversion - Determines whether the conversion of the
2698/// expression From, which has the (possibly adjusted) type FromType, can be
2699/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2700/// If so, returns true and places the converted type (that might differ from
2701/// ToType in its cv-qualifiers at some level) into ConvertedType.
2702bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002704 bool InOverloadResolution,
2705 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002706 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002707 if (!ToTypePtr)
2708 return false;
2709
2710 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 if (From->isNullPointerConstant(Context,
2712 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2713 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714 ConvertedType = ToType;
2715 return true;
2716 }
2717
2718 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002719 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720 if (!FromTypePtr)
2721 return false;
2722
2723 // A pointer to member of B can be converted to a pointer to member of D,
2724 // where D is derived from B (C++ 4.11p2).
2725 QualType FromClass(FromTypePtr->getClass(), 0);
2726 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002728 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002729 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002730 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002731 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2732 ToClass.getTypePtr());
2733 return true;
2734 }
2735
2736 return false;
2737}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739/// CheckMemberPointerConversion - Check the member pointer conversion from the
2740/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002741/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002742/// for which IsMemberPointerConversion has already returned true. It returns
2743/// true and produces a diagnostic if there was an error, or returns false
2744/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002745bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002746 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002747 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002748 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002750 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002751 if (!FromPtrType) {
2752 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002754 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002755 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002756 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002757 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002758 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002759
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002760 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002761 assert(ToPtrType && "No member pointer cast has a target type "
2762 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002763
Sebastian Redled8f2002009-01-28 18:33:18 +00002764 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2765 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002766
Sebastian Redled8f2002009-01-28 18:33:18 +00002767 // FIXME: What about dependent types?
2768 assert(FromClass->isRecordType() && "Pointer into non-class.");
2769 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002772 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002773 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2774 assert(DerivationOkay &&
2775 "Should not have been called if derivation isn't OK.");
2776 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002777
Sebastian Redled8f2002009-01-28 18:33:18 +00002778 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2779 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002780 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2781 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2782 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2783 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002784 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002785
Douglas Gregor89ee6822009-02-28 01:32:25 +00002786 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002787 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2788 << FromClass << ToClass << QualType(VBase, 0)
2789 << From->getSourceRange();
2790 return true;
2791 }
2792
John McCall5b0829a2010-02-10 09:31:12 +00002793 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002794 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2795 Paths.front(),
2796 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002797
Anders Carlssond7923c62009-08-22 23:33:40 +00002798 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002799 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002800 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002801 return false;
2802}
2803
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002804/// Determine whether the lifetime conversion between the two given
2805/// qualifiers sets is nontrivial.
2806static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2807 Qualifiers ToQuals) {
2808 // Converting anything to const __unsafe_unretained is trivial.
2809 if (ToQuals.hasConst() &&
2810 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2811 return false;
2812
2813 return true;
2814}
2815
Douglas Gregor9a657932008-10-21 23:43:52 +00002816/// IsQualificationConversion - Determines whether the conversion from
2817/// an rvalue of type FromType to ToType is a qualification conversion
2818/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002819///
2820/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2821/// when the qualification conversion involves a change in the Objective-C
2822/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002823bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002825 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002826 FromType = Context.getCanonicalType(FromType);
2827 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002828 ObjCLifetimeConversion = false;
2829
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 // If FromType and ToType are the same type, this is not a
2831 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002832 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002834
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // (C++ 4.4p4):
2836 // A conversion can add cv-qualifiers at levels other than the first
2837 // in multi-level pointers, subject to the following rules: [...]
2838 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002839 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002840 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 // Within each iteration of the loop, we check the qualifiers to
2842 // determine if this still looks like a qualification
2843 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002844 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002845 // until there are no more pointers or pointers-to-members left to
2846 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002847 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002848
Douglas Gregor90609aa2011-04-25 18:40:17 +00002849 Qualifiers FromQuals = FromType.getQualifiers();
2850 Qualifiers ToQuals = ToType.getQualifiers();
2851
John McCall31168b02011-06-15 23:02:42 +00002852 // Objective-C ARC:
2853 // Check Objective-C lifetime conversions.
2854 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2855 UnwrappedAnyPointer) {
2856 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002857 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2858 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002859 FromQuals.removeObjCLifetime();
2860 ToQuals.removeObjCLifetime();
2861 } else {
2862 // Qualification conversions cannot cast between different
2863 // Objective-C lifetime qualifiers.
2864 return false;
2865 }
2866 }
2867
Douglas Gregorf30053d2011-05-08 06:09:53 +00002868 // Allow addition/removal of GC attributes but not changing GC attributes.
2869 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2870 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2871 FromQuals.removeObjCGCAttr();
2872 ToQuals.removeObjCGCAttr();
2873 }
2874
Douglas Gregor9a657932008-10-21 23:43:52 +00002875 // -- for every j > 0, if const is in cv 1,j then const is in cv
2876 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002877 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002878 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002879
Douglas Gregor9a657932008-10-21 23:43:52 +00002880 // -- if the cv 1,j and cv 2,j are different, then const is in
2881 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002882 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002883 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002884 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor9a657932008-10-21 23:43:52 +00002886 // Keep track of whether all prior cv-qualifiers in the "to" type
2887 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002888 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002889 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002890 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002891
2892 // We are left with FromType and ToType being the pointee types
2893 // after unwrapping the original FromType and ToType the same number
2894 // of types. If we unwrapped any pointers, and if FromType and
2895 // ToType have the same unqualified type (since we checked
2896 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002897 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002898}
2899
Douglas Gregorc79862f2012-04-12 17:51:55 +00002900/// \brief - Determine whether this is a conversion from a scalar type to an
2901/// atomic type.
2902///
2903/// If successful, updates \c SCS's second and third steps in the conversion
2904/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002905static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2906 bool InOverloadResolution,
2907 StandardConversionSequence &SCS,
2908 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002909 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2910 if (!ToAtomic)
2911 return false;
2912
2913 StandardConversionSequence InnerSCS;
2914 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2915 InOverloadResolution, InnerSCS,
2916 CStyle, /*AllowObjCWritebackConversion=*/false))
2917 return false;
2918
2919 SCS.Second = InnerSCS.Second;
2920 SCS.setToType(1, InnerSCS.getToType(1));
2921 SCS.Third = InnerSCS.Third;
2922 SCS.QualificationIncludesObjCLifetime
2923 = InnerSCS.QualificationIncludesObjCLifetime;
2924 SCS.setToType(2, InnerSCS.getToType(2));
2925 return true;
2926}
2927
Sebastian Redle5417162012-03-27 18:33:03 +00002928static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2929 CXXConstructorDecl *Constructor,
2930 QualType Type) {
2931 const FunctionProtoType *CtorType =
2932 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002933 if (CtorType->getNumParams() > 0) {
2934 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002935 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2936 return true;
2937 }
2938 return false;
2939}
2940
Sebastian Redl82ace982012-02-11 23:51:08 +00002941static OverloadingResult
2942IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2943 CXXRecordDecl *To,
2944 UserDefinedConversionSequence &User,
2945 OverloadCandidateSet &CandidateSet,
2946 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002947 DeclContext::lookup_result R = S.LookupConstructors(To);
2948 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002949 Con != ConEnd; ++Con) {
2950 NamedDecl *D = *Con;
2951 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2952
2953 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002955 FunctionTemplateDecl *ConstructorTmpl
2956 = dyn_cast<FunctionTemplateDecl>(D);
2957 if (ConstructorTmpl)
2958 Constructor
2959 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2960 else
2961 Constructor = cast<CXXConstructorDecl>(D);
2962
2963 bool Usable = !Constructor->isInvalidDecl() &&
2964 S.isInitListConstructor(Constructor) &&
2965 (AllowExplicit || !Constructor->isExplicit());
2966 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002967 // If the first argument is (a reference to) the target type,
2968 // suppress conversions.
2969 bool SuppressUserConversions =
2970 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002971 if (ConstructorTmpl)
2972 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002973 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002974 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002975 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002976 else
2977 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002978 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002979 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002980 }
2981 }
2982
2983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984
2985 OverloadCandidateSet::iterator Best;
2986 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2987 case OR_Success: {
2988 // Record the standard conversion we used and the conversion function.
2989 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002990 QualType ThisType = Constructor->getThisType(S.Context);
2991 // Initializer lists don't have conversions as such.
2992 User.Before.setAsIdentityConversion();
2993 User.HadMultipleCandidates = HadMultipleCandidates;
2994 User.ConversionFunction = Constructor;
2995 User.FoundConversionFunction = Best->FoundDecl;
2996 User.After.setAsIdentityConversion();
2997 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2998 User.After.setAllToTypes(ToType);
2999 return OR_Success;
3000 }
3001
3002 case OR_No_Viable_Function:
3003 return OR_No_Viable_Function;
3004 case OR_Deleted:
3005 return OR_Deleted;
3006 case OR_Ambiguous:
3007 return OR_Ambiguous;
3008 }
3009
3010 llvm_unreachable("Invalid OverloadResult!");
3011}
3012
Douglas Gregor576e98c2009-01-30 23:27:23 +00003013/// Determines whether there is a user-defined conversion sequence
3014/// (C++ [over.ics.user]) that converts expression From to the type
3015/// ToType. If such a conversion exists, User will contain the
3016/// user-defined conversion sequence that performs such a conversion
3017/// and this routine will return true. Otherwise, this routine returns
3018/// false and User is unspecified.
3019///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003020/// \param AllowExplicit true if the conversion should consider C++0x
3021/// "explicit" conversion functions as well as non-explicit conversion
3022/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003023///
3024/// \param AllowObjCConversionOnExplicit true if the conversion should
3025/// allow an extra Objective-C pointer conversion on uses of explicit
3026/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003027static OverloadingResult
3028IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003029 UserDefinedConversionSequence &User,
3030 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003031 bool AllowExplicit,
3032 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003033 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003034
Douglas Gregor5ab11652010-04-17 22:01:05 +00003035 // Whether we will only visit constructors.
3036 bool ConstructorsOnly = false;
3037
3038 // If the type we are conversion to is a class type, enumerate its
3039 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003040 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003041 // C++ [over.match.ctor]p1:
3042 // When objects of class type are direct-initialized (8.5), or
3043 // copy-initialized from an expression of the same or a
3044 // derived class type (8.5), overload resolution selects the
3045 // constructor. [...] For copy-initialization, the candidate
3046 // functions are all the converting constructors (12.3.1) of
3047 // that class. The argument list is the expression-list within
3048 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003049 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003050 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003051 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003052 ConstructorsOnly = true;
3053
Benjamin Kramer90633e32012-11-23 17:04:52 +00003054 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003055 // RequireCompleteType may have returned true due to some invalid decl
3056 // during template instantiation, but ToType may be complete enough now
3057 // to try to recover.
3058 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003059 // We're not going to find any constructors.
3060 } else if (CXXRecordDecl *ToRecordDecl
3061 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003062
3063 Expr **Args = &From;
3064 unsigned NumArgs = 1;
3065 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003066 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003067 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003068 OverloadingResult Result = IsInitializerListConstructorConversion(
3069 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3070 if (Result != OR_No_Viable_Function)
3071 return Result;
3072 // Never mind.
3073 CandidateSet.clear();
3074
3075 // If we're list-initializing, we pass the individual elements as
3076 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003077 Args = InitList->getInits();
3078 NumArgs = InitList->getNumInits();
3079 ListInitializing = true;
3080 }
3081
David Blaikieff7d47a2012-12-19 00:45:41 +00003082 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3083 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003084 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003085 NamedDecl *D = *Con;
3086 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3087
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003088 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003089 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003090 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003091 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003092 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003093 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003094 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3095 else
John McCalla0296f72010-03-19 07:35:19 +00003096 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003098 bool Usable = !Constructor->isInvalidDecl();
3099 if (ListInitializing)
3100 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3101 else
3102 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3103 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003104 bool SuppressUserConversions = !ConstructorsOnly;
3105 if (SuppressUserConversions && ListInitializing) {
3106 SuppressUserConversions = false;
3107 if (NumArgs == 1) {
3108 // If the first argument is (a reference to) the target type,
3109 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003110 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3111 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003112 }
3113 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003114 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003115 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003116 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003117 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003118 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003119 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003120 // Allow one user-defined conversion when user specifies a
3121 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003122 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003123 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003124 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003125 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003126 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003127 }
3128 }
3129
Douglas Gregor5ab11652010-04-17 22:01:05 +00003130 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003131 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003132 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003133 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003134 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003135 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003136 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003137 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3138 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003139 std::pair<CXXRecordDecl::conversion_iterator,
3140 CXXRecordDecl::conversion_iterator>
3141 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3142 for (CXXRecordDecl::conversion_iterator
3143 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003144 DeclAccessPair FoundDecl = I.getPair();
3145 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003146 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3147 if (isa<UsingShadowDecl>(D))
3148 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3149
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003150 CXXConversionDecl *Conv;
3151 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003152 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3153 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003154 else
John McCallda4458e2010-03-31 01:36:47 +00003155 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003156
3157 if (AllowExplicit || !Conv->isExplicit()) {
3158 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003159 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3160 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003161 CandidateSet,
3162 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003163 else
John McCall5c32be02010-08-24 20:38:10 +00003164 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003165 From, ToType, CandidateSet,
3166 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003167 }
3168 }
3169 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003170 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003171
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003172 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3173
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003174 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003175 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003176 case OR_Success:
3177 // Record the standard conversion we used and the conversion function.
3178 if (CXXConstructorDecl *Constructor
3179 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3180 // C++ [over.ics.user]p1:
3181 // If the user-defined conversion is specified by a
3182 // constructor (12.3.1), the initial standard conversion
3183 // sequence converts the source type to the type required by
3184 // the argument of the constructor.
3185 //
3186 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003187 if (isa<InitListExpr>(From)) {
3188 // Initializer lists don't have conversions as such.
3189 User.Before.setAsIdentityConversion();
3190 } else {
3191 if (Best->Conversions[0].isEllipsis())
3192 User.EllipsisConversion = true;
3193 else {
3194 User.Before = Best->Conversions[0].Standard;
3195 User.EllipsisConversion = false;
3196 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003197 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003198 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003199 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003200 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003201 User.After.setAsIdentityConversion();
3202 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3203 User.After.setAllToTypes(ToType);
3204 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003205 }
3206 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003207 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3208 // C++ [over.ics.user]p1:
3209 //
3210 // [...] If the user-defined conversion is specified by a
3211 // conversion function (12.3.2), the initial standard
3212 // conversion sequence converts the source type to the
3213 // implicit object parameter of the conversion function.
3214 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003215 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003216 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003217 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003218 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003219
John McCall5c32be02010-08-24 20:38:10 +00003220 // C++ [over.ics.user]p2:
3221 // The second standard conversion sequence converts the
3222 // result of the user-defined conversion to the target type
3223 // for the sequence. Since an implicit conversion sequence
3224 // is an initialization, the special rules for
3225 // initialization by user-defined conversion apply when
3226 // selecting the best user-defined conversion for a
3227 // user-defined conversion sequence (see 13.3.3 and
3228 // 13.3.3.1).
3229 User.After = Best->FinalConversion;
3230 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003231 }
David Blaikie8a40f702012-01-17 06:56:22 +00003232 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003233
John McCall5c32be02010-08-24 20:38:10 +00003234 case OR_No_Viable_Function:
3235 return OR_No_Viable_Function;
3236 case OR_Deleted:
3237 // No conversion here! We're done.
3238 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239
John McCall5c32be02010-08-24 20:38:10 +00003240 case OR_Ambiguous:
3241 return OR_Ambiguous;
3242 }
3243
David Blaikie8a40f702012-01-17 06:56:22 +00003244 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003245}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003247bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003248Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003249 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003250 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3251 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003252 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003253 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003254 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003255 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003256 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3257 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003258 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003259 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003260 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003261 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003262 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3263 << From->getType() << From->getSourceRange() << ToType;
3264 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003265 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003266 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003268}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003269
Douglas Gregor2837aa22012-02-22 17:32:19 +00003270/// \brief Compare the user-defined conversion functions or constructors
3271/// of two user-defined conversion sequences to determine whether any ordering
3272/// is possible.
3273static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003274compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003275 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003276 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003277 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003278
Douglas Gregor2837aa22012-02-22 17:32:19 +00003279 // Objective-C++:
3280 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003281 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003282 // respectively, always prefer the conversion to a function pointer,
3283 // because the function pointer is more lightweight and is more likely
3284 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003285 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003286 if (!Conv1)
3287 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003288
Douglas Gregor2837aa22012-02-22 17:32:19 +00003289 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3290 if (!Conv2)
3291 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003292
Douglas Gregor2837aa22012-02-22 17:32:19 +00003293 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3294 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3295 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3296 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003297 return Block1 ? ImplicitConversionSequence::Worse
3298 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003299 }
3300
3301 return ImplicitConversionSequence::Indistinguishable;
3302}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003303
3304static bool hasDeprecatedStringLiteralToCharPtrConversion(
3305 const ImplicitConversionSequence &ICS) {
3306 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3307 (ICS.isUserDefined() &&
3308 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3309}
3310
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003311/// CompareImplicitConversionSequences - Compare two implicit
3312/// conversion sequences to determine whether one is better than the
3313/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003314static ImplicitConversionSequence::CompareKind
3315CompareImplicitConversionSequences(Sema &S,
3316 const ImplicitConversionSequence& ICS1,
3317 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003318{
3319 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3320 // conversion sequences (as defined in 13.3.3.1)
3321 // -- a standard conversion sequence (13.3.3.1.1) is a better
3322 // conversion sequence than a user-defined conversion sequence or
3323 // an ellipsis conversion sequence, and
3324 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3325 // conversion sequence than an ellipsis conversion sequence
3326 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003327 //
John McCall0d1da222010-01-12 00:44:57 +00003328 // C++0x [over.best.ics]p10:
3329 // For the purpose of ranking implicit conversion sequences as
3330 // described in 13.3.3.2, the ambiguous conversion sequence is
3331 // treated as a user-defined sequence that is indistinguishable
3332 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003333
3334 // String literal to 'char *' conversion has been deprecated in C++03. It has
3335 // been removed from C++11. We still accept this conversion, if it happens at
3336 // the best viable function. Otherwise, this conversion is considered worse
3337 // than ellipsis conversion. Consider this as an extension; this is not in the
3338 // standard. For example:
3339 //
3340 // int &f(...); // #1
3341 // void f(char*); // #2
3342 // void g() { int &r = f("foo"); }
3343 //
3344 // In C++03, we pick #2 as the best viable function.
3345 // In C++11, we pick #1 as the best viable function, because ellipsis
3346 // conversion is better than string-literal to char* conversion (since there
3347 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3348 // convert arguments, #2 would be the best viable function in C++11.
3349 // If the best viable function has this conversion, a warning will be issued
3350 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3351
3352 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3353 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3354 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3355 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3356 ? ImplicitConversionSequence::Worse
3357 : ImplicitConversionSequence::Better;
3358
Douglas Gregor5ab11652010-04-17 22:01:05 +00003359 if (ICS1.getKindRank() < ICS2.getKindRank())
3360 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003361 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003362 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003363
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003364 // The following checks require both conversion sequences to be of
3365 // the same kind.
3366 if (ICS1.getKind() != ICS2.getKind())
3367 return ImplicitConversionSequence::Indistinguishable;
3368
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003369 ImplicitConversionSequence::CompareKind Result =
3370 ImplicitConversionSequence::Indistinguishable;
3371
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003372 // Two implicit conversion sequences of the same form are
3373 // indistinguishable conversion sequences unless one of the
3374 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003375 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003376 Result = CompareStandardConversionSequences(S,
3377 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003378 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003379 // User-defined conversion sequence U1 is a better conversion
3380 // sequence than another user-defined conversion sequence U2 if
3381 // they contain the same user-defined conversion function or
3382 // constructor and if the second standard conversion sequence of
3383 // U1 is better than the second standard conversion sequence of
3384 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003385 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003387 Result = CompareStandardConversionSequences(S,
3388 ICS1.UserDefined.After,
3389 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003390 else
3391 Result = compareConversionFunctions(S,
3392 ICS1.UserDefined.ConversionFunction,
3393 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003394 }
3395
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003396 // List-initialization sequence L1 is a better conversion sequence than
3397 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3398 // for some X and L2 does not.
3399 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003400 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003401 if (ICS1.isStdInitializerListElement() &&
3402 !ICS2.isStdInitializerListElement())
3403 return ImplicitConversionSequence::Better;
3404 if (!ICS1.isStdInitializerListElement() &&
3405 ICS2.isStdInitializerListElement())
3406 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003407 }
3408
3409 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003410}
3411
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003412static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3413 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3414 Qualifiers Quals;
3415 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003419 return Context.hasSameUnqualifiedType(T1, T2);
3420}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003422// Per 13.3.3.2p3, compare the given standard conversion sequences to
3423// determine if one is a proper subset of the other.
3424static ImplicitConversionSequence::CompareKind
3425compareStandardConversionSubsets(ASTContext &Context,
3426 const StandardConversionSequence& SCS1,
3427 const StandardConversionSequence& SCS2) {
3428 ImplicitConversionSequence::CompareKind Result
3429 = ImplicitConversionSequence::Indistinguishable;
3430
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003432 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003433 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3434 return ImplicitConversionSequence::Better;
3435 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3436 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003438 if (SCS1.Second != SCS2.Second) {
3439 if (SCS1.Second == ICK_Identity)
3440 Result = ImplicitConversionSequence::Better;
3441 else if (SCS2.Second == ICK_Identity)
3442 Result = ImplicitConversionSequence::Worse;
3443 else
3444 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003445 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003446 return ImplicitConversionSequence::Indistinguishable;
3447
3448 if (SCS1.Third == SCS2.Third) {
3449 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3450 : ImplicitConversionSequence::Indistinguishable;
3451 }
3452
3453 if (SCS1.Third == ICK_Identity)
3454 return Result == ImplicitConversionSequence::Worse
3455 ? ImplicitConversionSequence::Indistinguishable
3456 : ImplicitConversionSequence::Better;
3457
3458 if (SCS2.Third == ICK_Identity)
3459 return Result == ImplicitConversionSequence::Better
3460 ? ImplicitConversionSequence::Indistinguishable
3461 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003463 return ImplicitConversionSequence::Indistinguishable;
3464}
3465
Douglas Gregore696ebb2011-01-26 14:52:12 +00003466/// \brief Determine whether one of the given reference bindings is better
3467/// than the other based on what kind of bindings they are.
3468static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3469 const StandardConversionSequence &SCS2) {
3470 // C++0x [over.ics.rank]p3b4:
3471 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3472 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003474 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003476 // reference*.
3477 //
3478 // FIXME: Rvalue references. We're going rogue with the above edits,
3479 // because the semantics in the current C++0x working paper (N3225 at the
3480 // time of this writing) break the standard definition of std::forward
3481 // and std::reference_wrapper when dealing with references to functions.
3482 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003483 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3484 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3485 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486
Douglas Gregore696ebb2011-01-26 14:52:12 +00003487 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3488 SCS2.IsLvalueReference) ||
3489 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3490 !SCS2.IsLvalueReference);
3491}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003492
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003493/// CompareStandardConversionSequences - Compare two standard
3494/// conversion sequences to determine whether one is better than the
3495/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003496static ImplicitConversionSequence::CompareKind
3497CompareStandardConversionSequences(Sema &S,
3498 const StandardConversionSequence& SCS1,
3499 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003500{
3501 // Standard conversion sequence S1 is a better conversion sequence
3502 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3503
3504 // -- S1 is a proper subsequence of S2 (comparing the conversion
3505 // sequences in the canonical form defined by 13.3.3.1.1,
3506 // excluding any Lvalue Transformation; the identity conversion
3507 // sequence is considered to be a subsequence of any
3508 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003509 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003510 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003511 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512
3513 // -- the rank of S1 is better than the rank of S2 (by the rules
3514 // defined below), or, if not that,
3515 ImplicitConversionRank Rank1 = SCS1.getRank();
3516 ImplicitConversionRank Rank2 = SCS2.getRank();
3517 if (Rank1 < Rank2)
3518 return ImplicitConversionSequence::Better;
3519 else if (Rank2 < Rank1)
3520 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003521
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003522 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3523 // are indistinguishable unless one of the following rules
3524 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003526 // A conversion that is not a conversion of a pointer, or
3527 // pointer to member, to bool is better than another conversion
3528 // that is such a conversion.
3529 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3530 return SCS2.isPointerConversionToBool()
3531 ? ImplicitConversionSequence::Better
3532 : ImplicitConversionSequence::Worse;
3533
Douglas Gregor5c407d92008-10-23 00:40:37 +00003534 // C++ [over.ics.rank]p4b2:
3535 //
3536 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003537 // conversion of B* to A* is better than conversion of B* to
3538 // void*, and conversion of A* to void* is better than conversion
3539 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003540 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003541 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003542 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003543 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003544 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3545 // Exactly one of the conversion sequences is a conversion to
3546 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003547 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3548 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003549 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3550 // Neither conversion sequence converts to a void pointer; compare
3551 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003552 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003553 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003554 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003555 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3556 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003557 // Both conversion sequences are conversions to void
3558 // pointers. Compare the source types to determine if there's an
3559 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003560 QualType FromType1 = SCS1.getFromType();
3561 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003562
3563 // Adjust the types we're converting from via the array-to-pointer
3564 // conversion, if we need to.
3565 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003566 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003567 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003568 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003569
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003570 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3571 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003572
John McCall5c32be02010-08-24 20:38:10 +00003573 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003574 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003575 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003576 return ImplicitConversionSequence::Worse;
3577
3578 // Objective-C++: If one interface is more specific than the
3579 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003580 const ObjCObjectPointerType* FromObjCPtr1
3581 = FromType1->getAs<ObjCObjectPointerType>();
3582 const ObjCObjectPointerType* FromObjCPtr2
3583 = FromType2->getAs<ObjCObjectPointerType>();
3584 if (FromObjCPtr1 && FromObjCPtr2) {
3585 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3586 FromObjCPtr2);
3587 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3588 FromObjCPtr1);
3589 if (AssignLeft != AssignRight) {
3590 return AssignLeft? ImplicitConversionSequence::Better
3591 : ImplicitConversionSequence::Worse;
3592 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003593 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003594 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003595
3596 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3597 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003598 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003599 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003600 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003601
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003602 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003603 // Check for a better reference binding based on the kind of bindings.
3604 if (isBetterReferenceBindingKind(SCS1, SCS2))
3605 return ImplicitConversionSequence::Better;
3606 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3607 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Sebastian Redlb28b4072009-03-22 23:49:27 +00003609 // C++ [over.ics.rank]p3b4:
3610 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3611 // which the references refer are the same type except for
3612 // top-level cv-qualifiers, and the type to which the reference
3613 // initialized by S2 refers is more cv-qualified than the type
3614 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003615 QualType T1 = SCS1.getToType(2);
3616 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003617 T1 = S.Context.getCanonicalType(T1);
3618 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003619 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003620 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3621 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003622 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003623 // Objective-C++ ARC: If the references refer to objects with different
3624 // lifetimes, prefer bindings that don't change lifetime.
3625 if (SCS1.ObjCLifetimeConversionBinding !=
3626 SCS2.ObjCLifetimeConversionBinding) {
3627 return SCS1.ObjCLifetimeConversionBinding
3628 ? ImplicitConversionSequence::Worse
3629 : ImplicitConversionSequence::Better;
3630 }
3631
Chandler Carruth8e543b32010-12-12 08:17:55 +00003632 // If the type is an array type, promote the element qualifiers to the
3633 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003634 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003635 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003636 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003637 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003638 if (T2.isMoreQualifiedThan(T1))
3639 return ImplicitConversionSequence::Better;
3640 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003641 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003642 }
3643 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003644
Francois Pichet08d2fa02011-09-18 21:37:37 +00003645 // In Microsoft mode, prefer an integral conversion to a
3646 // floating-to-integral conversion if the integral conversion
3647 // is between types of the same size.
3648 // For example:
3649 // void f(float);
3650 // void f(int);
3651 // int main {
3652 // long a;
3653 // f(a);
3654 // }
3655 // Here, MSVC will call f(int) instead of generating a compile error
3656 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003657 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3658 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003659 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003660 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003661 return ImplicitConversionSequence::Better;
3662
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003663 return ImplicitConversionSequence::Indistinguishable;
3664}
3665
3666/// CompareQualificationConversions - Compares two standard conversion
3667/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003668/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3669ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003670CompareQualificationConversions(Sema &S,
3671 const StandardConversionSequence& SCS1,
3672 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003673 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003674 // -- S1 and S2 differ only in their qualification conversion and
3675 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3676 // cv-qualification signature of type T1 is a proper subset of
3677 // the cv-qualification signature of type T2, and S1 is not the
3678 // deprecated string literal array-to-pointer conversion (4.2).
3679 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3680 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3681 return ImplicitConversionSequence::Indistinguishable;
3682
3683 // FIXME: the example in the standard doesn't use a qualification
3684 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003685 QualType T1 = SCS1.getToType(2);
3686 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003687 T1 = S.Context.getCanonicalType(T1);
3688 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003689 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003690 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3691 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003692
3693 // If the types are the same, we won't learn anything by unwrapped
3694 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003695 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696 return ImplicitConversionSequence::Indistinguishable;
3697
Chandler Carruth607f38e2009-12-29 07:16:59 +00003698 // If the type is an array type, promote the element qualifiers to the type
3699 // for comparison.
3700 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003701 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003702 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003703 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003704
Mike Stump11289f42009-09-09 15:08:12 +00003705 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003706 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003707
3708 // Objective-C++ ARC:
3709 // Prefer qualification conversions not involving a change in lifetime
3710 // to qualification conversions that do not change lifetime.
3711 if (SCS1.QualificationIncludesObjCLifetime !=
3712 SCS2.QualificationIncludesObjCLifetime) {
3713 Result = SCS1.QualificationIncludesObjCLifetime
3714 ? ImplicitConversionSequence::Worse
3715 : ImplicitConversionSequence::Better;
3716 }
3717
John McCall5c32be02010-08-24 20:38:10 +00003718 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003719 // Within each iteration of the loop, we check the qualifiers to
3720 // determine if this still looks like a qualification
3721 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003722 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003723 // until there are no more pointers or pointers-to-members left
3724 // to unwrap. This essentially mimics what
3725 // IsQualificationConversion does, but here we're checking for a
3726 // strict subset of qualifiers.
3727 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3728 // The qualifiers are the same, so this doesn't tell us anything
3729 // about how the sequences rank.
3730 ;
3731 else if (T2.isMoreQualifiedThan(T1)) {
3732 // T1 has fewer qualifiers, so it could be the better sequence.
3733 if (Result == ImplicitConversionSequence::Worse)
3734 // Neither has qualifiers that are a subset of the other's
3735 // qualifiers.
3736 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003738 Result = ImplicitConversionSequence::Better;
3739 } else if (T1.isMoreQualifiedThan(T2)) {
3740 // T2 has fewer qualifiers, so it could be the better sequence.
3741 if (Result == ImplicitConversionSequence::Better)
3742 // Neither has qualifiers that are a subset of the other's
3743 // qualifiers.
3744 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003745
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003746 Result = ImplicitConversionSequence::Worse;
3747 } else {
3748 // Qualifiers are disjoint.
3749 return ImplicitConversionSequence::Indistinguishable;
3750 }
3751
3752 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003753 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003754 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003755 }
3756
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003757 // Check that the winning standard conversion sequence isn't using
3758 // the deprecated string literal array to pointer conversion.
3759 switch (Result) {
3760 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003761 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003762 Result = ImplicitConversionSequence::Indistinguishable;
3763 break;
3764
3765 case ImplicitConversionSequence::Indistinguishable:
3766 break;
3767
3768 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003769 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003770 Result = ImplicitConversionSequence::Indistinguishable;
3771 break;
3772 }
3773
3774 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003775}
3776
Douglas Gregor5c407d92008-10-23 00:40:37 +00003777/// CompareDerivedToBaseConversions - Compares two standard conversion
3778/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003779/// various kinds of derived-to-base conversions (C++
3780/// [over.ics.rank]p4b3). As part of these checks, we also look at
3781/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003782ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003783CompareDerivedToBaseConversions(Sema &S,
3784 const StandardConversionSequence& SCS1,
3785 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003786 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003787 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003788 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003789 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003790
3791 // Adjust the types we're converting from via the array-to-pointer
3792 // conversion, if we need to.
3793 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003794 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003795 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003796 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003797
3798 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003799 FromType1 = S.Context.getCanonicalType(FromType1);
3800 ToType1 = S.Context.getCanonicalType(ToType1);
3801 FromType2 = S.Context.getCanonicalType(FromType2);
3802 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003803
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003804 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003805 //
3806 // If class B is derived directly or indirectly from class A and
3807 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003808 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003810 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003811 SCS2.Second == ICK_Pointer_Conversion &&
3812 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3813 FromType1->isPointerType() && FromType2->isPointerType() &&
3814 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003815 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003816 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003817 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003819 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003820 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003821 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003822 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003823
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003824 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003825 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003826 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003827 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003828 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003829 return ImplicitConversionSequence::Worse;
3830 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003831
3832 // -- conversion of B* to A* is better than conversion of C* to A*,
3833 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003834 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003835 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003836 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003837 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003838 }
3839 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3840 SCS2.Second == ICK_Pointer_Conversion) {
3841 const ObjCObjectPointerType *FromPtr1
3842 = FromType1->getAs<ObjCObjectPointerType>();
3843 const ObjCObjectPointerType *FromPtr2
3844 = FromType2->getAs<ObjCObjectPointerType>();
3845 const ObjCObjectPointerType *ToPtr1
3846 = ToType1->getAs<ObjCObjectPointerType>();
3847 const ObjCObjectPointerType *ToPtr2
3848 = ToType2->getAs<ObjCObjectPointerType>();
3849
3850 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3851 // Apply the same conversion ranking rules for Objective-C pointer types
3852 // that we do for C++ pointers to class types. However, we employ the
3853 // Objective-C pseudo-subtyping relationship used for assignment of
3854 // Objective-C pointer types.
3855 bool FromAssignLeft
3856 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3857 bool FromAssignRight
3858 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3859 bool ToAssignLeft
3860 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3861 bool ToAssignRight
3862 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3863
3864 // A conversion to an a non-id object pointer type or qualified 'id'
3865 // type is better than a conversion to 'id'.
3866 if (ToPtr1->isObjCIdType() &&
3867 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3868 return ImplicitConversionSequence::Worse;
3869 if (ToPtr2->isObjCIdType() &&
3870 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3871 return ImplicitConversionSequence::Better;
3872
3873 // A conversion to a non-id object pointer type is better than a
3874 // conversion to a qualified 'id' type
3875 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3876 return ImplicitConversionSequence::Worse;
3877 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3878 return ImplicitConversionSequence::Better;
3879
3880 // A conversion to an a non-Class object pointer type or qualified 'Class'
3881 // type is better than a conversion to 'Class'.
3882 if (ToPtr1->isObjCClassType() &&
3883 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3884 return ImplicitConversionSequence::Worse;
3885 if (ToPtr2->isObjCClassType() &&
3886 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3887 return ImplicitConversionSequence::Better;
3888
3889 // A conversion to a non-Class object pointer type is better than a
3890 // conversion to a qualified 'Class' type.
3891 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3892 return ImplicitConversionSequence::Worse;
3893 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3894 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003895
Douglas Gregor058d3de2011-01-31 18:51:41 +00003896 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3897 if (S.Context.hasSameType(FromType1, FromType2) &&
3898 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3899 (ToAssignLeft != ToAssignRight))
3900 return ToAssignLeft? ImplicitConversionSequence::Worse
3901 : ImplicitConversionSequence::Better;
3902
3903 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3904 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3905 (FromAssignLeft != FromAssignRight))
3906 return FromAssignLeft? ImplicitConversionSequence::Better
3907 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003908 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003909 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003910
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003911 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003912 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3913 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3914 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003916 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003918 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003920 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003922 ToType2->getAs<MemberPointerType>();
3923 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3924 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3925 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3926 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3927 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3928 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3929 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3930 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003931 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003932 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003933 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003934 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003935 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003936 return ImplicitConversionSequence::Better;
3937 }
3938 // conversion of B::* to C::* is better than conversion of A::* to C::*
3939 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003940 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003941 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003942 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003943 return ImplicitConversionSequence::Worse;
3944 }
3945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946
Douglas Gregor5ab11652010-04-17 22:01:05 +00003947 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003948 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003949 // -- binding of an expression of type C to a reference of type
3950 // B& is better than binding an expression of type C to a
3951 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003952 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3953 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3954 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003955 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003956 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003957 return ImplicitConversionSequence::Worse;
3958 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003959
Douglas Gregor2fe98832008-11-03 19:09:14 +00003960 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003961 // -- binding of an expression of type B to a reference of type
3962 // A& is better than binding an expression of type C to a
3963 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003964 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3965 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3966 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003967 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003968 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003969 return ImplicitConversionSequence::Worse;
3970 }
3971 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003972
Douglas Gregor5c407d92008-10-23 00:40:37 +00003973 return ImplicitConversionSequence::Indistinguishable;
3974}
3975
Douglas Gregor45bb4832013-03-26 23:36:30 +00003976/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3977/// C++ class.
3978static bool isTypeValid(QualType T) {
3979 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3980 return !Record->isInvalidDecl();
3981
3982 return true;
3983}
3984
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003985/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3986/// determine whether they are reference-related,
3987/// reference-compatible, reference-compatible with added
3988/// qualification, or incompatible, for use in C++ initialization by
3989/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3990/// type, and the first type (T1) is the pointee type of the reference
3991/// type being initialized.
3992Sema::ReferenceCompareResult
3993Sema::CompareReferenceRelationship(SourceLocation Loc,
3994 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003995 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003996 bool &ObjCConversion,
3997 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003998 assert(!OrigT1->isReferenceType() &&
3999 "T1 must be the pointee type of the reference type");
4000 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4001
4002 QualType T1 = Context.getCanonicalType(OrigT1);
4003 QualType T2 = Context.getCanonicalType(OrigT2);
4004 Qualifiers T1Quals, T2Quals;
4005 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4006 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4007
4008 // C++ [dcl.init.ref]p4:
4009 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4010 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4011 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004012 DerivedToBase = false;
4013 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004014 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004015 if (UnqualT1 == UnqualT2) {
4016 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004017 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004018 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4019 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004020 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004021 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4022 UnqualT2->isObjCObjectOrInterfaceType() &&
4023 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4024 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025 else
4026 return Ref_Incompatible;
4027
4028 // At this point, we know that T1 and T2 are reference-related (at
4029 // least).
4030
4031 // If the type is an array type, promote the element qualifiers to the type
4032 // for comparison.
4033 if (isa<ArrayType>(T1) && T1Quals)
4034 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4035 if (isa<ArrayType>(T2) && T2Quals)
4036 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4037
4038 // C++ [dcl.init.ref]p4:
4039 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4040 // reference-related to T2 and cv1 is the same cv-qualification
4041 // as, or greater cv-qualification than, cv2. For purposes of
4042 // overload resolution, cases for which cv1 is greater
4043 // cv-qualification than cv2 are identified as
4044 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004045 //
4046 // Note that we also require equivalence of Objective-C GC and address-space
4047 // qualifiers when performing these computations, so that e.g., an int in
4048 // address space 1 is not reference-compatible with an int in address
4049 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004050 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4051 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004052 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4053 ObjCLifetimeConversion = true;
4054
John McCall31168b02011-06-15 23:02:42 +00004055 T1Quals.removeObjCLifetime();
4056 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004057 }
4058
Douglas Gregord517d552011-04-28 17:56:11 +00004059 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004060 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004061 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004062 return Ref_Compatible_With_Added_Qualification;
4063 else
4064 return Ref_Related;
4065}
4066
Douglas Gregor836a7e82010-08-11 02:15:33 +00004067/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004068/// with DeclType. Return true if something definite is found.
4069static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004070FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4071 QualType DeclType, SourceLocation DeclLoc,
4072 Expr *Init, QualType T2, bool AllowRvalues,
4073 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004074 assert(T2->isRecordType() && "Can only find conversions of record types.");
4075 CXXRecordDecl *T2RecordDecl
4076 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4077
Richard Smith100b24a2014-04-17 01:52:14 +00004078 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004079 std::pair<CXXRecordDecl::conversion_iterator,
4080 CXXRecordDecl::conversion_iterator>
4081 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4082 for (CXXRecordDecl::conversion_iterator
4083 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004084 NamedDecl *D = *I;
4085 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4086 if (isa<UsingShadowDecl>(D))
4087 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4088
4089 FunctionTemplateDecl *ConvTemplate
4090 = dyn_cast<FunctionTemplateDecl>(D);
4091 CXXConversionDecl *Conv;
4092 if (ConvTemplate)
4093 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4094 else
4095 Conv = cast<CXXConversionDecl>(D);
4096
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004098 // explicit conversions, skip it.
4099 if (!AllowExplicit && Conv->isExplicit())
4100 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101
Douglas Gregor836a7e82010-08-11 02:15:33 +00004102 if (AllowRvalues) {
4103 bool DerivedToBase = false;
4104 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004105 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004106
4107 // If we are initializing an rvalue reference, don't permit conversion
4108 // functions that return lvalues.
4109 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4110 const ReferenceType *RefType
4111 = Conv->getConversionType()->getAs<LValueReferenceType>();
4112 if (RefType && !RefType->getPointeeType()->isFunctionType())
4113 continue;
4114 }
4115
Douglas Gregor836a7e82010-08-11 02:15:33 +00004116 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004117 S.CompareReferenceRelationship(
4118 DeclLoc,
4119 Conv->getConversionType().getNonReferenceType()
4120 .getUnqualifiedType(),
4121 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004122 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004123 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004124 continue;
4125 } else {
4126 // If the conversion function doesn't return a reference type,
4127 // it can't be considered for this conversion. An rvalue reference
4128 // is only acceptable if its referencee is a function type.
4129
4130 const ReferenceType *RefType =
4131 Conv->getConversionType()->getAs<ReferenceType>();
4132 if (!RefType ||
4133 (!RefType->isLValueReferenceType() &&
4134 !RefType->getPointeeType()->isFunctionType()))
4135 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137
Douglas Gregor836a7e82010-08-11 02:15:33 +00004138 if (ConvTemplate)
4139 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004140 Init, DeclType, CandidateSet,
4141 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004142 else
4143 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004144 DeclType, CandidateSet,
4145 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004146 }
4147
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004148 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4149
Sebastian Redld92badf2010-06-30 18:13:39 +00004150 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004151 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004152 case OR_Success:
4153 // C++ [over.ics.ref]p1:
4154 //
4155 // [...] If the parameter binds directly to the result of
4156 // applying a conversion function to the argument
4157 // expression, the implicit conversion sequence is a
4158 // user-defined conversion sequence (13.3.3.1.2), with the
4159 // second standard conversion sequence either an identity
4160 // conversion or, if the conversion function returns an
4161 // entity of a type that is a derived class of the parameter
4162 // type, a derived-to-base Conversion.
4163 if (!Best->FinalConversion.DirectBinding)
4164 return false;
4165
4166 ICS.setUserDefined();
4167 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4168 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004169 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004170 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004171 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004172 ICS.UserDefined.EllipsisConversion = false;
4173 assert(ICS.UserDefined.After.ReferenceBinding &&
4174 ICS.UserDefined.After.DirectBinding &&
4175 "Expected a direct reference binding!");
4176 return true;
4177
4178 case OR_Ambiguous:
4179 ICS.setAmbiguous();
4180 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4181 Cand != CandidateSet.end(); ++Cand)
4182 if (Cand->Viable)
4183 ICS.Ambiguous.addConversion(Cand->Function);
4184 return true;
4185
4186 case OR_No_Viable_Function:
4187 case OR_Deleted:
4188 // There was no suitable conversion, or we found a deleted
4189 // conversion; continue with other checks.
4190 return false;
4191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192
David Blaikie8a40f702012-01-17 06:56:22 +00004193 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004194}
4195
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004196/// \brief Compute an implicit conversion sequence for reference
4197/// initialization.
4198static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004199TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004200 SourceLocation DeclLoc,
4201 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004202 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004203 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4204
4205 // Most paths end in a failed conversion.
4206 ImplicitConversionSequence ICS;
4207 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4208
4209 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4210 QualType T2 = Init->getType();
4211
4212 // If the initializer is the address of an overloaded function, try
4213 // to resolve the overloaded function. If all goes well, T2 is the
4214 // type of the resulting function.
4215 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4216 DeclAccessPair Found;
4217 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4218 false, Found))
4219 T2 = Fn->getType();
4220 }
4221
4222 // Compute some basic properties of the types and the initializer.
4223 bool isRValRef = DeclType->isRValueReferenceType();
4224 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004225 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004226 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004227 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004228 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004229 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004230 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004231
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004232
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004234 // A reference to type "cv1 T1" is initialized by an expression
4235 // of type "cv2 T2" as follows:
4236
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004238 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004239 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4240 // reference-compatible with "cv2 T2," or
4241 //
4242 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4243 if (InitCategory.isLValue() &&
4244 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004245 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 // When a parameter of reference type binds directly (8.5.3)
4247 // to an argument expression, the implicit conversion sequence
4248 // is the identity conversion, unless the argument expression
4249 // has a type that is a derived class of the parameter type,
4250 // in which case the implicit conversion sequence is a
4251 // derived-to-base Conversion (13.3.3.1).
4252 ICS.setStandard();
4253 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004254 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4255 : ObjCConversion? ICK_Compatible_Conversion
4256 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 ICS.Standard.Third = ICK_Identity;
4258 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4259 ICS.Standard.setToType(0, T2);
4260 ICS.Standard.setToType(1, T1);
4261 ICS.Standard.setToType(2, T1);
4262 ICS.Standard.ReferenceBinding = true;
4263 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004264 ICS.Standard.IsLvalueReference = !isRValRef;
4265 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4266 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004267 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004268 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004269 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004270 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004271
Sebastian Redld92badf2010-06-30 18:13:39 +00004272 // Nothing more to do: the inaccessibility/ambiguity check for
4273 // derived-to-base conversions is suppressed when we're
4274 // computing the implicit conversion sequence (C++
4275 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004276 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004277 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004278
Sebastian Redld92badf2010-06-30 18:13:39 +00004279 // -- has a class type (i.e., T2 is a class type), where T1 is
4280 // not reference-related to T2, and can be implicitly
4281 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4282 // is reference-compatible with "cv3 T3" 92) (this
4283 // conversion is selected by enumerating the applicable
4284 // conversion functions (13.3.1.6) and choosing the best
4285 // one through overload resolution (13.3)),
4286 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004288 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004289 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4290 Init, T2, /*AllowRvalues=*/false,
4291 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004292 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004293 }
4294 }
4295
Sebastian Redld92badf2010-06-30 18:13:39 +00004296 // -- Otherwise, the reference shall be an lvalue reference to a
4297 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004298 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004300 // We actually handle one oddity of C++ [over.ics.ref] at this
4301 // point, which is that, due to p2 (which short-circuits reference
4302 // binding by only attempting a simple conversion for non-direct
4303 // bindings) and p3's strange wording, we allow a const volatile
4304 // reference to bind to an rvalue. Hence the check for the presence
4305 // of "const" rather than checking for "const" being the only
4306 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004307 // This is also the point where rvalue references and lvalue inits no longer
4308 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004309 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310 return ICS;
4311
Douglas Gregorf143cd52011-01-24 16:14:37 +00004312 // -- If the initializer expression
4313 //
4314 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004315 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004316 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4317 (InitCategory.isXValue() ||
4318 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4319 (InitCategory.isLValue() && T2->isFunctionType()))) {
4320 ICS.setStandard();
4321 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004323 : ObjCConversion? ICK_Compatible_Conversion
4324 : ICK_Identity;
4325 ICS.Standard.Third = ICK_Identity;
4326 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4327 ICS.Standard.setToType(0, T2);
4328 ICS.Standard.setToType(1, T1);
4329 ICS.Standard.setToType(2, T1);
4330 ICS.Standard.ReferenceBinding = true;
4331 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4332 // binding unless we're binding to a class prvalue.
4333 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4334 // allow the use of rvalue references in C++98/03 for the benefit of
4335 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004337 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004338 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004339 ICS.Standard.IsLvalueReference = !isRValRef;
4340 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004342 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004343 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004344 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004345 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregorf143cd52011-01-24 16:14:37 +00004349 // -- has a class type (i.e., T2 is a class type), where T1 is not
4350 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351 // an xvalue, class prvalue, or function lvalue of type
4352 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004353 // "cv3 T3",
4354 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004356 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004358 // class subobject).
4359 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004361 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4362 Init, T2, /*AllowRvalues=*/true,
4363 AllowExplicit)) {
4364 // In the second case, if the reference is an rvalue reference
4365 // and the second standard conversion sequence of the
4366 // user-defined conversion sequence includes an lvalue-to-rvalue
4367 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004369 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4370 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4371
Douglas Gregor95273c32011-01-21 16:36:05 +00004372 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004375 // -- Otherwise, a temporary of type "cv1 T1" is created and
4376 // initialized from the initializer expression using the
4377 // rules for a non-reference copy initialization (8.5). The
4378 // reference is then bound to the temporary. If T1 is
4379 // reference-related to T2, cv1 must be the same
4380 // cv-qualification as, or greater cv-qualification than,
4381 // cv2; otherwise, the program is ill-formed.
4382 if (RefRelationship == Sema::Ref_Related) {
4383 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4384 // we would be reference-compatible or reference-compatible with
4385 // added qualification. But that wasn't the case, so the reference
4386 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004387 //
4388 // Note that we only want to check address spaces and cvr-qualifiers here.
4389 // ObjC GC and lifetime qualifiers aren't important.
4390 Qualifiers T1Quals = T1.getQualifiers();
4391 Qualifiers T2Quals = T2.getQualifiers();
4392 T1Quals.removeObjCGCAttr();
4393 T1Quals.removeObjCLifetime();
4394 T2Quals.removeObjCGCAttr();
4395 T2Quals.removeObjCLifetime();
4396 if (!T1Quals.compatiblyIncludes(T2Quals))
4397 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004398 }
4399
4400 // If at least one of the types is a class type, the types are not
4401 // related, and we aren't allowed any user conversions, the
4402 // reference binding fails. This case is important for breaking
4403 // recursion, since TryImplicitConversion below will attempt to
4404 // create a temporary through the use of a copy constructor.
4405 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4406 (T1->isRecordType() || T2->isRecordType()))
4407 return ICS;
4408
Douglas Gregorcba72b12011-01-21 05:18:22 +00004409 // If T1 is reference-related to T2 and the reference is an rvalue
4410 // reference, the initializer expression shall not be an lvalue.
4411 if (RefRelationship >= Sema::Ref_Related &&
4412 isRValRef && Init->Classify(S.Context).isLValue())
4413 return ICS;
4414
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004415 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 // When a parameter of reference type is not bound directly to
4417 // an argument expression, the conversion sequence is the one
4418 // required to convert the argument expression to the
4419 // underlying type of the reference according to
4420 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4421 // to copy-initializing a temporary of the underlying type with
4422 // the argument expression. Any difference in top-level
4423 // cv-qualification is subsumed by the initialization itself
4424 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004425 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4426 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004427 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004428 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004429 /*AllowObjCWritebackConversion=*/false,
4430 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004431
4432 // Of course, that's still a reference binding.
4433 if (ICS.isStandard()) {
4434 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004435 ICS.Standard.IsLvalueReference = !isRValRef;
4436 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4437 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004438 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004439 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004440 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004441 // Don't allow rvalue references to bind to lvalues.
4442 if (DeclType->isRValueReferenceType()) {
Alp Toker314cc812014-01-25 16:55:45 +00004443 if (const ReferenceType *RefType =
4444 ICS.UserDefined.ConversionFunction->getReturnType()
4445 ->getAs<LValueReferenceType>()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004446 if (!RefType->getPointeeType()->isFunctionType()) {
4447 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4448 DeclType);
4449 return ICS;
4450 }
4451 }
4452 }
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004453 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004454 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004455 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4456 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4457 ICS.UserDefined.After.BindsToRvalue = true;
4458 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4459 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004460 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004461
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004462 return ICS;
4463}
4464
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004465static ImplicitConversionSequence
4466TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4467 bool SuppressUserConversions,
4468 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004469 bool AllowObjCWritebackConversion,
4470 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004471
4472/// TryListConversion - Try to copy-initialize a value of type ToType from the
4473/// initializer list From.
4474static ImplicitConversionSequence
4475TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4476 bool SuppressUserConversions,
4477 bool InOverloadResolution,
4478 bool AllowObjCWritebackConversion) {
4479 // C++11 [over.ics.list]p1:
4480 // When an argument is an initializer list, it is not an expression and
4481 // special rules apply for converting it to a parameter type.
4482
4483 ImplicitConversionSequence Result;
4484 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4485
Sebastian Redl09edce02012-01-23 22:09:39 +00004486 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004487 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004488 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004489 return Result;
4490
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004491 // C++11 [over.ics.list]p2:
4492 // If the parameter type is std::initializer_list<X> or "array of X" and
4493 // all the elements can be implicitly converted to X, the implicit
4494 // conversion sequence is the worst conversion necessary to convert an
4495 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004496 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004497 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004498 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004499 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004500 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004501 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004502 if (!X.isNull()) {
4503 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4504 Expr *Init = From->getInit(i);
4505 ImplicitConversionSequence ICS =
4506 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4507 InOverloadResolution,
4508 AllowObjCWritebackConversion);
4509 // If a single element isn't convertible, fail.
4510 if (ICS.isBad()) {
4511 Result = ICS;
4512 break;
4513 }
4514 // Otherwise, look for the worst conversion.
4515 if (Result.isBad() ||
4516 CompareImplicitConversionSequences(S, ICS, Result) ==
4517 ImplicitConversionSequence::Worse)
4518 Result = ICS;
4519 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004520
4521 // For an empty list, we won't have computed any conversion sequence.
4522 // Introduce the identity conversion sequence.
4523 if (From->getNumInits() == 0) {
4524 Result.setStandard();
4525 Result.Standard.setAsIdentityConversion();
4526 Result.Standard.setFromType(ToType);
4527 Result.Standard.setAllToTypes(ToType);
4528 }
4529
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004530 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004531 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004532 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004533
4534 // C++11 [over.ics.list]p3:
4535 // Otherwise, if the parameter is a non-aggregate class X and overload
4536 // resolution chooses a single best constructor [...] the implicit
4537 // conversion sequence is a user-defined conversion sequence. If multiple
4538 // constructors are viable but none is better than the others, the
4539 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004540 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4541 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004542 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4543 /*AllowExplicit=*/false,
4544 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004545 AllowObjCWritebackConversion,
4546 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004547 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004548
4549 // C++11 [over.ics.list]p4:
4550 // Otherwise, if the parameter has an aggregate type which can be
4551 // initialized from the initializer list [...] the implicit conversion
4552 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004553 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004554 // Type is an aggregate, argument is an init list. At this point it comes
4555 // down to checking whether the initialization works.
4556 // FIXME: Find out whether this parameter is consumed or not.
4557 InitializedEntity Entity =
4558 InitializedEntity::InitializeParameter(S.Context, ToType,
4559 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004560 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004561 Result.setUserDefined();
4562 Result.UserDefined.Before.setAsIdentityConversion();
4563 // Initializer lists don't have a type.
4564 Result.UserDefined.Before.setFromType(QualType());
4565 Result.UserDefined.Before.setAllToTypes(QualType());
4566
4567 Result.UserDefined.After.setAsIdentityConversion();
4568 Result.UserDefined.After.setFromType(ToType);
4569 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004570 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004571 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004572 return Result;
4573 }
4574
4575 // C++11 [over.ics.list]p5:
4576 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004577 if (ToType->isReferenceType()) {
4578 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4579 // mention initializer lists in any way. So we go by what list-
4580 // initialization would do and try to extrapolate from that.
4581
4582 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4583
4584 // If the initializer list has a single element that is reference-related
4585 // to the parameter type, we initialize the reference from that.
4586 if (From->getNumInits() == 1) {
4587 Expr *Init = From->getInit(0);
4588
4589 QualType T2 = Init->getType();
4590
4591 // If the initializer is the address of an overloaded function, try
4592 // to resolve the overloaded function. If all goes well, T2 is the
4593 // type of the resulting function.
4594 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4595 DeclAccessPair Found;
4596 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4597 Init, ToType, false, Found))
4598 T2 = Fn->getType();
4599 }
4600
4601 // Compute some basic properties of the types and the initializer.
4602 bool dummy1 = false;
4603 bool dummy2 = false;
4604 bool dummy3 = false;
4605 Sema::ReferenceCompareResult RefRelationship
4606 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4607 dummy2, dummy3);
4608
Richard Smith4d2bbd72013-09-06 01:22:42 +00004609 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004610 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4611 SuppressUserConversions,
4612 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004613 }
Sebastian Redldf888642011-12-03 14:54:30 +00004614 }
4615
4616 // Otherwise, we bind the reference to a temporary created from the
4617 // initializer list.
4618 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4619 InOverloadResolution,
4620 AllowObjCWritebackConversion);
4621 if (Result.isFailure())
4622 return Result;
4623 assert(!Result.isEllipsis() &&
4624 "Sub-initialization cannot result in ellipsis conversion.");
4625
4626 // Can we even bind to a temporary?
4627 if (ToType->isRValueReferenceType() ||
4628 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4629 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4630 Result.UserDefined.After;
4631 SCS.ReferenceBinding = true;
4632 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4633 SCS.BindsToRvalue = true;
4634 SCS.BindsToFunctionLvalue = false;
4635 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636 SCS.ObjCLifetimeConversionBinding = false;
4637 } else
4638 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4639 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004640 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004641 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004642
4643 // C++11 [over.ics.list]p6:
4644 // Otherwise, if the parameter type is not a class:
4645 if (!ToType->isRecordType()) {
4646 // - if the initializer list has one element, the implicit conversion
4647 // sequence is the one required to convert the element to the
4648 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004649 unsigned NumInits = From->getNumInits();
4650 if (NumInits == 1)
4651 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4652 SuppressUserConversions,
4653 InOverloadResolution,
4654 AllowObjCWritebackConversion);
4655 // - if the initializer list has no elements, the implicit conversion
4656 // sequence is the identity conversion.
4657 else if (NumInits == 0) {
4658 Result.setStandard();
4659 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004660 Result.Standard.setFromType(ToType);
4661 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004662 }
4663 return Result;
4664 }
4665
4666 // C++11 [over.ics.list]p7:
4667 // In all cases other than those enumerated above, no conversion is possible
4668 return Result;
4669}
4670
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004671/// TryCopyInitialization - Try to copy-initialize a value of type
4672/// ToType from the expression From. Return the implicit conversion
4673/// sequence required to pass this argument, which may be a bad
4674/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004675/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004676/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004677static ImplicitConversionSequence
4678TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004680 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004681 bool AllowObjCWritebackConversion,
4682 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004683 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4684 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4685 InOverloadResolution,AllowObjCWritebackConversion);
4686
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004687 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004688 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004689 /*FIXME:*/From->getLocStart(),
4690 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004691 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004692
John McCall5c32be02010-08-24 20:38:10 +00004693 return TryImplicitConversion(S, From, ToType,
4694 SuppressUserConversions,
4695 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004696 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004697 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004698 AllowObjCWritebackConversion,
4699 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004700}
4701
Anna Zaks1b068122011-07-28 19:46:48 +00004702static bool TryCopyInitialization(const CanQualType FromQTy,
4703 const CanQualType ToQTy,
4704 Sema &S,
4705 SourceLocation Loc,
4706 ExprValueKind FromVK) {
4707 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4708 ImplicitConversionSequence ICS =
4709 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4710
4711 return !ICS.isBad();
4712}
4713
Douglas Gregor436424c2008-11-18 23:14:02 +00004714/// TryObjectArgumentInitialization - Try to initialize the object
4715/// parameter of the given member function (@c Method) from the
4716/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004717static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004718TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004719 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004720 CXXMethodDecl *Method,
4721 CXXRecordDecl *ActingContext) {
4722 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004723 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4724 // const volatile object.
4725 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4726 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004727 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004728
4729 // Set up the conversion sequence as a "bad" conversion, to allow us
4730 // to exit early.
4731 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004732
4733 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004734 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004735 FromType = PT->getPointeeType();
4736
Douglas Gregor02824322011-01-26 19:30:28 +00004737 // When we had a pointer, it's implicitly dereferenced, so we
4738 // better have an lvalue.
4739 assert(FromClassification.isLValue());
4740 }
4741
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004742 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004743
Douglas Gregor02824322011-01-26 19:30:28 +00004744 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004746 // parameter is
4747 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004748 // - "lvalue reference to cv X" for functions declared without a
4749 // ref-qualifier or with the & ref-qualifier
4750 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // ref-qualifier
4752 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004754 // cv-qualification on the member function declaration.
4755 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004756 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004757 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004758 // (C++ [over.match.funcs]p5). We perform a simplified version of
4759 // reference binding here, that allows class rvalues to bind to
4760 // non-constant references.
4761
Douglas Gregor02824322011-01-26 19:30:28 +00004762 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004763 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004765 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004766 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004767 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004768 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004769 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004770 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004771
4772 // Check that we have either the same type or a derived type. It
4773 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004774 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004775 ImplicitConversionKind SecondKind;
4776 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4777 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004778 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004779 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004780 else {
John McCall65eb8792010-02-25 01:37:24 +00004781 ICS.setBad(BadConversionSequence::unrelated_class,
4782 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004783 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004784 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004785
Douglas Gregor02824322011-01-26 19:30:28 +00004786 // Check the ref-qualifier.
4787 switch (Method->getRefQualifier()) {
4788 case RQ_None:
4789 // Do nothing; we don't care about lvalueness or rvalueness.
4790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Douglas Gregor02824322011-01-26 19:30:28 +00004792 case RQ_LValue:
4793 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4794 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004796 ImplicitParamType);
4797 return ICS;
4798 }
4799 break;
4800
4801 case RQ_RValue:
4802 if (!FromClassification.isRValue()) {
4803 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004805 ImplicitParamType);
4806 return ICS;
4807 }
4808 break;
4809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
Douglas Gregor436424c2008-11-18 23:14:02 +00004811 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004812 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004813 ICS.Standard.setAsIdentityConversion();
4814 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004815 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004816 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004817 ICS.Standard.ReferenceBinding = true;
4818 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004820 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004821 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4822 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4823 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004824 return ICS;
4825}
4826
4827/// PerformObjectArgumentInitialization - Perform initialization of
4828/// the implicit object parameter for the given Method with the given
4829/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004830ExprResult
4831Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004833 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004834 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004835 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004836 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004837 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004838
Douglas Gregor02824322011-01-26 19:30:28 +00004839 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004840 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004841 FromRecordType = PT->getPointeeType();
4842 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004843 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004844 } else {
4845 FromRecordType = From->getType();
4846 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004847 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 }
4849
John McCall6e9f8f62009-12-03 04:06:58 +00004850 // Note that we always use the true parent context when performing
4851 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004852 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004853 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4854 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004855 if (ICS.isBad()) {
4856 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4857 Qualifiers FromQs = FromRecordType.getQualifiers();
4858 Qualifiers ToQs = DestType.getQualifiers();
4859 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4860 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004861 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004862 diag::err_member_function_call_bad_cvr)
4863 << Method->getDeclName() << FromRecordType << (CVR - 1)
4864 << From->getSourceRange();
4865 Diag(Method->getLocation(), diag::note_previous_decl)
4866 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004867 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004868 }
4869 }
4870
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004871 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004872 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004873 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
John Wiegley01296292011-04-08 18:41:53 +00004876 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4877 ExprResult FromRes =
4878 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4879 if (FromRes.isInvalid())
4880 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004881 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004882 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004883
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004884 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004885 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004886 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004887 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004888}
4889
Douglas Gregor5fb53972009-01-14 15:45:31 +00004890/// TryContextuallyConvertToBool - Attempt to contextually convert the
4891/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004892static ImplicitConversionSequence
4893TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004894 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004895 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004896 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004897 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004898 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004899 /*AllowObjCWritebackConversion=*/false,
4900 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004901}
4902
4903/// PerformContextuallyConvertToBool - Perform a contextual conversion
4904/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004905ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004906 if (checkPlaceholderForOverload(*this, From))
4907 return ExprError();
4908
John McCall5c32be02010-08-24 20:38:10 +00004909 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004910 if (!ICS.isBad())
4911 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912
Fariborz Jahanian76197412009-11-18 18:26:29 +00004913 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004914 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004915 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004916 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004917 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004918}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004919
Richard Smithf8379a02012-01-18 23:55:52 +00004920/// Check that the specified conversion is permitted in a converted constant
4921/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4922/// is acceptable.
4923static bool CheckConvertedConstantConversions(Sema &S,
4924 StandardConversionSequence &SCS) {
4925 // Since we know that the target type is an integral or unscoped enumeration
4926 // type, most conversion kinds are impossible. All possible First and Third
4927 // conversions are fine.
4928 switch (SCS.Second) {
4929 case ICK_Identity:
4930 case ICK_Integral_Promotion:
4931 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004932 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004933 return true;
4934
4935 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004936 // Conversion from an integral or unscoped enumeration type to bool is
4937 // classified as ICK_Boolean_Conversion, but it's also an integral
4938 // conversion, so it's permitted in a converted constant expression.
4939 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4940 SCS.getToType(2)->isBooleanType();
4941
Richard Smithf8379a02012-01-18 23:55:52 +00004942 case ICK_Floating_Integral:
4943 case ICK_Complex_Real:
4944 return false;
4945
4946 case ICK_Lvalue_To_Rvalue:
4947 case ICK_Array_To_Pointer:
4948 case ICK_Function_To_Pointer:
4949 case ICK_NoReturn_Adjustment:
4950 case ICK_Qualification:
4951 case ICK_Compatible_Conversion:
4952 case ICK_Vector_Conversion:
4953 case ICK_Vector_Splat:
4954 case ICK_Derived_To_Base:
4955 case ICK_Pointer_Conversion:
4956 case ICK_Pointer_Member:
4957 case ICK_Block_Pointer_Conversion:
4958 case ICK_Writeback_Conversion:
4959 case ICK_Floating_Promotion:
4960 case ICK_Complex_Promotion:
4961 case ICK_Complex_Conversion:
4962 case ICK_Floating_Conversion:
4963 case ICK_TransparentUnionConversion:
4964 llvm_unreachable("unexpected second conversion kind");
4965
4966 case ICK_Num_Conversion_Kinds:
4967 break;
4968 }
4969
4970 llvm_unreachable("unknown conversion kind");
4971}
4972
4973/// CheckConvertedConstantExpression - Check that the expression From is a
4974/// converted constant expression of type T, perform the conversion and produce
4975/// the converted expression, per C++11 [expr.const]p3.
4976ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4977 llvm::APSInt &Value,
4978 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004979 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004980 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4981
4982 if (checkPlaceholderForOverload(*this, From))
4983 return ExprError();
4984
4985 // C++11 [expr.const]p3 with proposed wording fixes:
4986 // A converted constant expression of type T is a core constant expression,
4987 // implicitly converted to a prvalue of type T, where the converted
4988 // expression is a literal constant expression and the implicit conversion
4989 // sequence contains only user-defined conversions, lvalue-to-rvalue
4990 // conversions, integral promotions, and integral conversions other than
4991 // narrowing conversions.
4992 ImplicitConversionSequence ICS =
4993 TryImplicitConversion(From, T,
4994 /*SuppressUserConversions=*/false,
4995 /*AllowExplicit=*/false,
4996 /*InOverloadResolution=*/false,
4997 /*CStyle=*/false,
4998 /*AllowObjcWritebackConversion=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00004999 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005000 switch (ICS.getKind()) {
5001 case ImplicitConversionSequence::StandardConversion:
5002 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005003 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005004 diag::err_typecheck_converted_constant_expression_disallowed)
5005 << From->getType() << From->getSourceRange() << T;
5006 SCS = &ICS.Standard;
5007 break;
5008 case ImplicitConversionSequence::UserDefinedConversion:
5009 // We are converting from class type to an integral or enumeration type, so
5010 // the Before sequence must be trivial.
5011 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005012 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005013 diag::err_typecheck_converted_constant_expression_disallowed)
5014 << From->getType() << From->getSourceRange() << T;
5015 SCS = &ICS.UserDefined.After;
5016 break;
5017 case ImplicitConversionSequence::AmbiguousConversion:
5018 case ImplicitConversionSequence::BadConversion:
5019 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005020 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005021 diag::err_typecheck_converted_constant_expression)
5022 << From->getType() << From->getSourceRange() << T;
5023 return ExprError();
5024
5025 case ImplicitConversionSequence::EllipsisConversion:
5026 llvm_unreachable("ellipsis conversion in converted constant expression");
5027 }
5028
5029 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5030 if (Result.isInvalid())
5031 return Result;
5032
5033 // Check for a narrowing implicit conversion.
5034 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005035 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005036 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5037 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005038 case NK_Variable_Narrowing:
5039 // Implicit conversion to a narrower type, and the value is not a constant
5040 // expression. We'll diagnose this in a moment.
5041 case NK_Not_Narrowing:
5042 break;
5043
5044 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005045 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005046 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005047 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005048 break;
5049
5050 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005051 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005052 << CCE << /*Constant*/0 << From->getType() << T;
5053 break;
5054 }
5055
5056 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005057 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005058 Expr::EvalResult Eval;
5059 Eval.Diag = &Notes;
5060
Douglas Gregorebe2db72013-04-08 23:24:07 +00005061 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005062 // The expression can't be folded, so we can't keep it at this position in
5063 // the AST.
5064 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005065 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005066 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005067
5068 if (Notes.empty()) {
5069 // It's a constant expression.
5070 return Result;
5071 }
Richard Smithf8379a02012-01-18 23:55:52 +00005072 }
5073
5074 // It's not a constant expression. Produce an appropriate diagnostic.
5075 if (Notes.size() == 1 &&
5076 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5077 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5078 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005079 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005080 << CCE << From->getSourceRange();
5081 for (unsigned I = 0; I < Notes.size(); ++I)
5082 Diag(Notes[I].first, Notes[I].second);
5083 }
Richard Smith911e1422012-01-30 22:27:01 +00005084 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005085}
5086
John McCallfec112d2011-09-09 06:11:02 +00005087/// dropPointerConversions - If the given standard conversion sequence
5088/// involves any pointer conversions, remove them. This may change
5089/// the result type of the conversion sequence.
5090static void dropPointerConversion(StandardConversionSequence &SCS) {
5091 if (SCS.Second == ICK_Pointer_Conversion) {
5092 SCS.Second = ICK_Identity;
5093 SCS.Third = ICK_Identity;
5094 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5095 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005096}
John McCall5c32be02010-08-24 20:38:10 +00005097
John McCallfec112d2011-09-09 06:11:02 +00005098/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5099/// convert the expression From to an Objective-C pointer type.
5100static ImplicitConversionSequence
5101TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5102 // Do an implicit conversion to 'id'.
5103 QualType Ty = S.Context.getObjCIdType();
5104 ImplicitConversionSequence ICS
5105 = TryImplicitConversion(S, From, Ty,
5106 // FIXME: Are these flags correct?
5107 /*SuppressUserConversions=*/false,
5108 /*AllowExplicit=*/true,
5109 /*InOverloadResolution=*/false,
5110 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005111 /*AllowObjCWritebackConversion=*/false,
5112 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005113
5114 // Strip off any final conversions to 'id'.
5115 switch (ICS.getKind()) {
5116 case ImplicitConversionSequence::BadConversion:
5117 case ImplicitConversionSequence::AmbiguousConversion:
5118 case ImplicitConversionSequence::EllipsisConversion:
5119 break;
5120
5121 case ImplicitConversionSequence::UserDefinedConversion:
5122 dropPointerConversion(ICS.UserDefined.After);
5123 break;
5124
5125 case ImplicitConversionSequence::StandardConversion:
5126 dropPointerConversion(ICS.Standard);
5127 break;
5128 }
5129
5130 return ICS;
5131}
5132
5133/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5134/// conversion of the expression From to an Objective-C pointer type.
5135ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005136 if (checkPlaceholderForOverload(*this, From))
5137 return ExprError();
5138
John McCall8b07ec22010-05-15 11:32:37 +00005139 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005140 ImplicitConversionSequence ICS =
5141 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005142 if (!ICS.isBad())
5143 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005144 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005145}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005146
Richard Smith8dd34252012-02-04 07:07:42 +00005147/// Determine whether the provided type is an integral type, or an enumeration
5148/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005149bool Sema::ICEConvertDiagnoser::match(QualType T) {
5150 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5151 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005152}
5153
Larisse Voufo236bec22013-06-10 06:50:24 +00005154static ExprResult
5155diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5156 Sema::ContextualImplicitConverter &Converter,
5157 QualType T, UnresolvedSetImpl &ViableConversions) {
5158
5159 if (Converter.Suppress)
5160 return ExprError();
5161
5162 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5163 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5164 CXXConversionDecl *Conv =
5165 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5166 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5167 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5168 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005169 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005170}
5171
5172static bool
5173diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5174 Sema::ContextualImplicitConverter &Converter,
5175 QualType T, bool HadMultipleCandidates,
5176 UnresolvedSetImpl &ExplicitConversions) {
5177 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5178 DeclAccessPair Found = ExplicitConversions[0];
5179 CXXConversionDecl *Conversion =
5180 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181
5182 // The user probably meant to invoke the given explicit
5183 // conversion; use it.
5184 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5185 std::string TypeStr;
5186 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5187
5188 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5189 << FixItHint::CreateInsertion(From->getLocStart(),
5190 "static_cast<" + TypeStr + ">(")
5191 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005192 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005193 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5194
5195 // If we aren't in a SFINAE context, build a call to the
5196 // explicit conversion function.
5197 if (SemaRef.isSFINAEContext())
5198 return true;
5199
Craig Topperc3ec1492014-05-26 06:22:03 +00005200 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005201 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5202 HadMultipleCandidates);
5203 if (Result.isInvalid())
5204 return true;
5205 // Record usage of conversion in an implicit cast.
5206 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005207 CK_UserDefinedConversion, Result.get(),
5208 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005209 }
5210 return false;
5211}
5212
5213static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5214 Sema::ContextualImplicitConverter &Converter,
5215 QualType T, bool HadMultipleCandidates,
5216 DeclAccessPair &Found) {
5217 CXXConversionDecl *Conversion =
5218 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005219 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005220
5221 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5222 if (!Converter.SuppressConversion) {
5223 if (SemaRef.isSFINAEContext())
5224 return true;
5225
5226 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5227 << From->getSourceRange();
5228 }
5229
5230 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5231 HadMultipleCandidates);
5232 if (Result.isInvalid())
5233 return true;
5234 // Record usage of conversion in an implicit cast.
5235 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005236 CK_UserDefinedConversion, Result.get(),
5237 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005238 return false;
5239}
5240
5241static ExprResult finishContextualImplicitConversion(
5242 Sema &SemaRef, SourceLocation Loc, Expr *From,
5243 Sema::ContextualImplicitConverter &Converter) {
5244 if (!Converter.match(From->getType()) && !Converter.Suppress)
5245 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5246 << From->getSourceRange();
5247
5248 return SemaRef.DefaultLvalueConversion(From);
5249}
5250
5251static void
5252collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5253 UnresolvedSetImpl &ViableConversions,
5254 OverloadCandidateSet &CandidateSet) {
5255 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5256 DeclAccessPair FoundDecl = ViableConversions[I];
5257 NamedDecl *D = FoundDecl.getDecl();
5258 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5259 if (isa<UsingShadowDecl>(D))
5260 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5261
5262 CXXConversionDecl *Conv;
5263 FunctionTemplateDecl *ConvTemplate;
5264 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5265 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5266 else
5267 Conv = cast<CXXConversionDecl>(D);
5268
5269 if (ConvTemplate)
5270 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005271 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5272 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005273 else
5274 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005275 ToType, CandidateSet,
5276 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005277 }
5278}
5279
Richard Smithccc11812013-05-21 19:05:48 +00005280/// \brief Attempt to convert the given expression to a type which is accepted
5281/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005282///
Richard Smithccc11812013-05-21 19:05:48 +00005283/// This routine will attempt to convert an expression of class type to a
5284/// type accepted by the specified converter. In C++11 and before, the class
5285/// must have a single non-explicit conversion function converting to a matching
5286/// type. In C++1y, there can be multiple such conversion functions, but only
5287/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005288///
Douglas Gregor4799d032010-06-30 00:20:43 +00005289/// \param Loc The source location of the construct that requires the
5290/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005291///
James Dennett18348b62012-06-22 08:52:37 +00005292/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005293///
Richard Smithccc11812013-05-21 19:05:48 +00005294/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005295///
Douglas Gregor4799d032010-06-30 00:20:43 +00005296/// \returns The expression, converted to an integral or enumeration type if
5297/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005298ExprResult Sema::PerformContextualImplicitConversion(
5299 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005300 // We can't perform any more checking for type-dependent expressions.
5301 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005302 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Eli Friedman1da70392012-01-26 00:26:18 +00005304 // Process placeholders immediately.
5305 if (From->hasPlaceholderType()) {
5306 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005307 if (result.isInvalid())
5308 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005309 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005310 }
5311
Richard Smithccc11812013-05-21 19:05:48 +00005312 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005313 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005314 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005315 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005316
5317 // FIXME: Check for missing '()' if T is a function type?
5318
Richard Smithccc11812013-05-21 19:05:48 +00005319 // We can only perform contextual implicit conversions on objects of class
5320 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005321 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005322 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005323 if (!Converter.Suppress)
5324 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005325 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005328 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005329 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005330 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005331 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005332
5333 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5334 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5335
Craig Toppere14c0f82014-03-12 04:55:44 +00005336 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005337 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005338 }
Richard Smithccc11812013-05-21 19:05:48 +00005339 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005340
5341 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005342 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005344 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005345 UnresolvedSet<4>
5346 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005347 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005348 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005349 CXXRecordDecl::conversion_iterator> Conversions =
5350 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005351
Larisse Voufo236bec22013-06-10 06:50:24 +00005352 bool HadMultipleCandidates =
5353 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005354
Larisse Voufo236bec22013-06-10 06:50:24 +00005355 // To check that there is only one target type, in C++1y:
5356 QualType ToType;
5357 bool HasUniqueTargetType = true;
5358
5359 // Collect explicit or viable (potentially in C++1y) conversions.
5360 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5361 E = Conversions.second;
5362 I != E; ++I) {
5363 NamedDecl *D = (*I)->getUnderlyingDecl();
5364 CXXConversionDecl *Conversion;
5365 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5366 if (ConvTemplate) {
5367 if (getLangOpts().CPlusPlus1y)
5368 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5369 else
5370 continue; // C++11 does not consider conversion operator templates(?).
5371 } else
5372 Conversion = cast<CXXConversionDecl>(D);
5373
5374 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5375 "Conversion operator templates are considered potentially "
5376 "viable in C++1y");
5377
5378 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5379 if (Converter.match(CurToType) || ConvTemplate) {
5380
5381 if (Conversion->isExplicit()) {
5382 // FIXME: For C++1y, do we need this restriction?
5383 // cf. diagnoseNoViableConversion()
5384 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005385 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005386 } else {
5387 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5388 if (ToType.isNull())
5389 ToType = CurToType.getUnqualifiedType();
5390 else if (HasUniqueTargetType &&
5391 (CurToType.getUnqualifiedType() != ToType))
5392 HasUniqueTargetType = false;
5393 }
5394 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005395 }
Richard Smith8dd34252012-02-04 07:07:42 +00005396 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Larisse Voufo236bec22013-06-10 06:50:24 +00005399 if (getLangOpts().CPlusPlus1y) {
5400 // C++1y [conv]p6:
5401 // ... An expression e of class type E appearing in such a context
5402 // is said to be contextually implicitly converted to a specified
5403 // type T and is well-formed if and only if e can be implicitly
5404 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005405 // for conversion functions whose return type is cv T or reference to
5406 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005407 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005408
Larisse Voufo236bec22013-06-10 06:50:24 +00005409 // If no unique T is found:
5410 if (ToType.isNull()) {
5411 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5412 HadMultipleCandidates,
5413 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005414 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005415 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005416 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417
Larisse Voufo236bec22013-06-10 06:50:24 +00005418 // If more than one unique Ts are found:
5419 if (!HasUniqueTargetType)
5420 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5421 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005422
Larisse Voufo236bec22013-06-10 06:50:24 +00005423 // If one unique T is found:
5424 // First, build a candidate set from the previously recorded
5425 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005426 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005427 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5428 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005429
Larisse Voufo236bec22013-06-10 06:50:24 +00005430 // Then, perform overload resolution over the candidate set.
5431 OverloadCandidateSet::iterator Best;
5432 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5433 case OR_Success: {
5434 // Apply this conversion.
5435 DeclAccessPair Found =
5436 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5437 if (recordConversion(*this, Loc, From, Converter, T,
5438 HadMultipleCandidates, Found))
5439 return ExprError();
5440 break;
5441 }
5442 case OR_Ambiguous:
5443 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5444 ViableConversions);
5445 case OR_No_Viable_Function:
5446 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5447 HadMultipleCandidates,
5448 ExplicitConversions))
5449 return ExprError();
5450 // fall through 'OR_Deleted' case.
5451 case OR_Deleted:
5452 // We'll complain below about a non-integral condition type.
5453 break;
5454 }
5455 } else {
5456 switch (ViableConversions.size()) {
5457 case 0: {
5458 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5459 HadMultipleCandidates,
5460 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005461 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Larisse Voufo236bec22013-06-10 06:50:24 +00005463 // We'll complain below about a non-integral condition type.
5464 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005465 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005466 case 1: {
5467 // Apply this conversion.
5468 DeclAccessPair Found = ViableConversions[0];
5469 if (recordConversion(*this, Loc, From, Converter, T,
5470 HadMultipleCandidates, Found))
5471 return ExprError();
5472 break;
5473 }
5474 default:
5475 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5476 ViableConversions);
5477 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
Larisse Voufo236bec22013-06-10 06:50:24 +00005480 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005481}
5482
Richard Smith100b24a2014-04-17 01:52:14 +00005483/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5484/// an acceptable non-member overloaded operator for a call whose
5485/// arguments have types T1 (and, if non-empty, T2). This routine
5486/// implements the check in C++ [over.match.oper]p3b2 concerning
5487/// enumeration types.
5488static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5489 FunctionDecl *Fn,
5490 ArrayRef<Expr *> Args) {
5491 QualType T1 = Args[0]->getType();
5492 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5493
5494 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5495 return true;
5496
5497 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5498 return true;
5499
5500 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5501 if (Proto->getNumParams() < 1)
5502 return false;
5503
5504 if (T1->isEnumeralType()) {
5505 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5506 if (Context.hasSameUnqualifiedType(T1, ArgType))
5507 return true;
5508 }
5509
5510 if (Proto->getNumParams() < 2)
5511 return false;
5512
5513 if (!T2.isNull() && T2->isEnumeralType()) {
5514 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5515 if (Context.hasSameUnqualifiedType(T2, ArgType))
5516 return true;
5517 }
5518
5519 return false;
5520}
5521
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005522/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005523/// candidate functions, using the given function call arguments. If
5524/// @p SuppressUserConversions, then don't allow user-defined
5525/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005526///
James Dennett2a4d13c2012-06-15 07:13:21 +00005527/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005528/// based on an incomplete set of function arguments. This feature is used by
5529/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005530void
5531Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005532 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005533 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005534 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005535 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005536 bool PartialOverloading,
5537 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005538 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005539 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005540 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005541 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005542 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005543
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005545 if (!isa<CXXConstructorDecl>(Method)) {
5546 // If we get here, it's because we're calling a member function
5547 // that is named without a member access expression (e.g.,
5548 // "this->f") that was either written explicitly or created
5549 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005550 // function, e.g., X::f(). We use an empty type for the implied
5551 // object argument (C++ [over.call.func]p3), and the acting context
5552 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005553 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005554 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005555 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005556 return;
5557 }
5558 // We treat a constructor like a non-member function, since its object
5559 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005560 }
5561
Douglas Gregorff7028a2009-11-13 23:59:09 +00005562 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005563 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005564
Richard Smith100b24a2014-04-17 01:52:14 +00005565 // C++ [over.match.oper]p3:
5566 // if no operand has a class type, only those non-member functions in the
5567 // lookup set that have a first parameter of type T1 or "reference to
5568 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5569 // is a right operand) a second parameter of type T2 or "reference to
5570 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5571 // candidate functions.
5572 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5573 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5574 return;
5575
Richard Smith8b86f2d2013-11-04 01:48:18 +00005576 // C++11 [class.copy]p11: [DR1402]
5577 // A defaulted move constructor that is defined as deleted is ignored by
5578 // overload resolution.
5579 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5580 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5581 Constructor->isMoveConstructor())
5582 return;
5583
Douglas Gregor27381f32009-11-23 12:27:39 +00005584 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005585 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005586
Richard Smith8b86f2d2013-11-04 01:48:18 +00005587 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005588 // C++ [class.copy]p3:
5589 // A member function template is never instantiated to perform the copy
5590 // of a class object to an object of its class type.
5591 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005592 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005593 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005594 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5595 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005596 return;
5597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005599 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005600 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005601 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005602 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005603 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005604 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005605 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005606 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005608 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005609
5610 // (C++ 13.3.2p2): A candidate function having fewer than m
5611 // parameters is viable only if it has an ellipsis in its parameter
5612 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005613 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005614 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005615 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005616 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005617 return;
5618 }
5619
5620 // (C++ 13.3.2p2): A candidate function having more than m parameters
5621 // is viable only if the (m+1)st parameter has a default argument
5622 // (8.3.6). For the purposes of overload resolution, the
5623 // parameter list is truncated on the right, so that there are
5624 // exactly m parameters.
5625 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005626 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005627 // Not enough arguments.
5628 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005629 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005630 return;
5631 }
5632
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005633 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005634 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005635 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5636 if (CheckCUDATarget(Caller, Function)) {
5637 Candidate.Viable = false;
5638 Candidate.FailureKind = ovl_fail_bad_target;
5639 return;
5640 }
5641
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005642 // Determine the implicit conversion sequences for each of the
5643 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005644 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005645 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005646 // (C++ 13.3.2p3): for F to be a viable function, there shall
5647 // exist for each argument an implicit conversion sequence
5648 // (13.3.3.1) that converts that argument to the corresponding
5649 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005650 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005651 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005652 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005654 /*InOverloadResolution=*/true,
5655 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005656 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005657 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005658 if (Candidate.Conversions[ArgIdx].isBad()) {
5659 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005660 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005661 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005662 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005663 } else {
5664 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5665 // argument for which there is no corresponding parameter is
5666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005667 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005668 }
5669 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005670
5671 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5672 Candidate.Viable = false;
5673 Candidate.FailureKind = ovl_fail_enable_if;
5674 Candidate.DeductionFailure.Data = FailedAttr;
5675 return;
5676 }
5677}
5678
5679static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5680
5681EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5682 bool MissingImplicitThis) {
5683 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5684 // we need to find the first failing one.
5685 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005686 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005687 AttrVec Attrs = Function->getAttrs();
5688 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5689 IsNotEnableIfAttr);
5690 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005691 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005692 std::reverse(Attrs.begin(), E);
5693
5694 SFINAETrap Trap(*this);
5695
5696 // Convert the arguments.
5697 SmallVector<Expr *, 16> ConvertedArgs;
5698 bool InitializationFailed = false;
5699 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5700 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005701 !cast<CXXMethodDecl>(Function)->isStatic() &&
5702 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005703 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5704 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005705 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005706 Method, Method);
5707 if (R.isInvalid()) {
5708 InitializationFailed = true;
5709 break;
5710 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005711 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005712 } else {
5713 ExprResult R =
5714 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5715 Context,
5716 Function->getParamDecl(i)),
5717 SourceLocation(),
5718 Args[i]);
5719 if (R.isInvalid()) {
5720 InitializationFailed = true;
5721 break;
5722 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005723 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005724 }
5725 }
5726
5727 if (InitializationFailed || Trap.hasErrorOccurred())
5728 return cast<EnableIfAttr>(Attrs[0]);
5729
5730 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5731 APValue Result;
5732 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5733 if (!EIA->getCond()->EvaluateWithSubstitution(
5734 Result, Context, Function,
5735 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5736 ConvertedArgs.size())) ||
5737 !Result.isInt() || !Result.getInt().getBoolValue()) {
5738 return EIA;
5739 }
5740 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005741 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005742}
5743
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005744/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005745/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005746void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005747 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005748 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005749 bool SuppressUserConversions,
5750 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005751 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005752 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5753 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005754 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005755 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005756 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005757 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005758 Args.slice(1), CandidateSet,
5759 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005760 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005761 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005762 SuppressUserConversions);
5763 } else {
John McCalla0296f72010-03-19 07:35:19 +00005764 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005765 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5766 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005767 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005768 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005769 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005771 Args[0]->Classify(Context), Args.slice(1),
5772 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005773 else
John McCalla0296f72010-03-19 07:35:19 +00005774 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005775 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005776 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005777 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005778 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005779}
5780
John McCallf0f1cf02009-11-17 07:50:12 +00005781/// AddMethodCandidate - Adds a named decl (which is some kind of
5782/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005783void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005784 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005785 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005786 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005787 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005788 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005789 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005790 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005791
5792 if (isa<UsingShadowDecl>(Decl))
5793 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005794
John McCallf0f1cf02009-11-17 07:50:12 +00005795 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5796 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5797 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005798 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005799 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005800 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005801 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005802 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005803 } else {
John McCalla0296f72010-03-19 07:35:19 +00005804 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005805 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005806 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005807 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005808 }
5809}
5810
Douglas Gregor436424c2008-11-18 23:14:02 +00005811/// AddMethodCandidate - Adds the given C++ member function to the set
5812/// of candidate functions, using the given function call arguments
5813/// and the object argument (@c Object). For example, in a call
5814/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5815/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5816/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005817/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005818void
John McCalla0296f72010-03-19 07:35:19 +00005819Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005820 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005821 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005822 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005823 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005824 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005826 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005827 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005828 assert(!isa<CXXConstructorDecl>(Method) &&
5829 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005830
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005831 if (!CandidateSet.isNewCandidate(Method))
5832 return;
5833
Richard Smith8b86f2d2013-11-04 01:48:18 +00005834 // C++11 [class.copy]p23: [DR1402]
5835 // A defaulted move assignment operator that is defined as deleted is
5836 // ignored by overload resolution.
5837 if (Method->isDefaulted() && Method->isDeleted() &&
5838 Method->isMoveAssignmentOperator())
5839 return;
5840
Douglas Gregor27381f32009-11-23 12:27:39 +00005841 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005842 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005843
Douglas Gregor436424c2008-11-18 23:14:02 +00005844 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005845 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005846 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005847 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005848 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005849 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005850 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005851
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005852 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005853
5854 // (C++ 13.3.2p2): A candidate function having fewer than m
5855 // parameters is viable only if it has an ellipsis in its parameter
5856 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005857 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005858 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005859 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005860 return;
5861 }
5862
5863 // (C++ 13.3.2p2): A candidate function having more than m parameters
5864 // is viable only if the (m+1)st parameter has a default argument
5865 // (8.3.6). For the purposes of overload resolution, the
5866 // parameter list is truncated on the right, so that there are
5867 // exactly m parameters.
5868 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005869 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005870 // Not enough arguments.
5871 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005872 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005873 return;
5874 }
5875
5876 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005877
John McCall6e9f8f62009-12-03 04:06:58 +00005878 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005879 // The implicit object argument is ignored.
5880 Candidate.IgnoreObjectArgument = true;
5881 else {
5882 // Determine the implicit conversion sequence for the object
5883 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005884 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005885 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5886 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005887 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005888 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005889 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005890 return;
5891 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005892 }
5893
5894 // Determine the implicit conversion sequences for each of the
5895 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005896 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005897 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005898 // (C++ 13.3.2p3): for F to be a viable function, there shall
5899 // exist for each argument an implicit conversion sequence
5900 // (13.3.3.1) that converts that argument to the corresponding
5901 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005902 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005903 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005904 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005906 /*InOverloadResolution=*/true,
5907 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005908 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005909 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005910 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005911 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005912 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005913 }
5914 } else {
5915 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005917 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005918 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005919 }
5920 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005921
5922 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5923 Candidate.Viable = false;
5924 Candidate.FailureKind = ovl_fail_enable_if;
5925 Candidate.DeductionFailure.Data = FailedAttr;
5926 return;
5927 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005928}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929
Douglas Gregor97628d62009-08-21 00:16:32 +00005930/// \brief Add a C++ member function template as a candidate to the candidate
5931/// set, using template argument deduction to produce an appropriate member
5932/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005933void
Douglas Gregor97628d62009-08-21 00:16:32 +00005934Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005935 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005936 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005937 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005938 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005939 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005940 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005941 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005942 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005943 if (!CandidateSet.isNewCandidate(MethodTmpl))
5944 return;
5945
Douglas Gregor97628d62009-08-21 00:16:32 +00005946 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005947 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005948 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005949 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005950 // candidate functions in the usual way.113) A given name can refer to one
5951 // or more function templates and also to a set of overloaded non-template
5952 // functions. In such a case, the candidate functions generated from each
5953 // function template are combined with the set of non-template candidate
5954 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005955 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00005956 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00005957 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005958 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5959 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005960 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005961 Candidate.FoundDecl = FoundDecl;
5962 Candidate.Function = MethodTmpl->getTemplatedDecl();
5963 Candidate.Viable = false;
5964 Candidate.FailureKind = ovl_fail_bad_deduction;
5965 Candidate.IsSurrogate = false;
5966 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005967 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005968 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005969 Info);
5970 return;
5971 }
Mike Stump11289f42009-09-09 15:08:12 +00005972
Douglas Gregor97628d62009-08-21 00:16:32 +00005973 // Add the function template specialization produced by template argument
5974 // deduction as a candidate.
5975 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005976 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005977 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005978 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005979 ActingContext, ObjectType, ObjectClassification, Args,
5980 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005981}
5982
Douglas Gregor05155d82009-08-21 23:19:43 +00005983/// \brief Add a C++ function template specialization as a candidate
5984/// in the candidate set, using template argument deduction to produce
5985/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005986void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005987Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005988 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005989 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005990 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005991 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005992 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005993 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5994 return;
5995
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005996 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005997 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005998 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005999 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006000 // candidate functions in the usual way.113) A given name can refer to one
6001 // or more function templates and also to a set of overloaded non-template
6002 // functions. In such a case, the candidate functions generated from each
6003 // function template are combined with the set of non-template candidate
6004 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006005 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006006 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006007 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006008 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6009 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006010 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006011 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006012 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6013 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006014 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006015 Candidate.IsSurrogate = false;
6016 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006017 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006019 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006020 return;
6021 }
Mike Stump11289f42009-09-09 15:08:12 +00006022
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006023 // Add the function template specialization produced by template argument
6024 // deduction as a candidate.
6025 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006026 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006027 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006028}
Mike Stump11289f42009-09-09 15:08:12 +00006029
Douglas Gregor4b60a152013-11-07 22:34:54 +00006030/// Determine whether this is an allowable conversion from the result
6031/// of an explicit conversion operator to the expected type, per C++
6032/// [over.match.conv]p1 and [over.match.ref]p1.
6033///
6034/// \param ConvType The return type of the conversion function.
6035///
6036/// \param ToType The type we are converting to.
6037///
6038/// \param AllowObjCPointerConversion Allow a conversion from one
6039/// Objective-C pointer to another.
6040///
6041/// \returns true if the conversion is allowable, false otherwise.
6042static bool isAllowableExplicitConversion(Sema &S,
6043 QualType ConvType, QualType ToType,
6044 bool AllowObjCPointerConversion) {
6045 QualType ToNonRefType = ToType.getNonReferenceType();
6046
6047 // Easy case: the types are the same.
6048 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6049 return true;
6050
6051 // Allow qualification conversions.
6052 bool ObjCLifetimeConversion;
6053 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6054 ObjCLifetimeConversion))
6055 return true;
6056
6057 // If we're not allowed to consider Objective-C pointer conversions,
6058 // we're done.
6059 if (!AllowObjCPointerConversion)
6060 return false;
6061
6062 // Is this an Objective-C pointer conversion?
6063 bool IncompatibleObjC = false;
6064 QualType ConvertedType;
6065 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6066 IncompatibleObjC);
6067}
6068
Douglas Gregora1f013e2008-11-07 22:36:19 +00006069/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006070/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006071/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006072/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006073/// (which may or may not be the same type as the type that the
6074/// conversion function produces).
6075void
6076Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006077 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006078 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006079 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006080 OverloadCandidateSet& CandidateSet,
6081 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006082 assert(!Conversion->getDescribedFunctionTemplate() &&
6083 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006084 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006085 if (!CandidateSet.isNewCandidate(Conversion))
6086 return;
6087
Richard Smith2a7d4812013-05-04 07:00:32 +00006088 // If the conversion function has an undeduced return type, trigger its
6089 // deduction now.
6090 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6091 if (DeduceReturnType(Conversion, From->getExprLoc()))
6092 return;
6093 ConvType = Conversion->getConversionType().getNonReferenceType();
6094 }
6095
Richard Smith089c3162013-09-21 21:55:46 +00006096 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6097 // operator is only a candidate if its return type is the target type or
6098 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006099 if (Conversion->isExplicit() &&
6100 !isAllowableExplicitConversion(*this, ConvType, ToType,
6101 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006102 return;
6103
Douglas Gregor27381f32009-11-23 12:27:39 +00006104 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006105 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006106
Douglas Gregora1f013e2008-11-07 22:36:19 +00006107 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006108 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006109 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006110 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006111 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006112 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006113 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006114 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006115 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006116 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006117 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006118
Douglas Gregor6affc782010-08-19 15:37:02 +00006119 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120 // For conversion functions, the function is considered to be a member of
6121 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006122 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006123 //
6124 // Determine the implicit conversion sequence for the implicit
6125 // object parameter.
6126 QualType ImplicitParamType = From->getType();
6127 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6128 ImplicitParamType = FromPtrType->getPointeeType();
6129 CXXRecordDecl *ConversionContext
6130 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006131
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006132 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006133 = TryObjectArgumentInitialization(*this, From->getType(),
6134 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006135 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136
John McCall0d1da222010-01-12 00:44:57 +00006137 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006138 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006139 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006140 return;
6141 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006142
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006143 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006144 // derived to base as such conversions are given Conversion Rank. They only
6145 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6146 QualType FromCanon
6147 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6148 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6149 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6150 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006151 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006152 return;
6153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154
Douglas Gregora1f013e2008-11-07 22:36:19 +00006155 // To determine what the conversion from the result of calling the
6156 // conversion function to the type we're eventually trying to
6157 // convert to (ToType), we need to synthesize a call to the
6158 // conversion function and attempt copy initialization from it. This
6159 // makes sure that we get the right semantics with respect to
6160 // lvalues/rvalues and the type. Fortunately, we can allocate this
6161 // call on the stack and we don't need its arguments to be
6162 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006163 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006164 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006165 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6166 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006167 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006168 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006169
Richard Smith48d24642011-07-13 22:53:21 +00006170 QualType ConversionType = Conversion->getConversionType();
6171 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006172 Candidate.Viable = false;
6173 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6174 return;
6175 }
6176
Richard Smith48d24642011-07-13 22:53:21 +00006177 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006178
Mike Stump11289f42009-09-09 15:08:12 +00006179 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006180 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6181 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006182 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006183 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006184 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006185 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006186 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006187 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006188 /*InOverloadResolution=*/false,
6189 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006190
John McCall0d1da222010-01-12 00:44:57 +00006191 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006192 case ImplicitConversionSequence::StandardConversion:
6193 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006195 // C++ [over.ics.user]p3:
6196 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006198 // shall have exact match rank.
6199 if (Conversion->getPrimaryTemplate() &&
6200 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6201 Candidate.Viable = false;
6202 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006203 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205
Douglas Gregorcba72b12011-01-21 05:18:22 +00006206 // C++0x [dcl.init.ref]p5:
6207 // In the second case, if the reference is an rvalue reference and
6208 // the second standard conversion sequence of the user-defined
6209 // conversion sequence includes an lvalue-to-rvalue conversion, the
6210 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006211 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006212 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6213 Candidate.Viable = false;
6214 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006215 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006216 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006217 break;
6218
6219 case ImplicitConversionSequence::BadConversion:
6220 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006221 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006222 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006223
6224 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006225 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006226 "Can only end up with a standard conversion sequence or failure");
6227 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006228
6229 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6230 Candidate.Viable = false;
6231 Candidate.FailureKind = ovl_fail_enable_if;
6232 Candidate.DeductionFailure.Data = FailedAttr;
6233 return;
6234 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006235}
6236
Douglas Gregor05155d82009-08-21 23:19:43 +00006237/// \brief Adds a conversion function template specialization
6238/// candidate to the overload set, using template argument deduction
6239/// to deduce the template arguments of the conversion function
6240/// template from the type that we are converting to (C++
6241/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006242void
Douglas Gregor05155d82009-08-21 23:19:43 +00006243Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006244 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006245 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006246 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006247 OverloadCandidateSet &CandidateSet,
6248 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006249 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6250 "Only conversion function templates permitted here");
6251
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006252 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6253 return;
6254
Craig Toppere6706e42012-09-19 02:26:47 +00006255 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006256 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006257 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006258 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006259 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006260 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006261 Candidate.FoundDecl = FoundDecl;
6262 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6263 Candidate.Viable = false;
6264 Candidate.FailureKind = ovl_fail_bad_deduction;
6265 Candidate.IsSurrogate = false;
6266 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006267 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006268 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006269 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006270 return;
6271 }
Mike Stump11289f42009-09-09 15:08:12 +00006272
Douglas Gregor05155d82009-08-21 23:19:43 +00006273 // Add the conversion function template specialization produced by
6274 // template argument deduction as a candidate.
6275 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006276 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006277 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006278}
6279
Douglas Gregorab7897a2008-11-19 22:57:39 +00006280/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6281/// converts the given @c Object to a function pointer via the
6282/// conversion function @c Conversion, and then attempts to call it
6283/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6284/// the type of function that we'll eventually be calling.
6285void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006286 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006287 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006288 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006289 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006290 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006291 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006292 if (!CandidateSet.isNewCandidate(Conversion))
6293 return;
6294
Douglas Gregor27381f32009-11-23 12:27:39 +00006295 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006296 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006297
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006298 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006299 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006300 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006301 Candidate.Surrogate = Conversion;
6302 Candidate.Viable = true;
6303 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006304 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006305 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006306
6307 // Determine the implicit conversion sequence for the implicit
6308 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006309 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006310 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006311 Object->Classify(Context),
6312 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006313 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006314 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006315 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006316 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006317 return;
6318 }
6319
6320 // The first conversion is actually a user-defined conversion whose
6321 // first conversion is ObjectInit's standard conversion (which is
6322 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006323 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006324 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006325 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006326 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006327 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006328 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006329 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006330 = Candidate.Conversions[0].UserDefined.Before;
6331 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6332
Mike Stump11289f42009-09-09 15:08:12 +00006333 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006334 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006335
6336 // (C++ 13.3.2p2): A candidate function having fewer than m
6337 // parameters is viable only if it has an ellipsis in its parameter
6338 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006339 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006340 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006341 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006342 return;
6343 }
6344
6345 // Function types don't have any default arguments, so just check if
6346 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006347 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006348 // Not enough arguments.
6349 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006350 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006351 return;
6352 }
6353
6354 // Determine the implicit conversion sequences for each of the
6355 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006356 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006357 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006358 // (C++ 13.3.2p3): for F to be a viable function, there shall
6359 // exist for each argument an implicit conversion sequence
6360 // (13.3.3.1) that converts that argument to the corresponding
6361 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006362 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006363 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006364 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006365 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006366 /*InOverloadResolution=*/false,
6367 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006368 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006369 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006370 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006371 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006372 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006373 }
6374 } else {
6375 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6376 // argument for which there is no corresponding parameter is
6377 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006378 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006379 }
6380 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006381
6382 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6383 Candidate.Viable = false;
6384 Candidate.FailureKind = ovl_fail_enable_if;
6385 Candidate.DeductionFailure.Data = FailedAttr;
6386 return;
6387 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006388}
6389
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006390/// \brief Add overload candidates for overloaded operators that are
6391/// member functions.
6392///
6393/// Add the overloaded operator candidates that are member functions
6394/// for the operator Op that was used in an operator expression such
6395/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6396/// CandidateSet will store the added overload candidates. (C++
6397/// [over.match.oper]).
6398void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6399 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006400 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006401 OverloadCandidateSet& CandidateSet,
6402 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6404
6405 // C++ [over.match.oper]p3:
6406 // For a unary operator @ with an operand of a type whose
6407 // cv-unqualified version is T1, and for a binary operator @ with
6408 // a left operand of a type whose cv-unqualified version is T1 and
6409 // a right operand of a type whose cv-unqualified version is T2,
6410 // three sets of candidate functions, designated member
6411 // candidates, non-member candidates and built-in candidates, are
6412 // constructed as follows:
6413 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006414
Richard Smith0feaf0c2013-04-20 12:41:22 +00006415 // -- If T1 is a complete class type or a class currently being
6416 // defined, the set of member candidates is the result of the
6417 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6418 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006419 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006420 // Complete the type if it can be completed.
6421 RequireCompleteType(OpLoc, T1, 0);
6422 // If the type is neither complete nor being defined, bail out now.
6423 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006424 return;
Mike Stump11289f42009-09-09 15:08:12 +00006425
John McCall27b18f82009-11-17 02:14:36 +00006426 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6427 LookupQualifiedName(Operators, T1Rec->getDecl());
6428 Operators.suppressDiagnostics();
6429
Mike Stump11289f42009-09-09 15:08:12 +00006430 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006431 OperEnd = Operators.end();
6432 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006433 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006434 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006435 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006436 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006437 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006438 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006439 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006440}
6441
Douglas Gregora11693b2008-11-12 17:17:38 +00006442/// AddBuiltinCandidate - Add a candidate for a built-in
6443/// operator. ResultTy and ParamTys are the result and parameter types
6444/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006445/// arguments being passed to the candidate. IsAssignmentOperator
6446/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006447/// operator. NumContextualBoolArguments is the number of arguments
6448/// (at the beginning of the argument list) that will be contextually
6449/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006450void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006451 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006452 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006453 bool IsAssignmentOperator,
6454 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006455 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006456 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006457
Douglas Gregora11693b2008-11-12 17:17:38 +00006458 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006459 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006460 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6461 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006462 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006463 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006464 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006465 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006466 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6467
6468 // Determine the implicit conversion sequences for each of the
6469 // arguments.
6470 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006471 Candidate.ExplicitCallArguments = Args.size();
6472 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006473 // C++ [over.match.oper]p4:
6474 // For the built-in assignment operators, conversions of the
6475 // left operand are restricted as follows:
6476 // -- no temporaries are introduced to hold the left operand, and
6477 // -- no user-defined conversions are applied to the left
6478 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006479 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006480 //
6481 // We block these conversions by turning off user-defined
6482 // conversions, since that is the only way that initialization of
6483 // a reference to a non-class type can occur from something that
6484 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006485 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006486 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006487 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006488 Candidate.Conversions[ArgIdx]
6489 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006490 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006491 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006492 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006493 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006494 /*InOverloadResolution=*/false,
6495 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006496 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006497 }
John McCall0d1da222010-01-12 00:44:57 +00006498 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006499 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006500 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006501 break;
6502 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006503 }
6504}
6505
Craig Toppercd7b0332013-07-01 06:29:40 +00006506namespace {
6507
Douglas Gregora11693b2008-11-12 17:17:38 +00006508/// BuiltinCandidateTypeSet - A set of types that will be used for the
6509/// candidate operator functions for built-in operators (C++
6510/// [over.built]). The types are separated into pointer types and
6511/// enumeration types.
6512class BuiltinCandidateTypeSet {
6513 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006514 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006515
6516 /// PointerTypes - The set of pointer types that will be used in the
6517 /// built-in candidates.
6518 TypeSet PointerTypes;
6519
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006520 /// MemberPointerTypes - The set of member pointer types that will be
6521 /// used in the built-in candidates.
6522 TypeSet MemberPointerTypes;
6523
Douglas Gregora11693b2008-11-12 17:17:38 +00006524 /// EnumerationTypes - The set of enumeration types that will be
6525 /// used in the built-in candidates.
6526 TypeSet EnumerationTypes;
6527
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006529 /// candidates.
6530 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006531
6532 /// \brief A flag indicating non-record types are viable candidates
6533 bool HasNonRecordTypes;
6534
6535 /// \brief A flag indicating whether either arithmetic or enumeration types
6536 /// were present in the candidate set.
6537 bool HasArithmeticOrEnumeralTypes;
6538
Douglas Gregor80af3132011-05-21 23:15:46 +00006539 /// \brief A flag indicating whether the nullptr type was present in the
6540 /// candidate set.
6541 bool HasNullPtrType;
6542
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006543 /// Sema - The semantic analysis instance where we are building the
6544 /// candidate type set.
6545 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006546
Douglas Gregora11693b2008-11-12 17:17:38 +00006547 /// Context - The AST context in which we will build the type sets.
6548 ASTContext &Context;
6549
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006550 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6551 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006552 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006553
6554public:
6555 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006556 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006557
Mike Stump11289f42009-09-09 15:08:12 +00006558 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006559 : HasNonRecordTypes(false),
6560 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006561 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006562 SemaRef(SemaRef),
6563 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006564
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006566 SourceLocation Loc,
6567 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006568 bool AllowExplicitConversions,
6569 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006570
6571 /// pointer_begin - First pointer type found;
6572 iterator pointer_begin() { return PointerTypes.begin(); }
6573
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006574 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006575 iterator pointer_end() { return PointerTypes.end(); }
6576
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006577 /// member_pointer_begin - First member pointer type found;
6578 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6579
6580 /// member_pointer_end - Past the last member pointer type found;
6581 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6582
Douglas Gregora11693b2008-11-12 17:17:38 +00006583 /// enumeration_begin - First enumeration type found;
6584 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6585
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006586 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006587 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006588
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006589 iterator vector_begin() { return VectorTypes.begin(); }
6590 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006591
6592 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6593 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006594 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006595};
6596
Craig Toppercd7b0332013-07-01 06:29:40 +00006597} // end anonymous namespace
6598
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006599/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006600/// the set of pointer types along with any more-qualified variants of
6601/// that type. For example, if @p Ty is "int const *", this routine
6602/// will add "int const *", "int const volatile *", "int const
6603/// restrict *", and "int const volatile restrict *" to the set of
6604/// pointer types. Returns true if the add of @p Ty itself succeeded,
6605/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006606///
6607/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006608bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006609BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6610 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006611
Douglas Gregora11693b2008-11-12 17:17:38 +00006612 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006613 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006614 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006616 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006617 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006618 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006619 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006620 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6621 PointeeTy = PTy->getPointeeType();
6622 buildObjCPtr = true;
6623 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006624 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006625 }
6626
Sebastian Redl4990a632009-11-18 20:39:26 +00006627 // Don't add qualified variants of arrays. For one, they're not allowed
6628 // (the qualifier would sink to the element type), and for another, the
6629 // only overload situation where it matters is subscript or pointer +- int,
6630 // and those shouldn't have qualifier variants anyway.
6631 if (PointeeTy->isArrayType())
6632 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006633
John McCall8ccfcb52009-09-24 19:53:00 +00006634 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006635 bool hasVolatile = VisibleQuals.hasVolatile();
6636 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006637
John McCall8ccfcb52009-09-24 19:53:00 +00006638 // Iterate through all strict supersets of BaseCVR.
6639 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6640 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006641 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006642 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006643
6644 // Skip over restrict if no restrict found anywhere in the types, or if
6645 // the type cannot be restrict-qualified.
6646 if ((CVR & Qualifiers::Restrict) &&
6647 (!hasRestrict ||
6648 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6649 continue;
6650
6651 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006652 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006653
6654 // Build qualified pointer type.
6655 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006656 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006657 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006658 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006659 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6660
6661 // Insert qualified pointer type.
6662 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006663 }
6664
6665 return true;
6666}
6667
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006668/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6669/// to the set of pointer types along with any more-qualified variants of
6670/// that type. For example, if @p Ty is "int const *", this routine
6671/// will add "int const *", "int const volatile *", "int const
6672/// restrict *", and "int const volatile restrict *" to the set of
6673/// pointer types. Returns true if the add of @p Ty itself succeeded,
6674/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006675///
6676/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006677bool
6678BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6679 QualType Ty) {
6680 // Insert this type.
6681 if (!MemberPointerTypes.insert(Ty))
6682 return false;
6683
John McCall8ccfcb52009-09-24 19:53:00 +00006684 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6685 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006686
John McCall8ccfcb52009-09-24 19:53:00 +00006687 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006688 // Don't add qualified variants of arrays. For one, they're not allowed
6689 // (the qualifier would sink to the element type), and for another, the
6690 // only overload situation where it matters is subscript or pointer +- int,
6691 // and those shouldn't have qualifier variants anyway.
6692 if (PointeeTy->isArrayType())
6693 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006694 const Type *ClassTy = PointerTy->getClass();
6695
6696 // Iterate through all strict supersets of the pointee type's CVR
6697 // qualifiers.
6698 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6699 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6700 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
John McCall8ccfcb52009-09-24 19:53:00 +00006702 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006703 MemberPointerTypes.insert(
6704 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006705 }
6706
6707 return true;
6708}
6709
Douglas Gregora11693b2008-11-12 17:17:38 +00006710/// AddTypesConvertedFrom - Add each of the types to which the type @p
6711/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006712/// primarily interested in pointer types and enumeration types. We also
6713/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006714/// AllowUserConversions is true if we should look at the conversion
6715/// functions of a class type, and AllowExplicitConversions if we
6716/// should also include the explicit conversion functions of a class
6717/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006718void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006719BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006720 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006721 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006722 bool AllowExplicitConversions,
6723 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006724 // Only deal with canonical types.
6725 Ty = Context.getCanonicalType(Ty);
6726
6727 // Look through reference types; they aren't part of the type of an
6728 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006729 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006730 Ty = RefTy->getPointeeType();
6731
John McCall33ddac02011-01-19 10:06:00 +00006732 // If we're dealing with an array type, decay to the pointer.
6733 if (Ty->isArrayType())
6734 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6735
6736 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006737 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006738
Chandler Carruth00a38332010-12-13 01:44:01 +00006739 // Flag if we ever add a non-record type.
6740 const RecordType *TyRec = Ty->getAs<RecordType>();
6741 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6742
Chandler Carruth00a38332010-12-13 01:44:01 +00006743 // Flag if we encounter an arithmetic type.
6744 HasArithmeticOrEnumeralTypes =
6745 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6746
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006747 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6748 PointerTypes.insert(Ty);
6749 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006750 // Insert our type, and its more-qualified variants, into the set
6751 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006752 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006753 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006754 } else if (Ty->isMemberPointerType()) {
6755 // Member pointers are far easier, since the pointee can't be converted.
6756 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6757 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006758 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006759 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006760 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006761 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006762 // We treat vector types as arithmetic types in many contexts as an
6763 // extension.
6764 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006765 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006766 } else if (Ty->isNullPtrType()) {
6767 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006768 } else if (AllowUserConversions && TyRec) {
6769 // No conversion functions in incomplete types.
6770 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6771 return;
Mike Stump11289f42009-09-09 15:08:12 +00006772
Chandler Carruth00a38332010-12-13 01:44:01 +00006773 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006774 std::pair<CXXRecordDecl::conversion_iterator,
6775 CXXRecordDecl::conversion_iterator>
6776 Conversions = ClassDecl->getVisibleConversionFunctions();
6777 for (CXXRecordDecl::conversion_iterator
6778 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006779 NamedDecl *D = I.getDecl();
6780 if (isa<UsingShadowDecl>(D))
6781 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006782
Chandler Carruth00a38332010-12-13 01:44:01 +00006783 // Skip conversion function templates; they don't tell us anything
6784 // about which builtin types we can convert to.
6785 if (isa<FunctionTemplateDecl>(D))
6786 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006787
Chandler Carruth00a38332010-12-13 01:44:01 +00006788 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6789 if (AllowExplicitConversions || !Conv->isExplicit()) {
6790 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6791 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006792 }
6793 }
6794 }
6795}
6796
Douglas Gregor84605ae2009-08-24 13:43:27 +00006797/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6798/// the volatile- and non-volatile-qualified assignment operators for the
6799/// given type to the candidate set.
6800static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6801 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006802 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006803 OverloadCandidateSet &CandidateSet) {
6804 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006805
Douglas Gregor84605ae2009-08-24 13:43:27 +00006806 // T& operator=(T&, T)
6807 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6808 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006810 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006811
Douglas Gregor84605ae2009-08-24 13:43:27 +00006812 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6813 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006814 ParamTypes[0]
6815 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006816 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006818 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006819 }
6820}
Mike Stump11289f42009-09-09 15:08:12 +00006821
Sebastian Redl1054fae2009-10-25 17:03:50 +00006822/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6823/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006824static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6825 Qualifiers VRQuals;
6826 const RecordType *TyRec;
6827 if (const MemberPointerType *RHSMPType =
6828 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006829 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006830 else
6831 TyRec = ArgExpr->getType()->getAs<RecordType>();
6832 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006833 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006834 VRQuals.addVolatile();
6835 VRQuals.addRestrict();
6836 return VRQuals;
6837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006838
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006839 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006840 if (!ClassDecl->hasDefinition())
6841 return VRQuals;
6842
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006843 std::pair<CXXRecordDecl::conversion_iterator,
6844 CXXRecordDecl::conversion_iterator>
6845 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006847 for (CXXRecordDecl::conversion_iterator
6848 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006849 NamedDecl *D = I.getDecl();
6850 if (isa<UsingShadowDecl>(D))
6851 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6852 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006853 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6854 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6855 CanTy = ResTypeRef->getPointeeType();
6856 // Need to go down the pointer/mempointer chain and add qualifiers
6857 // as see them.
6858 bool done = false;
6859 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006860 if (CanTy.isRestrictQualified())
6861 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006862 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6863 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006865 CanTy->getAs<MemberPointerType>())
6866 CanTy = ResTypeMPtr->getPointeeType();
6867 else
6868 done = true;
6869 if (CanTy.isVolatileQualified())
6870 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006871 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6872 return VRQuals;
6873 }
6874 }
6875 }
6876 return VRQuals;
6877}
John McCall52872982010-11-13 05:51:15 +00006878
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006879namespace {
John McCall52872982010-11-13 05:51:15 +00006880
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006881/// \brief Helper class to manage the addition of builtin operator overload
6882/// candidates. It provides shared state and utility methods used throughout
6883/// the process, as well as a helper method to add each group of builtin
6884/// operator overloads from the standard to a candidate set.
6885class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006886 // Common instance state available to all overload candidate addition methods.
6887 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006888 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006889 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006890 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006891 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006892 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006893
Chandler Carruthc6586e52010-12-12 10:35:00 +00006894 // Define some constants used to index and iterate over the arithemetic types
6895 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006896 // The "promoted arithmetic types" are the arithmetic
6897 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006898 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006899 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006900 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006901 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006902 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006903 LastPromotedArithmeticType = 11;
6904 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006905
Chandler Carruthc6586e52010-12-12 10:35:00 +00006906 /// \brief Get the canonical type for a given arithmetic type index.
6907 CanQualType getArithmeticType(unsigned index) {
6908 assert(index < NumArithmeticTypes);
6909 static CanQualType ASTContext::* const
6910 ArithmeticTypes[NumArithmeticTypes] = {
6911 // Start of promoted types.
6912 &ASTContext::FloatTy,
6913 &ASTContext::DoubleTy,
6914 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006915
Chandler Carruthc6586e52010-12-12 10:35:00 +00006916 // Start of integral types.
6917 &ASTContext::IntTy,
6918 &ASTContext::LongTy,
6919 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006920 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006921 &ASTContext::UnsignedIntTy,
6922 &ASTContext::UnsignedLongTy,
6923 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006924 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006925 // End of promoted types.
6926
6927 &ASTContext::BoolTy,
6928 &ASTContext::CharTy,
6929 &ASTContext::WCharTy,
6930 &ASTContext::Char16Ty,
6931 &ASTContext::Char32Ty,
6932 &ASTContext::SignedCharTy,
6933 &ASTContext::ShortTy,
6934 &ASTContext::UnsignedCharTy,
6935 &ASTContext::UnsignedShortTy,
6936 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006937 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006938 };
6939 return S.Context.*ArithmeticTypes[index];
6940 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006941
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006942 /// \brief Gets the canonical type resulting from the usual arithemetic
6943 /// converions for the given arithmetic types.
6944 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6945 // Accelerator table for performing the usual arithmetic conversions.
6946 // The rules are basically:
6947 // - if either is floating-point, use the wider floating-point
6948 // - if same signedness, use the higher rank
6949 // - if same size, use unsigned of the higher rank
6950 // - use the larger type
6951 // These rules, together with the axiom that higher ranks are
6952 // never smaller, are sufficient to precompute all of these results
6953 // *except* when dealing with signed types of higher rank.
6954 // (we could precompute SLL x UI for all known platforms, but it's
6955 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006956 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006957 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006958 Dep=-1,
6959 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006960 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006961 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006962 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006963/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6964/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6965/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6966/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6967/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6968/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6969/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6970/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6971/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6972/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6973/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006974 };
6975
6976 assert(L < LastPromotedArithmeticType);
6977 assert(R < LastPromotedArithmeticType);
6978 int Idx = ConversionsTable[L][R];
6979
6980 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006981 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006982
6983 // Slow path: we need to compare widths.
6984 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006985 CanQualType LT = getArithmeticType(L),
6986 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006987 unsigned LW = S.Context.getIntWidth(LT),
6988 RW = S.Context.getIntWidth(RT);
6989
6990 // If they're different widths, use the signed type.
6991 if (LW > RW) return LT;
6992 else if (LW < RW) return RT;
6993
6994 // Otherwise, use the unsigned type of the signed type's rank.
6995 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6996 assert(L == SLL || R == SLL);
6997 return S.Context.UnsignedLongLongTy;
6998 }
6999
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007000 /// \brief Helper method to factor out the common pattern of adding overloads
7001 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007002 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007003 bool HasVolatile,
7004 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007005 QualType ParamTypes[2] = {
7006 S.Context.getLValueReferenceType(CandidateTy),
7007 S.Context.IntTy
7008 };
7009
7010 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007011 if (Args.size() == 1)
7012 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007013 else
Richard Smithe54c3072013-05-05 15:51:06 +00007014 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007015
7016 // Use a heuristic to reduce number of builtin candidates in the set:
7017 // add volatile version only if there are conversions to a volatile type.
7018 if (HasVolatile) {
7019 ParamTypes[0] =
7020 S.Context.getLValueReferenceType(
7021 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007022 if (Args.size() == 1)
7023 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007024 else
Richard Smithe54c3072013-05-05 15:51:06 +00007025 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007026 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007027
7028 // Add restrict version only if there are conversions to a restrict type
7029 // and our candidate type is a non-restrict-qualified pointer.
7030 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7031 !CandidateTy.isRestrictQualified()) {
7032 ParamTypes[0]
7033 = S.Context.getLValueReferenceType(
7034 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007035 if (Args.size() == 1)
7036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007037 else
Richard Smithe54c3072013-05-05 15:51:06 +00007038 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007039
7040 if (HasVolatile) {
7041 ParamTypes[0]
7042 = S.Context.getLValueReferenceType(
7043 S.Context.getCVRQualifiedType(CandidateTy,
7044 (Qualifiers::Volatile |
7045 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007046 if (Args.size() == 1)
7047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007048 else
Richard Smithe54c3072013-05-05 15:51:06 +00007049 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007050 }
7051 }
7052
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007053 }
7054
7055public:
7056 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007057 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007058 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007059 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007060 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007061 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007062 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007063 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007064 HasArithmeticOrEnumeralCandidateType(
7065 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007066 CandidateTypes(CandidateTypes),
7067 CandidateSet(CandidateSet) {
7068 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007069 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007070 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007071 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007072 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007073 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007074 assert(getArithmeticType(FirstPromotedArithmeticType)
7075 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007076 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007077 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007078 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007079 "Invalid last promoted arithmetic type");
7080 }
7081
7082 // C++ [over.built]p3:
7083 //
7084 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7085 // is either volatile or empty, there exist candidate operator
7086 // functions of the form
7087 //
7088 // VQ T& operator++(VQ T&);
7089 // T operator++(VQ T&, int);
7090 //
7091 // C++ [over.built]p4:
7092 //
7093 // For every pair (T, VQ), where T is an arithmetic type other
7094 // than bool, and VQ is either volatile or empty, there exist
7095 // candidate operator functions of the form
7096 //
7097 // VQ T& operator--(VQ T&);
7098 // T operator--(VQ T&, int);
7099 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007100 if (!HasArithmeticOrEnumeralCandidateType)
7101 return;
7102
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007103 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7104 Arith < NumArithmeticTypes; ++Arith) {
7105 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007106 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007107 VisibleTypeConversionsQuals.hasVolatile(),
7108 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007109 }
7110 }
7111
7112 // C++ [over.built]p5:
7113 //
7114 // For every pair (T, VQ), where T is a cv-qualified or
7115 // cv-unqualified object type, and VQ is either volatile or
7116 // empty, there exist candidate operator functions of the form
7117 //
7118 // T*VQ& operator++(T*VQ&);
7119 // T*VQ& operator--(T*VQ&);
7120 // T* operator++(T*VQ&, int);
7121 // T* operator--(T*VQ&, int);
7122 void addPlusPlusMinusMinusPointerOverloads() {
7123 for (BuiltinCandidateTypeSet::iterator
7124 Ptr = CandidateTypes[0].pointer_begin(),
7125 PtrEnd = CandidateTypes[0].pointer_end();
7126 Ptr != PtrEnd; ++Ptr) {
7127 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007128 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007129 continue;
7130
7131 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007132 (!(*Ptr).isVolatileQualified() &&
7133 VisibleTypeConversionsQuals.hasVolatile()),
7134 (!(*Ptr).isRestrictQualified() &&
7135 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007136 }
7137 }
7138
7139 // C++ [over.built]p6:
7140 // For every cv-qualified or cv-unqualified object type T, there
7141 // exist candidate operator functions of the form
7142 //
7143 // T& operator*(T*);
7144 //
7145 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007147 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007148 // T& operator*(T*);
7149 void addUnaryStarPointerOverloads() {
7150 for (BuiltinCandidateTypeSet::iterator
7151 Ptr = CandidateTypes[0].pointer_begin(),
7152 PtrEnd = CandidateTypes[0].pointer_end();
7153 Ptr != PtrEnd; ++Ptr) {
7154 QualType ParamTy = *Ptr;
7155 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007156 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7157 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158
Douglas Gregor02824322011-01-26 19:30:28 +00007159 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7160 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7161 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007162
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007163 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007164 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007165 }
7166 }
7167
7168 // C++ [over.built]p9:
7169 // For every promoted arithmetic type T, there exist candidate
7170 // operator functions of the form
7171 //
7172 // T operator+(T);
7173 // T operator-(T);
7174 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007175 if (!HasArithmeticOrEnumeralCandidateType)
7176 return;
7177
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178 for (unsigned Arith = FirstPromotedArithmeticType;
7179 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007180 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007181 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007182 }
7183
7184 // Extension: We also add these operators for vector types.
7185 for (BuiltinCandidateTypeSet::iterator
7186 Vec = CandidateTypes[0].vector_begin(),
7187 VecEnd = CandidateTypes[0].vector_end();
7188 Vec != VecEnd; ++Vec) {
7189 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007190 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007191 }
7192 }
7193
7194 // C++ [over.built]p8:
7195 // For every type T, there exist candidate operator functions of
7196 // the form
7197 //
7198 // T* operator+(T*);
7199 void addUnaryPlusPointerOverloads() {
7200 for (BuiltinCandidateTypeSet::iterator
7201 Ptr = CandidateTypes[0].pointer_begin(),
7202 PtrEnd = CandidateTypes[0].pointer_end();
7203 Ptr != PtrEnd; ++Ptr) {
7204 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007205 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007206 }
7207 }
7208
7209 // C++ [over.built]p10:
7210 // For every promoted integral type T, there exist candidate
7211 // operator functions of the form
7212 //
7213 // T operator~(T);
7214 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007215 if (!HasArithmeticOrEnumeralCandidateType)
7216 return;
7217
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007218 for (unsigned Int = FirstPromotedIntegralType;
7219 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007220 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007221 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007222 }
7223
7224 // Extension: We also add this operator for vector types.
7225 for (BuiltinCandidateTypeSet::iterator
7226 Vec = CandidateTypes[0].vector_begin(),
7227 VecEnd = CandidateTypes[0].vector_end();
7228 Vec != VecEnd; ++Vec) {
7229 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007230 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007231 }
7232 }
7233
7234 // C++ [over.match.oper]p16:
7235 // For every pointer to member type T, there exist candidate operator
7236 // functions of the form
7237 //
7238 // bool operator==(T,T);
7239 // bool operator!=(T,T);
7240 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7241 /// Set of (canonical) types that we've already handled.
7242 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7243
Richard Smithe54c3072013-05-05 15:51:06 +00007244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007245 for (BuiltinCandidateTypeSet::iterator
7246 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248 MemPtr != MemPtrEnd;
7249 ++MemPtr) {
7250 // Don't add the same builtin candidate twice.
7251 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7252 continue;
7253
7254 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007255 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007256 }
7257 }
7258 }
7259
7260 // C++ [over.built]p15:
7261 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007262 // For every T, where T is an enumeration type, a pointer type, or
7263 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007264 //
7265 // bool operator<(T, T);
7266 // bool operator>(T, T);
7267 // bool operator<=(T, T);
7268 // bool operator>=(T, T);
7269 // bool operator==(T, T);
7270 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007271 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007272 // C++ [over.match.oper]p3:
7273 // [...]the built-in candidates include all of the candidate operator
7274 // functions defined in 13.6 that, compared to the given operator, [...]
7275 // do not have the same parameter-type-list as any non-template non-member
7276 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007277 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007278 // Note that in practice, this only affects enumeration types because there
7279 // aren't any built-in candidates of record type, and a user-defined operator
7280 // must have an operand of record or enumeration type. Also, the only other
7281 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007282 // cannot be overloaded for enumeration types, so this is the only place
7283 // where we must suppress candidates like this.
7284 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7285 UserDefinedBinaryOperators;
7286
Richard Smithe54c3072013-05-05 15:51:06 +00007287 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007288 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7289 CandidateTypes[ArgIdx].enumeration_end()) {
7290 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7291 CEnd = CandidateSet.end();
7292 C != CEnd; ++C) {
7293 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7294 continue;
7295
Eli Friedman14f082b2012-09-18 21:52:24 +00007296 if (C->Function->isFunctionTemplateSpecialization())
7297 continue;
7298
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007299 QualType FirstParamType =
7300 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7301 QualType SecondParamType =
7302 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7303
7304 // Skip if either parameter isn't of enumeral type.
7305 if (!FirstParamType->isEnumeralType() ||
7306 !SecondParamType->isEnumeralType())
7307 continue;
7308
7309 // Add this operator to the set of known user-defined operators.
7310 UserDefinedBinaryOperators.insert(
7311 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7312 S.Context.getCanonicalType(SecondParamType)));
7313 }
7314 }
7315 }
7316
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007317 /// Set of (canonical) types that we've already handled.
7318 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7319
Richard Smithe54c3072013-05-05 15:51:06 +00007320 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007321 for (BuiltinCandidateTypeSet::iterator
7322 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7323 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7324 Ptr != PtrEnd; ++Ptr) {
7325 // Don't add the same builtin candidate twice.
7326 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7327 continue;
7328
7329 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007330 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 }
7332 for (BuiltinCandidateTypeSet::iterator
7333 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7334 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7335 Enum != EnumEnd; ++Enum) {
7336 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7337
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007338 // Don't add the same builtin candidate twice, or if a user defined
7339 // candidate exists.
7340 if (!AddedTypes.insert(CanonType) ||
7341 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7342 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007343 continue;
7344
7345 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007346 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007347 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007348
7349 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7350 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7351 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007352 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007353 NullPtrTy))) {
7354 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007355 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007356 CandidateSet);
7357 }
7358 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007359 }
7360 }
7361
7362 // C++ [over.built]p13:
7363 //
7364 // For every cv-qualified or cv-unqualified object type T
7365 // there exist candidate operator functions of the form
7366 //
7367 // T* operator+(T*, ptrdiff_t);
7368 // T& operator[](T*, ptrdiff_t); [BELOW]
7369 // T* operator-(T*, ptrdiff_t);
7370 // T* operator+(ptrdiff_t, T*);
7371 // T& operator[](ptrdiff_t, T*); [BELOW]
7372 //
7373 // C++ [over.built]p14:
7374 //
7375 // For every T, where T is a pointer to object type, there
7376 // exist candidate operator functions of the form
7377 //
7378 // ptrdiff_t operator-(T, T);
7379 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7380 /// Set of (canonical) types that we've already handled.
7381 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7382
7383 for (int Arg = 0; Arg < 2; ++Arg) {
7384 QualType AsymetricParamTypes[2] = {
7385 S.Context.getPointerDiffType(),
7386 S.Context.getPointerDiffType(),
7387 };
7388 for (BuiltinCandidateTypeSet::iterator
7389 Ptr = CandidateTypes[Arg].pointer_begin(),
7390 PtrEnd = CandidateTypes[Arg].pointer_end();
7391 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007392 QualType PointeeTy = (*Ptr)->getPointeeType();
7393 if (!PointeeTy->isObjectType())
7394 continue;
7395
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007396 AsymetricParamTypes[Arg] = *Ptr;
7397 if (Arg == 0 || Op == OO_Plus) {
7398 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7399 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007400 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 }
7402 if (Op == OO_Minus) {
7403 // ptrdiff_t operator-(T, T);
7404 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7405 continue;
7406
7407 QualType ParamTypes[2] = { *Ptr, *Ptr };
7408 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007409 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007410 }
7411 }
7412 }
7413 }
7414
7415 // C++ [over.built]p12:
7416 //
7417 // For every pair of promoted arithmetic types L and R, there
7418 // exist candidate operator functions of the form
7419 //
7420 // LR operator*(L, R);
7421 // LR operator/(L, R);
7422 // LR operator+(L, R);
7423 // LR operator-(L, R);
7424 // bool operator<(L, R);
7425 // bool operator>(L, R);
7426 // bool operator<=(L, R);
7427 // bool operator>=(L, R);
7428 // bool operator==(L, R);
7429 // bool operator!=(L, R);
7430 //
7431 // where LR is the result of the usual arithmetic conversions
7432 // between types L and R.
7433 //
7434 // C++ [over.built]p24:
7435 //
7436 // For every pair of promoted arithmetic types L and R, there exist
7437 // candidate operator functions of the form
7438 //
7439 // LR operator?(bool, L, R);
7440 //
7441 // where LR is the result of the usual arithmetic conversions
7442 // between types L and R.
7443 // Our candidates ignore the first parameter.
7444 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007445 if (!HasArithmeticOrEnumeralCandidateType)
7446 return;
7447
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007448 for (unsigned Left = FirstPromotedArithmeticType;
7449 Left < LastPromotedArithmeticType; ++Left) {
7450 for (unsigned Right = FirstPromotedArithmeticType;
7451 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007452 QualType LandR[2] = { getArithmeticType(Left),
7453 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007454 QualType Result =
7455 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007456 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007457 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007458 }
7459 }
7460
7461 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7462 // conditional operator for vector types.
7463 for (BuiltinCandidateTypeSet::iterator
7464 Vec1 = CandidateTypes[0].vector_begin(),
7465 Vec1End = CandidateTypes[0].vector_end();
7466 Vec1 != Vec1End; ++Vec1) {
7467 for (BuiltinCandidateTypeSet::iterator
7468 Vec2 = CandidateTypes[1].vector_begin(),
7469 Vec2End = CandidateTypes[1].vector_end();
7470 Vec2 != Vec2End; ++Vec2) {
7471 QualType LandR[2] = { *Vec1, *Vec2 };
7472 QualType Result = S.Context.BoolTy;
7473 if (!isComparison) {
7474 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7475 Result = *Vec1;
7476 else
7477 Result = *Vec2;
7478 }
7479
Richard Smithe54c3072013-05-05 15:51:06 +00007480 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007481 }
7482 }
7483 }
7484
7485 // C++ [over.built]p17:
7486 //
7487 // For every pair of promoted integral types L and R, there
7488 // exist candidate operator functions of the form
7489 //
7490 // LR operator%(L, R);
7491 // LR operator&(L, R);
7492 // LR operator^(L, R);
7493 // LR operator|(L, R);
7494 // L operator<<(L, R);
7495 // L operator>>(L, R);
7496 //
7497 // where LR is the result of the usual arithmetic conversions
7498 // between types L and R.
7499 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007500 if (!HasArithmeticOrEnumeralCandidateType)
7501 return;
7502
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007503 for (unsigned Left = FirstPromotedIntegralType;
7504 Left < LastPromotedIntegralType; ++Left) {
7505 for (unsigned Right = FirstPromotedIntegralType;
7506 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007507 QualType LandR[2] = { getArithmeticType(Left),
7508 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007509 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7510 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007511 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007512 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007513 }
7514 }
7515 }
7516
7517 // C++ [over.built]p20:
7518 //
7519 // For every pair (T, VQ), where T is an enumeration or
7520 // pointer to member type and VQ is either volatile or
7521 // empty, there exist candidate operator functions of the form
7522 //
7523 // VQ T& operator=(VQ T&, T);
7524 void addAssignmentMemberPointerOrEnumeralOverloads() {
7525 /// Set of (canonical) types that we've already handled.
7526 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7527
7528 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7529 for (BuiltinCandidateTypeSet::iterator
7530 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7531 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7532 Enum != EnumEnd; ++Enum) {
7533 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7534 continue;
7535
Richard Smithe54c3072013-05-05 15:51:06 +00007536 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 }
7538
7539 for (BuiltinCandidateTypeSet::iterator
7540 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7541 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7542 MemPtr != MemPtrEnd; ++MemPtr) {
7543 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7544 continue;
7545
Richard Smithe54c3072013-05-05 15:51:06 +00007546 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007547 }
7548 }
7549 }
7550
7551 // C++ [over.built]p19:
7552 //
7553 // For every pair (T, VQ), where T is any type and VQ is either
7554 // volatile or empty, there exist candidate operator functions
7555 // of the form
7556 //
7557 // T*VQ& operator=(T*VQ&, T*);
7558 //
7559 // C++ [over.built]p21:
7560 //
7561 // For every pair (T, VQ), where T is a cv-qualified or
7562 // cv-unqualified object type and VQ is either volatile or
7563 // empty, there exist candidate operator functions of the form
7564 //
7565 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7566 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7567 void addAssignmentPointerOverloads(bool isEqualOp) {
7568 /// Set of (canonical) types that we've already handled.
7569 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7570
7571 for (BuiltinCandidateTypeSet::iterator
7572 Ptr = CandidateTypes[0].pointer_begin(),
7573 PtrEnd = CandidateTypes[0].pointer_end();
7574 Ptr != PtrEnd; ++Ptr) {
7575 // If this is operator=, keep track of the builtin candidates we added.
7576 if (isEqualOp)
7577 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007578 else if (!(*Ptr)->getPointeeType()->isObjectType())
7579 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580
7581 // non-volatile version
7582 QualType ParamTypes[2] = {
7583 S.Context.getLValueReferenceType(*Ptr),
7584 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7585 };
Richard Smithe54c3072013-05-05 15:51:06 +00007586 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007587 /*IsAssigmentOperator=*/ isEqualOp);
7588
Douglas Gregor5bee2582012-06-04 00:15:09 +00007589 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7590 VisibleTypeConversionsQuals.hasVolatile();
7591 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 // volatile version
7593 ParamTypes[0] =
7594 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007595 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007596 /*IsAssigmentOperator=*/isEqualOp);
7597 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007598
7599 if (!(*Ptr).isRestrictQualified() &&
7600 VisibleTypeConversionsQuals.hasRestrict()) {
7601 // restrict version
7602 ParamTypes[0]
7603 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007604 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007605 /*IsAssigmentOperator=*/isEqualOp);
7606
7607 if (NeedVolatile) {
7608 // volatile restrict version
7609 ParamTypes[0]
7610 = S.Context.getLValueReferenceType(
7611 S.Context.getCVRQualifiedType(*Ptr,
7612 (Qualifiers::Volatile |
7613 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007614 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007615 /*IsAssigmentOperator=*/isEqualOp);
7616 }
7617 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007618 }
7619
7620 if (isEqualOp) {
7621 for (BuiltinCandidateTypeSet::iterator
7622 Ptr = CandidateTypes[1].pointer_begin(),
7623 PtrEnd = CandidateTypes[1].pointer_end();
7624 Ptr != PtrEnd; ++Ptr) {
7625 // Make sure we don't add the same candidate twice.
7626 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7627 continue;
7628
Chandler Carruth8e543b32010-12-12 08:17:55 +00007629 QualType ParamTypes[2] = {
7630 S.Context.getLValueReferenceType(*Ptr),
7631 *Ptr,
7632 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007633
7634 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007635 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007636 /*IsAssigmentOperator=*/true);
7637
Douglas Gregor5bee2582012-06-04 00:15:09 +00007638 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7639 VisibleTypeConversionsQuals.hasVolatile();
7640 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007641 // volatile version
7642 ParamTypes[0] =
7643 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7645 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007647
7648 if (!(*Ptr).isRestrictQualified() &&
7649 VisibleTypeConversionsQuals.hasRestrict()) {
7650 // restrict version
7651 ParamTypes[0]
7652 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007653 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7654 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007655
7656 if (NeedVolatile) {
7657 // volatile restrict version
7658 ParamTypes[0]
7659 = S.Context.getLValueReferenceType(
7660 S.Context.getCVRQualifiedType(*Ptr,
7661 (Qualifiers::Volatile |
7662 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007663 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7664 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007665 }
7666 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 }
7668 }
7669 }
7670
7671 // C++ [over.built]p18:
7672 //
7673 // For every triple (L, VQ, R), where L is an arithmetic type,
7674 // VQ is either volatile or empty, and R is a promoted
7675 // arithmetic type, there exist candidate operator functions of
7676 // the form
7677 //
7678 // VQ L& operator=(VQ L&, R);
7679 // VQ L& operator*=(VQ L&, R);
7680 // VQ L& operator/=(VQ L&, R);
7681 // VQ L& operator+=(VQ L&, R);
7682 // VQ L& operator-=(VQ L&, R);
7683 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007684 if (!HasArithmeticOrEnumeralCandidateType)
7685 return;
7686
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7688 for (unsigned Right = FirstPromotedArithmeticType;
7689 Right < LastPromotedArithmeticType; ++Right) {
7690 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007691 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007692
7693 // Add this built-in operator as a candidate (VQ is empty).
7694 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007695 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007696 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007697 /*IsAssigmentOperator=*/isEqualOp);
7698
7699 // Add this built-in operator as a candidate (VQ is 'volatile').
7700 if (VisibleTypeConversionsQuals.hasVolatile()) {
7701 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007702 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007703 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007704 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 /*IsAssigmentOperator=*/isEqualOp);
7706 }
7707 }
7708 }
7709
7710 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7711 for (BuiltinCandidateTypeSet::iterator
7712 Vec1 = CandidateTypes[0].vector_begin(),
7713 Vec1End = CandidateTypes[0].vector_end();
7714 Vec1 != Vec1End; ++Vec1) {
7715 for (BuiltinCandidateTypeSet::iterator
7716 Vec2 = CandidateTypes[1].vector_begin(),
7717 Vec2End = CandidateTypes[1].vector_end();
7718 Vec2 != Vec2End; ++Vec2) {
7719 QualType ParamTypes[2];
7720 ParamTypes[1] = *Vec2;
7721 // Add this built-in operator as a candidate (VQ is empty).
7722 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007723 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007724 /*IsAssigmentOperator=*/isEqualOp);
7725
7726 // Add this built-in operator as a candidate (VQ is 'volatile').
7727 if (VisibleTypeConversionsQuals.hasVolatile()) {
7728 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7729 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007730 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731 /*IsAssigmentOperator=*/isEqualOp);
7732 }
7733 }
7734 }
7735 }
7736
7737 // C++ [over.built]p22:
7738 //
7739 // For every triple (L, VQ, R), where L is an integral type, VQ
7740 // is either volatile or empty, and R is a promoted integral
7741 // type, there exist candidate operator functions of the form
7742 //
7743 // VQ L& operator%=(VQ L&, R);
7744 // VQ L& operator<<=(VQ L&, R);
7745 // VQ L& operator>>=(VQ L&, R);
7746 // VQ L& operator&=(VQ L&, R);
7747 // VQ L& operator^=(VQ L&, R);
7748 // VQ L& operator|=(VQ L&, R);
7749 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007750 if (!HasArithmeticOrEnumeralCandidateType)
7751 return;
7752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7754 for (unsigned Right = FirstPromotedIntegralType;
7755 Right < LastPromotedIntegralType; ++Right) {
7756 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007757 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758
7759 // Add this built-in operator as a candidate (VQ is empty).
7760 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007761 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007762 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007763 if (VisibleTypeConversionsQuals.hasVolatile()) {
7764 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007765 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7767 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007768 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 }
7770 }
7771 }
7772 }
7773
7774 // C++ [over.operator]p23:
7775 //
7776 // There also exist candidate operator functions of the form
7777 //
7778 // bool operator!(bool);
7779 // bool operator&&(bool, bool);
7780 // bool operator||(bool, bool);
7781 void addExclaimOverload() {
7782 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007783 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007784 /*IsAssignmentOperator=*/false,
7785 /*NumContextualBoolArguments=*/1);
7786 }
7787 void addAmpAmpOrPipePipeOverload() {
7788 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007789 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 /*IsAssignmentOperator=*/false,
7791 /*NumContextualBoolArguments=*/2);
7792 }
7793
7794 // C++ [over.built]p13:
7795 //
7796 // For every cv-qualified or cv-unqualified object type T there
7797 // exist candidate operator functions of the form
7798 //
7799 // T* operator+(T*, ptrdiff_t); [ABOVE]
7800 // T& operator[](T*, ptrdiff_t);
7801 // T* operator-(T*, ptrdiff_t); [ABOVE]
7802 // T* operator+(ptrdiff_t, T*); [ABOVE]
7803 // T& operator[](ptrdiff_t, T*);
7804 void addSubscriptOverloads() {
7805 for (BuiltinCandidateTypeSet::iterator
7806 Ptr = CandidateTypes[0].pointer_begin(),
7807 PtrEnd = CandidateTypes[0].pointer_end();
7808 Ptr != PtrEnd; ++Ptr) {
7809 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7810 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007811 if (!PointeeType->isObjectType())
7812 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007814 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7815
7816 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007817 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007818 }
7819
7820 for (BuiltinCandidateTypeSet::iterator
7821 Ptr = CandidateTypes[1].pointer_begin(),
7822 PtrEnd = CandidateTypes[1].pointer_end();
7823 Ptr != PtrEnd; ++Ptr) {
7824 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7825 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007826 if (!PointeeType->isObjectType())
7827 continue;
7828
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7830
7831 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007832 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833 }
7834 }
7835
7836 // C++ [over.built]p11:
7837 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7838 // C1 is the same type as C2 or is a derived class of C2, T is an object
7839 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7840 // there exist candidate operator functions of the form
7841 //
7842 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7843 //
7844 // where CV12 is the union of CV1 and CV2.
7845 void addArrowStarOverloads() {
7846 for (BuiltinCandidateTypeSet::iterator
7847 Ptr = CandidateTypes[0].pointer_begin(),
7848 PtrEnd = CandidateTypes[0].pointer_end();
7849 Ptr != PtrEnd; ++Ptr) {
7850 QualType C1Ty = (*Ptr);
7851 QualType C1;
7852 QualifierCollector Q1;
7853 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7854 if (!isa<RecordType>(C1))
7855 continue;
7856 // heuristic to reduce number of builtin candidates in the set.
7857 // Add volatile/restrict version only if there are conversions to a
7858 // volatile/restrict type.
7859 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7860 continue;
7861 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7862 continue;
7863 for (BuiltinCandidateTypeSet::iterator
7864 MemPtr = CandidateTypes[1].member_pointer_begin(),
7865 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7866 MemPtr != MemPtrEnd; ++MemPtr) {
7867 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7868 QualType C2 = QualType(mptr->getClass(), 0);
7869 C2 = C2.getUnqualifiedType();
7870 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7871 break;
7872 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7873 // build CV12 T&
7874 QualType T = mptr->getPointeeType();
7875 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7876 T.isVolatileQualified())
7877 continue;
7878 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7879 T.isRestrictQualified())
7880 continue;
7881 T = Q1.apply(S.Context, T);
7882 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007883 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 }
7885 }
7886 }
7887
7888 // Note that we don't consider the first argument, since it has been
7889 // contextually converted to bool long ago. The candidates below are
7890 // therefore added as binary.
7891 //
7892 // C++ [over.built]p25:
7893 // For every type T, where T is a pointer, pointer-to-member, or scoped
7894 // enumeration type, there exist candidate operator functions of the form
7895 //
7896 // T operator?(bool, T, T);
7897 //
7898 void addConditionalOperatorOverloads() {
7899 /// Set of (canonical) types that we've already handled.
7900 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7901
7902 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7903 for (BuiltinCandidateTypeSet::iterator
7904 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7905 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7906 Ptr != PtrEnd; ++Ptr) {
7907 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7908 continue;
7909
7910 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007911 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 }
7913
7914 for (BuiltinCandidateTypeSet::iterator
7915 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7916 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7917 MemPtr != MemPtrEnd; ++MemPtr) {
7918 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7919 continue;
7920
7921 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007922 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007923 }
7924
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007925 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 for (BuiltinCandidateTypeSet::iterator
7927 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7928 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7929 Enum != EnumEnd; ++Enum) {
7930 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7931 continue;
7932
7933 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7934 continue;
7935
7936 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007937 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007938 }
7939 }
7940 }
7941 }
7942};
7943
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007944} // end anonymous namespace
7945
7946/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7947/// operator overloads to the candidate set (C++ [over.built]), based
7948/// on the operator @p Op and the arguments given. For example, if the
7949/// operator is a binary '+', this routine might add "int
7950/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007951void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7952 SourceLocation OpLoc,
7953 ArrayRef<Expr *> Args,
7954 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007955 // Find all of the types that the arguments can convert to, but only
7956 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007957 // that make use of these types. Also record whether we encounter non-record
7958 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007959 Qualifiers VisibleTypeConversionsQuals;
7960 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007961 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007962 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007963
7964 bool HasNonRecordCandidateType = false;
7965 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007966 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007967 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007968 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7969 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7970 OpLoc,
7971 true,
7972 (Op == OO_Exclaim ||
7973 Op == OO_AmpAmp ||
7974 Op == OO_PipePipe),
7975 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007976 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7977 CandidateTypes[ArgIdx].hasNonRecordTypes();
7978 HasArithmeticOrEnumeralCandidateType =
7979 HasArithmeticOrEnumeralCandidateType ||
7980 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007981 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007982
Chandler Carruth00a38332010-12-13 01:44:01 +00007983 // Exit early when no non-record types have been added to the candidate set
7984 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007985 //
7986 // We can't exit early for !, ||, or &&, since there we have always have
7987 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007988 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007989 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007990 return;
7991
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007993 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007994 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007995 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007996 CandidateTypes, CandidateSet);
7997
7998 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007999 switch (Op) {
8000 case OO_None:
8001 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008002 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008003
Chandler Carruth5184de02010-12-12 08:51:33 +00008004 case OO_New:
8005 case OO_Delete:
8006 case OO_Array_New:
8007 case OO_Array_Delete:
8008 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008009 llvm_unreachable(
8010 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008011
8012 case OO_Comma:
8013 case OO_Arrow:
8014 // C++ [over.match.oper]p3:
8015 // -- For the operator ',', the unary operator '&', or the
8016 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008017 break;
8018
8019 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008020 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008022 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008023
8024 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008025 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008027 } else {
8028 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8029 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8030 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008031 break;
8032
Chandler Carruth5184de02010-12-12 08:51:33 +00008033 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008034 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008035 OpBuilder.addUnaryStarPointerOverloads();
8036 else
8037 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8038 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008039
Chandler Carruth5184de02010-12-12 08:51:33 +00008040 case OO_Slash:
8041 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008042 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008043
8044 case OO_PlusPlus:
8045 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8047 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008048 break;
8049
Douglas Gregor84605ae2009-08-24 13:43:27 +00008050 case OO_EqualEqual:
8051 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008053 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008054
Douglas Gregora11693b2008-11-12 17:17:38 +00008055 case OO_Less:
8056 case OO_Greater:
8057 case OO_LessEqual:
8058 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008059 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008060 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8061 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008062
Douglas Gregora11693b2008-11-12 17:17:38 +00008063 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008064 case OO_Caret:
8065 case OO_Pipe:
8066 case OO_LessLess:
8067 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008068 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008069 break;
8070
Chandler Carruth5184de02010-12-12 08:51:33 +00008071 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008072 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008073 // C++ [over.match.oper]p3:
8074 // -- For the operator ',', the unary operator '&', or the
8075 // operator '->', the built-in candidates set is empty.
8076 break;
8077
8078 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8079 break;
8080
8081 case OO_Tilde:
8082 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8083 break;
8084
Douglas Gregora11693b2008-11-12 17:17:38 +00008085 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008087 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008088
8089 case OO_PlusEqual:
8090 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008091 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008092 // Fall through.
8093
8094 case OO_StarEqual:
8095 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008096 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008097 break;
8098
8099 case OO_PercentEqual:
8100 case OO_LessLessEqual:
8101 case OO_GreaterGreaterEqual:
8102 case OO_AmpEqual:
8103 case OO_CaretEqual:
8104 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008106 break;
8107
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008108 case OO_Exclaim:
8109 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008110 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008111
Douglas Gregora11693b2008-11-12 17:17:38 +00008112 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008113 case OO_PipePipe:
8114 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008115 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008116
8117 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008119 break;
8120
8121 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008122 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008123 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008124
8125 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008126 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008127 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8128 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008129 }
8130}
8131
Douglas Gregore254f902009-02-04 00:32:51 +00008132/// \brief Add function candidates found via argument-dependent lookup
8133/// to the set of overloading candidates.
8134///
8135/// This routine performs argument-dependent name lookup based on the
8136/// given function name (which may also be an operator name) and adds
8137/// all of the overload candidates found by ADL to the overload
8138/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008139void
Douglas Gregore254f902009-02-04 00:32:51 +00008140Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008141 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008142 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008143 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008144 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008145 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008146 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008147
John McCall91f61fc2010-01-26 06:04:06 +00008148 // FIXME: This approach for uniquing ADL results (and removing
8149 // redundant candidates from the set) relies on pointer-equality,
8150 // which means we need to key off the canonical decl. However,
8151 // always going back to the canonical decl might not get us the
8152 // right set of default arguments. What default arguments are
8153 // we supposed to consider on ADL candidates, anyway?
8154
Douglas Gregorcabea402009-09-22 15:41:20 +00008155 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008156 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008157
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008158 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008159 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8160 CandEnd = CandidateSet.end();
8161 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008162 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008163 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008164 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008165 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008166 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008167
8168 // For each of the ADL candidates we found, add it to the overload
8169 // set.
John McCall8fe68082010-01-26 07:16:45 +00008170 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008171 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008173 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008174 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008175
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008176 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8177 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008178 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008179 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008180 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008181 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008182 }
Douglas Gregore254f902009-02-04 00:32:51 +00008183}
8184
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008185/// isBetterOverloadCandidate - Determines whether the first overload
8186/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008187bool
John McCall5c32be02010-08-24 20:38:10 +00008188isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008189 const OverloadCandidate &Cand1,
8190 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008191 SourceLocation Loc,
8192 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008193 // Define viable functions to be better candidates than non-viable
8194 // functions.
8195 if (!Cand2.Viable)
8196 return Cand1.Viable;
8197 else if (!Cand1.Viable)
8198 return false;
8199
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008200 // C++ [over.match.best]p1:
8201 //
8202 // -- if F is a static member function, ICS1(F) is defined such
8203 // that ICS1(F) is neither better nor worse than ICS1(G) for
8204 // any function G, and, symmetrically, ICS1(G) is neither
8205 // better nor worse than ICS1(F).
8206 unsigned StartArg = 0;
8207 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8208 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008209
Douglas Gregord3cb3562009-07-07 23:38:56 +00008210 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008211 // A viable function F1 is defined to be a better function than another
8212 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008213 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008214 unsigned NumArgs = Cand1.NumConversions;
8215 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008216 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008217 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008218 switch (CompareImplicitConversionSequences(S,
8219 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008220 Cand2.Conversions[ArgIdx])) {
8221 case ImplicitConversionSequence::Better:
8222 // Cand1 has a better conversion sequence.
8223 HasBetterConversion = true;
8224 break;
8225
8226 case ImplicitConversionSequence::Worse:
8227 // Cand1 can't be better than Cand2.
8228 return false;
8229
8230 case ImplicitConversionSequence::Indistinguishable:
8231 // Do nothing.
8232 break;
8233 }
8234 }
8235
Mike Stump11289f42009-09-09 15:08:12 +00008236 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008237 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008238 if (HasBetterConversion)
8239 return true;
8240
Douglas Gregora1f013e2008-11-07 22:36:19 +00008241 // -- the context is an initialization by user-defined conversion
8242 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8243 // from the return type of F1 to the destination type (i.e.,
8244 // the type of the entity being initialized) is a better
8245 // conversion sequence than the standard conversion sequence
8246 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008247 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008248 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008249 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008250 // First check whether we prefer one of the conversion functions over the
8251 // other. This only distinguishes the results in non-standard, extension
8252 // cases such as the conversion from a lambda closure type to a function
8253 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008254 ImplicitConversionSequence::CompareKind Result =
8255 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8256 if (Result == ImplicitConversionSequence::Indistinguishable)
8257 Result = CompareStandardConversionSequences(S,
8258 Cand1.FinalConversion,
8259 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008260
Richard Smithec2748a2014-05-17 04:36:39 +00008261 if (Result != ImplicitConversionSequence::Indistinguishable)
8262 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008263
8264 // FIXME: Compare kind of reference binding if conversion functions
8265 // convert to a reference type used in direct reference binding, per
8266 // C++14 [over.match.best]p1 section 2 bullet 3.
8267 }
8268
8269 // -- F1 is a non-template function and F2 is a function template
8270 // specialization, or, if not that,
8271 bool Cand1IsSpecialization = Cand1.Function &&
8272 Cand1.Function->getPrimaryTemplate();
8273 bool Cand2IsSpecialization = Cand2.Function &&
8274 Cand2.Function->getPrimaryTemplate();
8275 if (Cand1IsSpecialization != Cand2IsSpecialization)
8276 return Cand2IsSpecialization;
8277
8278 // -- F1 and F2 are function template specializations, and the function
8279 // template for F1 is more specialized than the template for F2
8280 // according to the partial ordering rules described in 14.5.5.2, or,
8281 // if not that,
8282 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8283 if (FunctionTemplateDecl *BetterTemplate
8284 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8285 Cand2.Function->getPrimaryTemplate(),
8286 Loc,
8287 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8288 : TPOC_Call,
8289 Cand1.ExplicitCallArguments,
8290 Cand2.ExplicitCallArguments))
8291 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008292 }
8293
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008294 // Check for enable_if value-based overload resolution.
8295 if (Cand1.Function && Cand2.Function &&
8296 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8297 Cand2.Function->hasAttr<EnableIfAttr>())) {
8298 // FIXME: The next several lines are just
8299 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8300 // instead of reverse order which is how they're stored in the AST.
8301 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008302 if (Cand1.Function->hasAttrs()) {
8303 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008304 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8305 IsNotEnableIfAttr),
8306 Cand1Attrs.end());
8307 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008308 }
8309
8310 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008311 if (Cand2.Function->hasAttrs()) {
8312 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008313 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8314 IsNotEnableIfAttr),
8315 Cand2Attrs.end());
8316 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008317 }
Richard Smith9516eee2014-05-17 02:21:47 +00008318
8319 // Candidate 1 is better if it has strictly more attributes and
8320 // the common sequence is identical.
8321 if (Cand1Attrs.size() <= Cand2Attrs.size())
8322 return false;
8323
8324 auto Cand1I = Cand1Attrs.begin();
8325 for (auto &Cand2A : Cand2Attrs) {
8326 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008327 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008328 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8329 S.getASTContext(), true);
8330 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8331 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008332 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008333 return false;
8334 }
Richard Smith9516eee2014-05-17 02:21:47 +00008335
8336 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008337 }
8338
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008339 return false;
8340}
8341
Mike Stump11289f42009-09-09 15:08:12 +00008342/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008343/// within an overload candidate set.
8344///
James Dennettffad8b72012-06-22 08:10:18 +00008345/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008346/// which overload resolution occurs.
8347///
James Dennettffad8b72012-06-22 08:10:18 +00008348/// \param Best If overload resolution was successful or found a deleted
8349/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008350///
8351/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008352OverloadingResult
8353OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008354 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008355 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008356 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008357 Best = end();
8358 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8359 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008360 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008361 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008362 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008363 }
8364
8365 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008366 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008367 return OR_No_Viable_Function;
8368
8369 // Make sure that this function is better than every other viable
8370 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008371 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008372 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008373 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008374 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008375 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008376 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008377 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008378 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008379 }
Mike Stump11289f42009-09-09 15:08:12 +00008380
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008381 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008382 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008383 (Best->Function->isDeleted() ||
8384 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008385 return OR_Deleted;
8386
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008387 return OR_Success;
8388}
8389
John McCall53262c92010-01-12 02:15:36 +00008390namespace {
8391
8392enum OverloadCandidateKind {
8393 oc_function,
8394 oc_method,
8395 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008396 oc_function_template,
8397 oc_method_template,
8398 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008399 oc_implicit_default_constructor,
8400 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008401 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008402 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008403 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008404 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008405};
8406
John McCalle1ac8d12010-01-13 00:25:19 +00008407OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8408 FunctionDecl *Fn,
8409 std::string &Description) {
8410 bool isTemplate = false;
8411
8412 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8413 isTemplate = true;
8414 Description = S.getTemplateArgumentBindingsText(
8415 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8416 }
John McCallfd0b2f82010-01-06 09:43:14 +00008417
8418 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008419 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008420 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008421
Sebastian Redl08905022011-02-05 19:23:19 +00008422 if (Ctor->getInheritedConstructor())
8423 return oc_implicit_inherited_constructor;
8424
Alexis Hunt119c10e2011-05-25 23:16:36 +00008425 if (Ctor->isDefaultConstructor())
8426 return oc_implicit_default_constructor;
8427
8428 if (Ctor->isMoveConstructor())
8429 return oc_implicit_move_constructor;
8430
8431 assert(Ctor->isCopyConstructor() &&
8432 "unexpected sort of implicit constructor");
8433 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008434 }
8435
8436 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8437 // This actually gets spelled 'candidate function' for now, but
8438 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008439 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008440 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008441
Alexis Hunt119c10e2011-05-25 23:16:36 +00008442 if (Meth->isMoveAssignmentOperator())
8443 return oc_implicit_move_assignment;
8444
Douglas Gregor12695102012-02-10 08:36:38 +00008445 if (Meth->isCopyAssignmentOperator())
8446 return oc_implicit_copy_assignment;
8447
8448 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8449 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008450 }
8451
John McCalle1ac8d12010-01-13 00:25:19 +00008452 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008453}
8454
Larisse Voufo98b20f12013-07-19 23:00:19 +00008455void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008456 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8457 if (!Ctor) return;
8458
8459 Ctor = Ctor->getInheritedConstructor();
8460 if (!Ctor) return;
8461
8462 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8463}
8464
John McCall53262c92010-01-12 02:15:36 +00008465} // end anonymous namespace
8466
8467// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008468void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008469 std::string FnDesc;
8470 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008471 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8472 << (unsigned) K << FnDesc;
8473 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8474 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008475 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008476}
8477
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008478// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008479// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008480void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008481 assert(OverloadedExpr->getType() == Context.OverloadTy);
8482
8483 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8484 OverloadExpr *OvlExpr = Ovl.Expression;
8485
8486 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8487 IEnd = OvlExpr->decls_end();
8488 I != IEnd; ++I) {
8489 if (FunctionTemplateDecl *FunTmpl =
8490 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008491 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008492 } else if (FunctionDecl *Fun
8493 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008494 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008495 }
8496 }
8497}
8498
John McCall0d1da222010-01-12 00:44:57 +00008499/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8500/// "lead" diagnostic; it will be given two arguments, the source and
8501/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008502void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8503 Sema &S,
8504 SourceLocation CaretLoc,
8505 const PartialDiagnostic &PDiag) const {
8506 S.Diag(CaretLoc, PDiag)
8507 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008508 // FIXME: The note limiting machinery is borrowed from
8509 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8510 // refactoring here.
8511 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8512 unsigned CandsShown = 0;
8513 AmbiguousConversionSequence::const_iterator I, E;
8514 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8515 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8516 break;
8517 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008518 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008519 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008520 if (I != E)
8521 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008522}
8523
John McCall0d1da222010-01-12 00:44:57 +00008524namespace {
8525
John McCall6a61b522010-01-13 09:16:55 +00008526void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8527 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8528 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008529 assert(Cand->Function && "for now, candidate must be a function");
8530 FunctionDecl *Fn = Cand->Function;
8531
8532 // There's a conversion slot for the object argument if this is a
8533 // non-constructor method. Note that 'I' corresponds the
8534 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008535 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008536 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008537 if (I == 0)
8538 isObjectArgument = true;
8539 else
8540 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008541 }
8542
John McCalle1ac8d12010-01-13 00:25:19 +00008543 std::string FnDesc;
8544 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8545
John McCall6a61b522010-01-13 09:16:55 +00008546 Expr *FromExpr = Conv.Bad.FromExpr;
8547 QualType FromTy = Conv.Bad.getFromType();
8548 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008549
John McCallfb7ad0f2010-02-02 02:42:52 +00008550 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008551 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008552 Expr *E = FromExpr->IgnoreParens();
8553 if (isa<UnaryOperator>(E))
8554 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008555 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008556
8557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8558 << (unsigned) FnKind << FnDesc
8559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8560 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008561 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008562 return;
8563 }
8564
John McCall6d174642010-01-23 08:10:49 +00008565 // Do some hand-waving analysis to see if the non-viability is due
8566 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008567 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8568 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8569 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8570 CToTy = RT->getPointeeType();
8571 else {
8572 // TODO: detect and diagnose the full richness of const mismatches.
8573 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8574 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8575 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8576 }
8577
8578 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8579 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008580 Qualifiers FromQs = CFromTy.getQualifiers();
8581 Qualifiers ToQs = CToTy.getQualifiers();
8582
8583 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8585 << (unsigned) FnKind << FnDesc
8586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8587 << FromTy
8588 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8589 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008590 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008591 return;
8592 }
8593
John McCall31168b02011-06-15 23:02:42 +00008594 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008596 << (unsigned) FnKind << FnDesc
8597 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8598 << FromTy
8599 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8600 << (unsigned) isObjectArgument << I+1;
8601 MaybeEmitInheritedConstructorNote(S, Fn);
8602 return;
8603 }
8604
Douglas Gregoraec25842011-04-26 23:16:46 +00008605 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8607 << (unsigned) FnKind << FnDesc
8608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8609 << FromTy
8610 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8611 << (unsigned) isObjectArgument << I+1;
8612 MaybeEmitInheritedConstructorNote(S, Fn);
8613 return;
8614 }
8615
John McCall47000992010-01-14 03:28:57 +00008616 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8617 assert(CVR && "unexpected qualifiers mismatch");
8618
8619 if (isObjectArgument) {
8620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8621 << (unsigned) FnKind << FnDesc
8622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8623 << FromTy << (CVR - 1);
8624 } else {
8625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8626 << (unsigned) FnKind << FnDesc
8627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8628 << FromTy << (CVR - 1) << I+1;
8629 }
Sebastian Redl08905022011-02-05 19:23:19 +00008630 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008631 return;
8632 }
8633
Sebastian Redla72462c2011-09-24 17:48:32 +00008634 // Special diagnostic for failure to convert an initializer list, since
8635 // telling the user that it has type void is not useful.
8636 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8638 << (unsigned) FnKind << FnDesc
8639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8640 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8641 MaybeEmitInheritedConstructorNote(S, Fn);
8642 return;
8643 }
8644
John McCall6d174642010-01-23 08:10:49 +00008645 // Diagnose references or pointers to incomplete types differently,
8646 // since it's far from impossible that the incompleteness triggered
8647 // the failure.
8648 QualType TempFromTy = FromTy.getNonReferenceType();
8649 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8650 TempFromTy = PTy->getPointeeType();
8651 if (TempFromTy->isIncompleteType()) {
8652 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8653 << (unsigned) FnKind << FnDesc
8654 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8655 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008656 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008657 return;
8658 }
8659
Douglas Gregor56f2e342010-06-30 23:01:39 +00008660 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008661 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008662 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8663 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8664 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8665 FromPtrTy->getPointeeType()) &&
8666 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8667 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008668 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008669 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008670 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008671 }
8672 } else if (const ObjCObjectPointerType *FromPtrTy
8673 = FromTy->getAs<ObjCObjectPointerType>()) {
8674 if (const ObjCObjectPointerType *ToPtrTy
8675 = ToTy->getAs<ObjCObjectPointerType>())
8676 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8677 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8678 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8679 FromPtrTy->getPointeeType()) &&
8680 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008681 BaseToDerivedConversion = 2;
8682 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008683 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8684 !FromTy->isIncompleteType() &&
8685 !ToRefTy->getPointeeType()->isIncompleteType() &&
8686 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8687 BaseToDerivedConversion = 3;
8688 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8689 ToTy.getNonReferenceType().getCanonicalType() ==
8690 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8692 << (unsigned) FnKind << FnDesc
8693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8694 << (unsigned) isObjectArgument << I + 1;
8695 MaybeEmitInheritedConstructorNote(S, Fn);
8696 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008697 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008699
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008700 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008701 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008702 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008703 << (unsigned) FnKind << FnDesc
8704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008705 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008706 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008707 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008708 return;
8709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008710
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008711 if (isa<ObjCObjectPointerType>(CFromTy) &&
8712 isa<PointerType>(CToTy)) {
8713 Qualifiers FromQs = CFromTy.getQualifiers();
8714 Qualifiers ToQs = CToTy.getQualifiers();
8715 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8717 << (unsigned) FnKind << FnDesc
8718 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8720 MaybeEmitInheritedConstructorNote(S, Fn);
8721 return;
8722 }
8723 }
8724
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008725 // Emit the generic diagnostic and, optionally, add the hints to it.
8726 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8727 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008728 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008729 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8730 << (unsigned) (Cand->Fix.Kind);
8731
8732 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008733 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8734 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008735 FDiag << *HI;
8736 S.Diag(Fn->getLocation(), FDiag);
8737
Sebastian Redl08905022011-02-05 19:23:19 +00008738 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008739}
8740
Larisse Voufo98b20f12013-07-19 23:00:19 +00008741/// Additional arity mismatch diagnosis specific to a function overload
8742/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8743/// over a candidate in any candidate set.
8744bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8745 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008746 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008747 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008748
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008749 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008750 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008751 // right number of arguments, because only overloaded operators have
8752 // the weird behavior of overloading member and non-member functions.
8753 // Just don't report anything.
8754 if (Fn->isInvalidDecl() &&
8755 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008756 return true;
8757
8758 if (NumArgs < MinParams) {
8759 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8760 (Cand->FailureKind == ovl_fail_bad_deduction &&
8761 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8762 } else {
8763 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8764 (Cand->FailureKind == ovl_fail_bad_deduction &&
8765 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8766 }
8767
8768 return false;
8769}
8770
8771/// General arity mismatch diagnosis over a candidate in a candidate set.
8772void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8773 assert(isa<FunctionDecl>(D) &&
8774 "The templated declaration should at least be a function"
8775 " when diagnosing bad template argument deduction due to too many"
8776 " or too few arguments");
8777
8778 FunctionDecl *Fn = cast<FunctionDecl>(D);
8779
8780 // TODO: treat calls to a missing default constructor as a special case
8781 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8782 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008783
John McCall6a61b522010-01-13 09:16:55 +00008784 // at least / at most / exactly
8785 unsigned mode, modeCount;
8786 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008787 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8788 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008789 mode = 0; // "at least"
8790 else
8791 mode = 2; // "exactly"
8792 modeCount = MinParams;
8793 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008794 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008795 mode = 1; // "at most"
8796 else
8797 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008798 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008799 }
8800
8801 std::string Description;
8802 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8803
Richard Smith10ff50d2012-05-11 05:16:41 +00008804 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8805 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008806 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8807 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008808 else
8809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008810 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8811 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008812 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008813}
8814
Larisse Voufo98b20f12013-07-19 23:00:19 +00008815/// Arity mismatch diagnosis specific to a function overload candidate.
8816void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8817 unsigned NumFormalArgs) {
8818 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8819 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8820}
Larisse Voufo47c08452013-07-19 22:53:23 +00008821
Larisse Voufo98b20f12013-07-19 23:00:19 +00008822TemplateDecl *getDescribedTemplate(Decl *Templated) {
8823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8824 return FD->getDescribedFunctionTemplate();
8825 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8826 return RD->getDescribedClassTemplate();
8827
8828 llvm_unreachable("Unsupported: Getting the described template declaration"
8829 " for bad deduction diagnosis");
8830}
8831
8832/// Diagnose a failed template-argument deduction.
8833void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8834 DeductionFailureInfo &DeductionFailure,
8835 unsigned NumArgs) {
8836 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008837 NamedDecl *ParamD;
8838 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8839 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8840 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008841 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008842 case Sema::TDK_Success:
8843 llvm_unreachable("TDK_success while diagnosing bad deduction");
8844
8845 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008846 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008847 S.Diag(Templated->getLocation(),
8848 diag::note_ovl_candidate_incomplete_deduction)
8849 << ParamD->getDeclName();
8850 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008851 return;
8852 }
8853
John McCall42d7d192010-08-05 09:05:08 +00008854 case Sema::TDK_Underqualified: {
8855 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8856 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8857
Larisse Voufo98b20f12013-07-19 23:00:19 +00008858 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008859
8860 // Param will have been canonicalized, but it should just be a
8861 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008862 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008863 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008864 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008865 assert(S.Context.hasSameType(Param, NonCanonParam));
8866
8867 // Arg has also been canonicalized, but there's nothing we can do
8868 // about that. It also doesn't matter as much, because it won't
8869 // have any template parameters in it (because deduction isn't
8870 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008871 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008872
Larisse Voufo98b20f12013-07-19 23:00:19 +00008873 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8874 << ParamD->getDeclName() << Arg << NonCanonParam;
8875 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008876 return;
8877 }
8878
8879 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008880 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008881 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008882 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008883 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008884 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008885 which = 1;
8886 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008887 which = 2;
8888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008889
Larisse Voufo98b20f12013-07-19 23:00:19 +00008890 S.Diag(Templated->getLocation(),
8891 diag::note_ovl_candidate_inconsistent_deduction)
8892 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8893 << *DeductionFailure.getSecondArg();
8894 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008895 return;
8896 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008897
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008898 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008899 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008900 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008901 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008902 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008903 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008904 else {
8905 int index = 0;
8906 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8907 index = TTP->getIndex();
8908 else if (NonTypeTemplateParmDecl *NTTP
8909 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8910 index = NTTP->getIndex();
8911 else
8912 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008913 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008914 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008915 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008916 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008917 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008918 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008919
Douglas Gregor02eb4832010-05-08 18:13:28 +00008920 case Sema::TDK_TooManyArguments:
8921 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008922 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008923 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008924
8925 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008926 S.Diag(Templated->getLocation(),
8927 diag::note_ovl_candidate_instantiation_depth);
8928 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008929 return;
8930
8931 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008932 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008933 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008934 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008935 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008936 TemplateArgString = " ";
8937 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008938 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008939 }
8940
Richard Smith6f8d2c62012-05-09 05:17:00 +00008941 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008942 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008943 if (PDiag && PDiag->second.getDiagID() ==
8944 diag::err_typename_nested_not_found_enable_if) {
8945 // FIXME: Use the source range of the condition, and the fully-qualified
8946 // name of the enable_if template. These are both present in PDiag.
8947 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8948 << "'enable_if'" << TemplateArgString;
8949 return;
8950 }
8951
Richard Smith9ca64612012-05-07 09:03:25 +00008952 // Format the SFINAE diagnostic into the argument string.
8953 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8954 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008955 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008956 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008957 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008958 SFINAEArgString = ": ";
8959 R = SourceRange(PDiag->first, PDiag->first);
8960 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8961 }
8962
Larisse Voufo98b20f12013-07-19 23:00:19 +00008963 S.Diag(Templated->getLocation(),
8964 diag::note_ovl_candidate_substitution_failure)
8965 << TemplateArgString << SFINAEArgString << R;
8966 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008967 return;
8968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008969
Richard Smith8c6eeb92013-01-31 04:03:12 +00008970 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008971 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8972 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008973 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008974 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008975 return;
8976 }
8977
Richard Trieue3732352013-04-08 21:11:40 +00008978 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008979 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008980 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8981 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008982 if (FirstTA.getKind() == TemplateArgument::Template &&
8983 SecondTA.getKind() == TemplateArgument::Template) {
8984 TemplateName FirstTN = FirstTA.getAsTemplate();
8985 TemplateName SecondTN = SecondTA.getAsTemplate();
8986 if (FirstTN.getKind() == TemplateName::Template &&
8987 SecondTN.getKind() == TemplateName::Template) {
8988 if (FirstTN.getAsTemplateDecl()->getName() ==
8989 SecondTN.getAsTemplateDecl()->getName()) {
8990 // FIXME: This fixes a bad diagnostic where both templates are named
8991 // the same. This particular case is a bit difficult since:
8992 // 1) It is passed as a string to the diagnostic printer.
8993 // 2) The diagnostic printer only attempts to find a better
8994 // name for types, not decls.
8995 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008996 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008997 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8998 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8999 return;
9000 }
9001 }
9002 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009003 // FIXME: For generic lambda parameters, check if the function is a lambda
9004 // call operator, and if so, emit a prettier and more informative
9005 // diagnostic that mentions 'auto' and lambda in addition to
9006 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009007 S.Diag(Templated->getLocation(),
9008 diag::note_ovl_candidate_non_deduced_mismatch)
9009 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009010 return;
Richard Trieue3732352013-04-08 21:11:40 +00009011 }
John McCall8b9ed552010-02-01 18:53:26 +00009012 // TODO: diagnose these individually, then kill off
9013 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009014 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009015 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9016 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009017 return;
9018 }
9019}
9020
Larisse Voufo98b20f12013-07-19 23:00:19 +00009021/// Diagnose a failed template-argument deduction, for function calls.
9022void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
9023 unsigned TDK = Cand->DeductionFailure.Result;
9024 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9025 if (CheckArityMismatch(S, Cand, NumArgs))
9026 return;
9027 }
9028 DiagnoseBadDeduction(S, Cand->Function, // pattern
9029 Cand->DeductionFailure, NumArgs);
9030}
9031
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009032/// CUDA: diagnose an invalid call across targets.
9033void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9034 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9035 FunctionDecl *Callee = Cand->Function;
9036
9037 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9038 CalleeTarget = S.IdentifyCUDATarget(Callee);
9039
9040 std::string FnDesc;
9041 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9042
9043 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9044 << (unsigned) FnKind << CalleeTarget << CallerTarget;
9045}
9046
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009047void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9048 FunctionDecl *Callee = Cand->Function;
9049 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9050
9051 S.Diag(Callee->getLocation(),
9052 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9053 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9054}
9055
John McCall8b9ed552010-02-01 18:53:26 +00009056/// Generates a 'note' diagnostic for an overload candidate. We've
9057/// already generated a primary error at the call site.
9058///
9059/// It really does need to be a single diagnostic with its caret
9060/// pointed at the candidate declaration. Yes, this creates some
9061/// major challenges of technical writing. Yes, this makes pointing
9062/// out problems with specific arguments quite awkward. It's still
9063/// better than generating twenty screens of text for every failed
9064/// overload.
9065///
9066/// It would be great to be able to express per-candidate problems
9067/// more richly for those diagnostic clients that cared, but we'd
9068/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009069void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009070 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009071 FunctionDecl *Fn = Cand->Function;
9072
John McCall12f97bc2010-01-08 04:41:39 +00009073 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009074 if (Cand->Viable && (Fn->isDeleted() ||
9075 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009076 std::string FnDesc;
9077 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009078
9079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009080 << FnKind << FnDesc
9081 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009082 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009083 return;
John McCall12f97bc2010-01-08 04:41:39 +00009084 }
9085
John McCalle1ac8d12010-01-13 00:25:19 +00009086 // We don't really have anything else to say about viable candidates.
9087 if (Cand->Viable) {
9088 S.NoteOverloadCandidate(Fn);
9089 return;
9090 }
John McCall0d1da222010-01-12 00:44:57 +00009091
John McCall6a61b522010-01-13 09:16:55 +00009092 switch (Cand->FailureKind) {
9093 case ovl_fail_too_many_arguments:
9094 case ovl_fail_too_few_arguments:
9095 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009096
John McCall6a61b522010-01-13 09:16:55 +00009097 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009098 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009099
John McCallfe796dd2010-01-23 05:17:32 +00009100 case ovl_fail_trivial_conversion:
9101 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009102 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009103 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009104
John McCall65eb8792010-02-25 01:37:24 +00009105 case ovl_fail_bad_conversion: {
9106 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009107 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009108 if (Cand->Conversions[I].isBad())
9109 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110
John McCall6a61b522010-01-13 09:16:55 +00009111 // FIXME: this currently happens when we're called from SemaInit
9112 // when user-conversion overload fails. Figure out how to handle
9113 // those conditions and diagnose them well.
9114 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009115 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009116
9117 case ovl_fail_bad_target:
9118 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009119
9120 case ovl_fail_enable_if:
9121 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009122 }
John McCalld3224162010-01-08 00:58:21 +00009123}
9124
9125void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9126 // Desugar the type of the surrogate down to a function type,
9127 // retaining as many typedefs as possible while still showing
9128 // the function type (and, therefore, its parameter types).
9129 QualType FnType = Cand->Surrogate->getConversionType();
9130 bool isLValueReference = false;
9131 bool isRValueReference = false;
9132 bool isPointer = false;
9133 if (const LValueReferenceType *FnTypeRef =
9134 FnType->getAs<LValueReferenceType>()) {
9135 FnType = FnTypeRef->getPointeeType();
9136 isLValueReference = true;
9137 } else if (const RValueReferenceType *FnTypeRef =
9138 FnType->getAs<RValueReferenceType>()) {
9139 FnType = FnTypeRef->getPointeeType();
9140 isRValueReference = true;
9141 }
9142 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9143 FnType = FnTypePtr->getPointeeType();
9144 isPointer = true;
9145 }
9146 // Desugar down to a function type.
9147 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9148 // Reconstruct the pointer/reference as appropriate.
9149 if (isPointer) FnType = S.Context.getPointerType(FnType);
9150 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9151 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9152
9153 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9154 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009155 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009156}
9157
9158void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009159 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009160 SourceLocation OpLoc,
9161 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009162 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009163 std::string TypeStr("operator");
9164 TypeStr += Opc;
9165 TypeStr += "(";
9166 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009167 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009168 TypeStr += ")";
9169 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9170 } else {
9171 TypeStr += ", ";
9172 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9173 TypeStr += ")";
9174 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9175 }
9176}
9177
9178void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9179 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009180 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009181 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9182 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009183 if (ICS.isBad()) break; // all meaningless after first invalid
9184 if (!ICS.isAmbiguous()) continue;
9185
John McCall5c32be02010-08-24 20:38:10 +00009186 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009187 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009188 }
9189}
9190
Larisse Voufo98b20f12013-07-19 23:00:19 +00009191static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009192 if (Cand->Function)
9193 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009194 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009195 return Cand->Surrogate->getLocation();
9196 return SourceLocation();
9197}
9198
Larisse Voufo98b20f12013-07-19 23:00:19 +00009199static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009200 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009201 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009202 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009203
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009204 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009205 case Sema::TDK_Incomplete:
9206 return 1;
9207
9208 case Sema::TDK_Underqualified:
9209 case Sema::TDK_Inconsistent:
9210 return 2;
9211
9212 case Sema::TDK_SubstitutionFailure:
9213 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009214 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009215 return 3;
9216
9217 case Sema::TDK_InstantiationDepth:
9218 case Sema::TDK_FailedOverloadResolution:
9219 return 4;
9220
9221 case Sema::TDK_InvalidExplicitArguments:
9222 return 5;
9223
9224 case Sema::TDK_TooManyArguments:
9225 case Sema::TDK_TooFewArguments:
9226 return 6;
9227 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009228 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009229}
9230
John McCallad2587a2010-01-12 00:48:53 +00009231struct CompareOverloadCandidatesForDisplay {
9232 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009233 size_t NumArgs;
9234
9235 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9236 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009237
9238 bool operator()(const OverloadCandidate *L,
9239 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009240 // Fast-path this check.
9241 if (L == R) return false;
9242
John McCall12f97bc2010-01-08 04:41:39 +00009243 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009244 if (L->Viable) {
9245 if (!R->Viable) return true;
9246
9247 // TODO: introduce a tri-valued comparison for overload
9248 // candidates. Would be more worthwhile if we had a sort
9249 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009250 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9251 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009252 } else if (R->Viable)
9253 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009254
John McCall3712d9e2010-01-15 23:32:50 +00009255 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009256
John McCall3712d9e2010-01-15 23:32:50 +00009257 // Criteria by which we can sort non-viable candidates:
9258 if (!L->Viable) {
9259 // 1. Arity mismatches come after other candidates.
9260 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009261 L->FailureKind == ovl_fail_too_few_arguments) {
9262 if (R->FailureKind == ovl_fail_too_many_arguments ||
9263 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009264 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9265 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9266 if (LDist == RDist) {
9267 if (L->FailureKind == R->FailureKind)
9268 // Sort non-surrogates before surrogates.
9269 return !L->IsSurrogate && R->IsSurrogate;
9270 // Sort candidates requiring fewer parameters than there were
9271 // arguments given after candidates requiring more parameters
9272 // than there were arguments given.
9273 return L->FailureKind == ovl_fail_too_many_arguments;
9274 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009275 return LDist < RDist;
9276 }
John McCall3712d9e2010-01-15 23:32:50 +00009277 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009278 }
John McCall3712d9e2010-01-15 23:32:50 +00009279 if (R->FailureKind == ovl_fail_too_many_arguments ||
9280 R->FailureKind == ovl_fail_too_few_arguments)
9281 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009282
John McCallfe796dd2010-01-23 05:17:32 +00009283 // 2. Bad conversions come first and are ordered by the number
9284 // of bad conversions and quality of good conversions.
9285 if (L->FailureKind == ovl_fail_bad_conversion) {
9286 if (R->FailureKind != ovl_fail_bad_conversion)
9287 return true;
9288
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009289 // The conversion that can be fixed with a smaller number of changes,
9290 // comes first.
9291 unsigned numLFixes = L->Fix.NumConversionsFixed;
9292 unsigned numRFixes = R->Fix.NumConversionsFixed;
9293 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9294 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009295 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009296 if (numLFixes < numRFixes)
9297 return true;
9298 else
9299 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009300 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009301
John McCallfe796dd2010-01-23 05:17:32 +00009302 // If there's any ordering between the defined conversions...
9303 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009304 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009305
9306 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009307 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009308 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009309 switch (CompareImplicitConversionSequences(S,
9310 L->Conversions[I],
9311 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009312 case ImplicitConversionSequence::Better:
9313 leftBetter++;
9314 break;
9315
9316 case ImplicitConversionSequence::Worse:
9317 leftBetter--;
9318 break;
9319
9320 case ImplicitConversionSequence::Indistinguishable:
9321 break;
9322 }
9323 }
9324 if (leftBetter > 0) return true;
9325 if (leftBetter < 0) return false;
9326
9327 } else if (R->FailureKind == ovl_fail_bad_conversion)
9328 return false;
9329
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009330 if (L->FailureKind == ovl_fail_bad_deduction) {
9331 if (R->FailureKind != ovl_fail_bad_deduction)
9332 return true;
9333
9334 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9335 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009336 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009337 } else if (R->FailureKind == ovl_fail_bad_deduction)
9338 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009339
John McCall3712d9e2010-01-15 23:32:50 +00009340 // TODO: others?
9341 }
9342
9343 // Sort everything else by location.
9344 SourceLocation LLoc = GetLocationForCandidate(L);
9345 SourceLocation RLoc = GetLocationForCandidate(R);
9346
9347 // Put candidates without locations (e.g. builtins) at the end.
9348 if (LLoc.isInvalid()) return false;
9349 if (RLoc.isInvalid()) return true;
9350
9351 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009352 }
9353};
9354
John McCallfe796dd2010-01-23 05:17:32 +00009355/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009356/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009357void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009358 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009359 assert(!Cand->Viable);
9360
9361 // Don't do anything on failures other than bad conversion.
9362 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9363
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009364 // We only want the FixIts if all the arguments can be corrected.
9365 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009366 // Use a implicit copy initialization to check conversion fixes.
9367 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009368
John McCallfe796dd2010-01-23 05:17:32 +00009369 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009370 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009371 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009372 while (true) {
9373 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9374 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009375 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009376 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009377 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009378 }
John McCallfe796dd2010-01-23 05:17:32 +00009379 }
9380
9381 if (ConvIdx == ConvCount)
9382 return;
9383
John McCall65eb8792010-02-25 01:37:24 +00009384 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9385 "remaining conversion is initialized?");
9386
Douglas Gregoradc7a702010-04-16 17:45:54 +00009387 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009388 // operation somehow.
9389 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009390
9391 const FunctionProtoType* Proto;
9392 unsigned ArgIdx = ConvIdx;
9393
9394 if (Cand->IsSurrogate) {
9395 QualType ConvType
9396 = Cand->Surrogate->getConversionType().getNonReferenceType();
9397 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9398 ConvType = ConvPtrType->getPointeeType();
9399 Proto = ConvType->getAs<FunctionProtoType>();
9400 ArgIdx--;
9401 } else if (Cand->Function) {
9402 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9403 if (isa<CXXMethodDecl>(Cand->Function) &&
9404 !isa<CXXConstructorDecl>(Cand->Function))
9405 ArgIdx--;
9406 } else {
9407 // Builtin binary operator with a bad first conversion.
9408 assert(ConvCount <= 3);
9409 for (; ConvIdx != ConvCount; ++ConvIdx)
9410 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009411 = TryCopyInitialization(S, Args[ConvIdx],
9412 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009413 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009414 /*InOverloadResolution*/ true,
9415 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009416 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009417 return;
9418 }
9419
9420 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009421 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009422 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009423 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009424 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9425 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9426 /*InOverloadResolution=*/true,
9427 /*AllowObjCWritebackConversion=*/
9428 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009429 // Store the FixIt in the candidate if it exists.
9430 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009431 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009432 }
John McCallfe796dd2010-01-23 05:17:32 +00009433 else
9434 Cand->Conversions[ConvIdx].setEllipsis();
9435 }
9436}
9437
John McCalld3224162010-01-08 00:58:21 +00009438} // end anonymous namespace
9439
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009440/// PrintOverloadCandidates - When overload resolution fails, prints
9441/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009442/// set.
John McCall5c32be02010-08-24 20:38:10 +00009443void OverloadCandidateSet::NoteCandidates(Sema &S,
9444 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009445 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009446 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009447 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009448 // Sort the candidates by viability and position. Sorting directly would
9449 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009450 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009451 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9452 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009453 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009454 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009455 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009456 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009457 if (Cand->Function || Cand->IsSurrogate)
9458 Cands.push_back(Cand);
9459 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9460 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009461 }
9462 }
9463
John McCallad2587a2010-01-12 00:48:53 +00009464 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009465 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009466
John McCall0d1da222010-01-12 00:44:57 +00009467 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009468
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009469 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009470 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009471 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009472 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9473 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009474
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009475 // Set an arbitrary limit on the number of candidate functions we'll spam
9476 // the user with. FIXME: This limit should depend on details of the
9477 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009478 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009479 break;
9480 }
9481 ++CandsShown;
9482
John McCalld3224162010-01-08 00:58:21 +00009483 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009484 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009485 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009486 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009487 else {
9488 assert(Cand->Viable &&
9489 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009490 // Generally we only see ambiguities including viable builtin
9491 // operators if overload resolution got screwed up by an
9492 // ambiguous user-defined conversion.
9493 //
9494 // FIXME: It's quite possible for different conversions to see
9495 // different ambiguities, though.
9496 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009497 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009498 ReportedAmbiguousConversions = true;
9499 }
John McCalld3224162010-01-08 00:58:21 +00009500
John McCall0d1da222010-01-12 00:44:57 +00009501 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009502 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009503 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009504 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009505
9506 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009507 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009508}
9509
Larisse Voufo98b20f12013-07-19 23:00:19 +00009510static SourceLocation
9511GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9512 return Cand->Specialization ? Cand->Specialization->getLocation()
9513 : SourceLocation();
9514}
9515
9516struct CompareTemplateSpecCandidatesForDisplay {
9517 Sema &S;
9518 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9519
9520 bool operator()(const TemplateSpecCandidate *L,
9521 const TemplateSpecCandidate *R) {
9522 // Fast-path this check.
9523 if (L == R)
9524 return false;
9525
9526 // Assuming that both candidates are not matches...
9527
9528 // Sort by the ranking of deduction failures.
9529 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9530 return RankDeductionFailure(L->DeductionFailure) <
9531 RankDeductionFailure(R->DeductionFailure);
9532
9533 // Sort everything else by location.
9534 SourceLocation LLoc = GetLocationForCandidate(L);
9535 SourceLocation RLoc = GetLocationForCandidate(R);
9536
9537 // Put candidates without locations (e.g. builtins) at the end.
9538 if (LLoc.isInvalid())
9539 return false;
9540 if (RLoc.isInvalid())
9541 return true;
9542
9543 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9544 }
9545};
9546
9547/// Diagnose a template argument deduction failure.
9548/// We are treating these failures as overload failures due to bad
9549/// deductions.
9550void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9551 DiagnoseBadDeduction(S, Specialization, // pattern
9552 DeductionFailure, /*NumArgs=*/0);
9553}
9554
9555void TemplateSpecCandidateSet::destroyCandidates() {
9556 for (iterator i = begin(), e = end(); i != e; ++i) {
9557 i->DeductionFailure.Destroy();
9558 }
9559}
9560
9561void TemplateSpecCandidateSet::clear() {
9562 destroyCandidates();
9563 Candidates.clear();
9564}
9565
9566/// NoteCandidates - When no template specialization match is found, prints
9567/// diagnostic messages containing the non-matching specializations that form
9568/// the candidate set.
9569/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9570/// OCD == OCD_AllCandidates and Cand->Viable == false.
9571void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9572 // Sort the candidates by position (assuming no candidate is a match).
9573 // Sorting directly would be prohibitive, so we make a set of pointers
9574 // and sort those.
9575 SmallVector<TemplateSpecCandidate *, 32> Cands;
9576 Cands.reserve(size());
9577 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9578 if (Cand->Specialization)
9579 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009580 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009581 // in general, want to list every possible builtin candidate.
9582 }
9583
9584 std::sort(Cands.begin(), Cands.end(),
9585 CompareTemplateSpecCandidatesForDisplay(S));
9586
9587 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9588 // for generalization purposes (?).
9589 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9590
9591 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9592 unsigned CandsShown = 0;
9593 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9594 TemplateSpecCandidate *Cand = *I;
9595
9596 // Set an arbitrary limit on the number of candidates we'll spam
9597 // the user with. FIXME: This limit should depend on details of the
9598 // candidate list.
9599 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9600 break;
9601 ++CandsShown;
9602
9603 assert(Cand->Specialization &&
9604 "Non-matching built-in candidates are not added to Cands.");
9605 Cand->NoteDeductionFailure(S);
9606 }
9607
9608 if (I != E)
9609 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9610}
9611
Douglas Gregorb491ed32011-02-19 21:32:49 +00009612// [PossiblyAFunctionType] --> [Return]
9613// NonFunctionType --> NonFunctionType
9614// R (A) --> R(A)
9615// R (*)(A) --> R (A)
9616// R (&)(A) --> R (A)
9617// R (S::*)(A) --> R (A)
9618QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9619 QualType Ret = PossiblyAFunctionType;
9620 if (const PointerType *ToTypePtr =
9621 PossiblyAFunctionType->getAs<PointerType>())
9622 Ret = ToTypePtr->getPointeeType();
9623 else if (const ReferenceType *ToTypeRef =
9624 PossiblyAFunctionType->getAs<ReferenceType>())
9625 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009626 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009627 PossiblyAFunctionType->getAs<MemberPointerType>())
9628 Ret = MemTypePtr->getPointeeType();
9629 Ret =
9630 Context.getCanonicalType(Ret).getUnqualifiedType();
9631 return Ret;
9632}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009633
Douglas Gregorb491ed32011-02-19 21:32:49 +00009634// A helper class to help with address of function resolution
9635// - allows us to avoid passing around all those ugly parameters
9636class AddressOfFunctionResolver
9637{
9638 Sema& S;
9639 Expr* SourceExpr;
9640 const QualType& TargetType;
9641 QualType TargetFunctionType; // Extracted function type from target type
9642
9643 bool Complain;
9644 //DeclAccessPair& ResultFunctionAccessPair;
9645 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009646
Douglas Gregorb491ed32011-02-19 21:32:49 +00009647 bool TargetTypeIsNonStaticMemberFunction;
9648 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009649 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009650
Douglas Gregorb491ed32011-02-19 21:32:49 +00009651 OverloadExpr::FindResult OvlExprInfo;
9652 OverloadExpr *OvlExpr;
9653 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009654 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009655 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009656
Douglas Gregorb491ed32011-02-19 21:32:49 +00009657public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009658 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9659 const QualType &TargetType, bool Complain)
9660 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9661 Complain(Complain), Context(S.getASTContext()),
9662 TargetTypeIsNonStaticMemberFunction(
9663 !!TargetType->getAs<MemberPointerType>()),
9664 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009665 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009666 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9667 OvlExpr(OvlExprInfo.Expression),
9668 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009669 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009670
David Majnemera4f7c7a2013-08-01 06:13:59 +00009671 if (TargetFunctionType->isFunctionType()) {
9672 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9673 if (!UME->isImplicitAccess() &&
9674 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9675 StaticMemberFunctionFromBoundPointer = true;
9676 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9677 DeclAccessPair dap;
9678 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9679 OvlExpr, false, &dap)) {
9680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9681 if (!Method->isStatic()) {
9682 // If the target type is a non-function type and the function found
9683 // is a non-static member function, pretend as if that was the
9684 // target, it's the only possible type to end up with.
9685 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009686
David Majnemera4f7c7a2013-08-01 06:13:59 +00009687 // And skip adding the function if its not in the proper form.
9688 // We'll diagnose this due to an empty set of functions.
9689 if (!OvlExprInfo.HasFormOfMemberPointer)
9690 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009691 }
9692
David Majnemera4f7c7a2013-08-01 06:13:59 +00009693 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009694 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009695 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009696 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009697
9698 if (OvlExpr->hasExplicitTemplateArgs())
9699 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009700
Douglas Gregorb491ed32011-02-19 21:32:49 +00009701 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9702 // C++ [over.over]p4:
9703 // If more than one function is selected, [...]
9704 if (Matches.size() > 1) {
9705 if (FoundNonTemplateFunction)
9706 EliminateAllTemplateMatches();
9707 else
9708 EliminateAllExceptMostSpecializedTemplate();
9709 }
9710 }
9711 }
9712
9713private:
9714 bool isTargetTypeAFunction() const {
9715 return TargetFunctionType->isFunctionType();
9716 }
9717
9718 // [ToType] [Return]
9719
9720 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9721 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9722 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9723 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9724 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9725 }
9726
9727 // return true if any matching specializations were found
9728 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9729 const DeclAccessPair& CurAccessFunPair) {
9730 if (CXXMethodDecl *Method
9731 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9732 // Skip non-static function templates when converting to pointer, and
9733 // static when converting to member pointer.
9734 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9735 return false;
9736 }
9737 else if (TargetTypeIsNonStaticMemberFunction)
9738 return false;
9739
9740 // C++ [over.over]p2:
9741 // If the name is a function template, template argument deduction is
9742 // done (14.8.2.2), and if the argument deduction succeeds, the
9743 // resulting template argument list is used to generate a single
9744 // function template specialization, which is added to the set of
9745 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009746 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009747 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009748 if (Sema::TemplateDeductionResult Result
9749 = S.DeduceTemplateArguments(FunctionTemplate,
9750 &OvlExplicitTemplateArgs,
9751 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009752 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009753 // Make a note of the failed deduction for diagnostics.
9754 FailedCandidates.addCandidate()
9755 .set(FunctionTemplate->getTemplatedDecl(),
9756 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009757 return false;
9758 }
9759
Douglas Gregor19a41f12013-04-17 08:45:07 +00009760 // Template argument deduction ensures that we have an exact match or
9761 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009762 // This function template specicalization works.
9763 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009764 assert(S.isSameOrCompatibleFunctionType(
9765 Context.getCanonicalType(Specialization->getType()),
9766 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009767 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9768 return true;
9769 }
9770
9771 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9772 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009774 // Skip non-static functions when converting to pointer, and static
9775 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009776 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9777 return false;
9778 }
9779 else if (TargetTypeIsNonStaticMemberFunction)
9780 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009781
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009782 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009783 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009784 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9785 if (S.CheckCUDATarget(Caller, FunDecl))
9786 return false;
9787
Richard Smith2a7d4812013-05-04 07:00:32 +00009788 // If any candidate has a placeholder return type, trigger its deduction
9789 // now.
9790 if (S.getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00009791 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009792 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9793 return false;
9794
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009795 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009796 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9797 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009798 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9799 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009800 Matches.push_back(std::make_pair(CurAccessFunPair,
9801 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009802 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009803 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009804 }
Mike Stump11289f42009-09-09 15:08:12 +00009805 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009806
9807 return false;
9808 }
9809
9810 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9811 bool Ret = false;
9812
9813 // If the overload expression doesn't have the form of a pointer to
9814 // member, don't try to convert it to a pointer-to-member type.
9815 if (IsInvalidFormOfPointerToMemberFunction())
9816 return false;
9817
9818 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9819 E = OvlExpr->decls_end();
9820 I != E; ++I) {
9821 // Look through any using declarations to find the underlying function.
9822 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9823
9824 // C++ [over.over]p3:
9825 // Non-member functions and static member functions match
9826 // targets of type "pointer-to-function" or "reference-to-function."
9827 // Nonstatic member functions match targets of
9828 // type "pointer-to-member-function."
9829 // Note that according to DR 247, the containing class does not matter.
9830 if (FunctionTemplateDecl *FunctionTemplate
9831 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9832 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9833 Ret = true;
9834 }
9835 // If we have explicit template arguments supplied, skip non-templates.
9836 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9837 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9838 Ret = true;
9839 }
9840 assert(Ret || Matches.empty());
9841 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009842 }
9843
Douglas Gregorb491ed32011-02-19 21:32:49 +00009844 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009845 // [...] and any given function template specialization F1 is
9846 // eliminated if the set contains a second function template
9847 // specialization whose function template is more specialized
9848 // than the function template of F1 according to the partial
9849 // ordering rules of 14.5.5.2.
9850
9851 // The algorithm specified above is quadratic. We instead use a
9852 // two-pass algorithm (similar to the one used to identify the
9853 // best viable function in an overload set) that identifies the
9854 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009855
9856 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9857 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9858 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009859
Larisse Voufo98b20f12013-07-19 23:00:19 +00009860 // TODO: It looks like FailedCandidates does not serve much purpose
9861 // here, since the no_viable diagnostic has index 0.
9862 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009863 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009864 SourceExpr->getLocStart(), S.PDiag(),
9865 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9866 .second->getDeclName(),
9867 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9868 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009869
Douglas Gregorb491ed32011-02-19 21:32:49 +00009870 if (Result != MatchesCopy.end()) {
9871 // Make it the first and only element
9872 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9873 Matches[0].second = cast<FunctionDecl>(*Result);
9874 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009875 }
9876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009877
Douglas Gregorb491ed32011-02-19 21:32:49 +00009878 void EliminateAllTemplateMatches() {
9879 // [...] any function template specializations in the set are
9880 // eliminated if the set also contains a non-template function, [...]
9881 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009882 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009883 ++I;
9884 else {
9885 Matches[I] = Matches[--N];
9886 Matches.set_size(N);
9887 }
9888 }
9889 }
9890
9891public:
9892 void ComplainNoMatchesFound() const {
9893 assert(Matches.empty());
9894 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9895 << OvlExpr->getName() << TargetFunctionType
9896 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009897 if (FailedCandidates.empty())
9898 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9899 else {
9900 // We have some deduction failure messages. Use them to diagnose
9901 // the function templates, and diagnose the non-template candidates
9902 // normally.
9903 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9904 IEnd = OvlExpr->decls_end();
9905 I != IEnd; ++I)
9906 if (FunctionDecl *Fun =
9907 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9908 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9909 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9910 }
9911 }
9912
Douglas Gregorb491ed32011-02-19 21:32:49 +00009913 bool IsInvalidFormOfPointerToMemberFunction() const {
9914 return TargetTypeIsNonStaticMemberFunction &&
9915 !OvlExprInfo.HasFormOfMemberPointer;
9916 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009917
Douglas Gregorb491ed32011-02-19 21:32:49 +00009918 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9919 // TODO: Should we condition this on whether any functions might
9920 // have matched, or is it more appropriate to do that in callers?
9921 // TODO: a fixit wouldn't hurt.
9922 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9923 << TargetType << OvlExpr->getSourceRange();
9924 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009925
9926 bool IsStaticMemberFunctionFromBoundPointer() const {
9927 return StaticMemberFunctionFromBoundPointer;
9928 }
9929
9930 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9931 S.Diag(OvlExpr->getLocStart(),
9932 diag::err_invalid_form_pointer_member_function)
9933 << OvlExpr->getSourceRange();
9934 }
9935
Douglas Gregorb491ed32011-02-19 21:32:49 +00009936 void ComplainOfInvalidConversion() const {
9937 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9938 << OvlExpr->getName() << TargetType;
9939 }
9940
9941 void ComplainMultipleMatchesFound() const {
9942 assert(Matches.size() > 1);
9943 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9944 << OvlExpr->getName()
9945 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009946 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009947 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009948
9949 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9950
Douglas Gregorb491ed32011-02-19 21:32:49 +00009951 int getNumMatches() const { return Matches.size(); }
9952
9953 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +00009954 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009955 return Matches[0].second;
9956 }
9957
9958 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +00009959 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009960 return &Matches[0].first;
9961 }
9962};
9963
9964/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9965/// an overloaded function (C++ [over.over]), where @p From is an
9966/// expression with overloaded function type and @p ToType is the type
9967/// we're trying to resolve to. For example:
9968///
9969/// @code
9970/// int f(double);
9971/// int f(int);
9972///
9973/// int (*pfd)(double) = f; // selects f(double)
9974/// @endcode
9975///
9976/// This routine returns the resulting FunctionDecl if it could be
9977/// resolved, and NULL otherwise. When @p Complain is true, this
9978/// routine will emit diagnostics if there is an error.
9979FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009980Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9981 QualType TargetType,
9982 bool Complain,
9983 DeclAccessPair &FoundResult,
9984 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009985 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009986
9987 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9988 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009989 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +00009990 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009991 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009992 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9993 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9994 else
9995 Resolver.ComplainNoMatchesFound();
9996 }
9997 else if (NumMatches > 1 && Complain)
9998 Resolver.ComplainMultipleMatchesFound();
9999 else if (NumMatches == 1) {
10000 Fn = Resolver.getMatchingFunctionDecl();
10001 assert(Fn);
10002 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010003 if (Complain) {
10004 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10005 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10006 else
10007 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10008 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010009 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010010
10011 if (pHadMultipleCandidates)
10012 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010013 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010014}
10015
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010016/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010017/// resolve that overloaded function expression down to a single function.
10018///
10019/// This routine can only resolve template-ids that refer to a single function
10020/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010021/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010022/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010023///
10024/// If no template-ids are found, no diagnostics are emitted and NULL is
10025/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010026FunctionDecl *
10027Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10028 bool Complain,
10029 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010030 // C++ [over.over]p1:
10031 // [...] [Note: any redundant set of parentheses surrounding the
10032 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010033 // C++ [over.over]p1:
10034 // [...] The overloaded function name can be preceded by the &
10035 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010036
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010037 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010038 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010039 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010040
10041 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010042 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010043 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010044
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010045 // Look through all of the overloaded functions, searching for one
10046 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010047 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010048 for (UnresolvedSetIterator I = ovl->decls_begin(),
10049 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010050 // C++0x [temp.arg.explicit]p3:
10051 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010052 // where deduction is not done, if a template argument list is
10053 // specified and it, along with any default template arguments,
10054 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010055 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010056 FunctionTemplateDecl *FunctionTemplate
10057 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010058
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010059 // C++ [over.over]p2:
10060 // If the name is a function template, template argument deduction is
10061 // done (14.8.2.2), and if the argument deduction succeeds, the
10062 // resulting template argument list is used to generate a single
10063 // function template specialization, which is added to the set of
10064 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010065 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010066 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010067 if (TemplateDeductionResult Result
10068 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010069 Specialization, Info,
10070 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010071 // Make a note of the failed deduction for diagnostics.
10072 // TODO: Actually use the failed-deduction info?
10073 FailedCandidates.addCandidate()
10074 .set(FunctionTemplate->getTemplatedDecl(),
10075 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010076 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010077 }
10078
John McCall0009fcc2011-04-26 20:42:42 +000010079 assert(Specialization && "no specialization and no error?");
10080
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010081 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010082 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010083 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010084 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10085 << ovl->getName();
10086 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010087 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010088 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010089 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010090
John McCall0009fcc2011-04-26 20:42:42 +000010091 Matched = Specialization;
10092 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010094
Richard Smith2a7d4812013-05-04 07:00:32 +000010095 if (Matched && getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +000010096 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010097 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010098 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010099
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010100 return Matched;
10101}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010102
Douglas Gregor1beec452011-03-12 01:48:56 +000010103
10104
10105
John McCall50a2c2c2011-10-11 23:14:30 +000010106// Resolve and fix an overloaded expression that can be resolved
10107// because it identifies a single function template specialization.
10108//
Douglas Gregor1beec452011-03-12 01:48:56 +000010109// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010110//
10111// Return true if it was logically possible to so resolve the
10112// expression, regardless of whether or not it succeeded. Always
10113// returns true if 'complain' is set.
10114bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10115 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10116 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010117 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010118 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010119 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010120
John McCall50a2c2c2011-10-11 23:14:30 +000010121 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010122
John McCall0009fcc2011-04-26 20:42:42 +000010123 DeclAccessPair found;
10124 ExprResult SingleFunctionExpression;
10125 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10126 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010127 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010128 SrcExpr = ExprError();
10129 return true;
10130 }
John McCall0009fcc2011-04-26 20:42:42 +000010131
10132 // It is only correct to resolve to an instance method if we're
10133 // resolving a form that's permitted to be a pointer to member.
10134 // Otherwise we'll end up making a bound member expression, which
10135 // is illegal in all the contexts we resolve like this.
10136 if (!ovl.HasFormOfMemberPointer &&
10137 isa<CXXMethodDecl>(fn) &&
10138 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010139 if (!complain) return false;
10140
10141 Diag(ovl.Expression->getExprLoc(),
10142 diag::err_bound_member_function)
10143 << 0 << ovl.Expression->getSourceRange();
10144
10145 // TODO: I believe we only end up here if there's a mix of
10146 // static and non-static candidates (otherwise the expression
10147 // would have 'bound member' type, not 'overload' type).
10148 // Ideally we would note which candidate was chosen and why
10149 // the static candidates were rejected.
10150 SrcExpr = ExprError();
10151 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010152 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010153
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010154 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010155 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010156 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010157
10158 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010159 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010160 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010161 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010162 if (SingleFunctionExpression.isInvalid()) {
10163 SrcExpr = ExprError();
10164 return true;
10165 }
10166 }
John McCall0009fcc2011-04-26 20:42:42 +000010167 }
10168
10169 if (!SingleFunctionExpression.isUsable()) {
10170 if (complain) {
10171 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10172 << ovl.Expression->getName()
10173 << DestTypeForComplaining
10174 << OpRangeForComplaining
10175 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010176 NoteAllOverloadCandidates(SrcExpr.get());
10177
10178 SrcExpr = ExprError();
10179 return true;
10180 }
10181
10182 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010183 }
10184
John McCall50a2c2c2011-10-11 23:14:30 +000010185 SrcExpr = SingleFunctionExpression;
10186 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010187}
10188
Douglas Gregorcabea402009-09-22 15:41:20 +000010189/// \brief Add a single candidate to the overload set.
10190static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010191 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010192 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010193 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010194 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010195 bool PartialOverloading,
10196 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010197 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010198 if (isa<UsingShadowDecl>(Callee))
10199 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10200
Douglas Gregorcabea402009-09-22 15:41:20 +000010201 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010202 if (ExplicitTemplateArgs) {
10203 assert(!KnownValid && "Explicit template arguments?");
10204 return;
10205 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010206 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10207 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010208 return;
John McCalld14a8642009-11-21 08:51:07 +000010209 }
10210
10211 if (FunctionTemplateDecl *FuncTemplate
10212 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010213 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010214 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010215 return;
10216 }
10217
Richard Smith95ce4f62011-06-26 22:19:54 +000010218 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010219}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010220
Douglas Gregorcabea402009-09-22 15:41:20 +000010221/// \brief Add the overload candidates named by callee and/or found by argument
10222/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010223void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010224 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010225 OverloadCandidateSet &CandidateSet,
10226 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010227
10228#ifndef NDEBUG
10229 // Verify that ArgumentDependentLookup is consistent with the rules
10230 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010231 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010232 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10233 // and let Y be the lookup set produced by argument dependent
10234 // lookup (defined as follows). If X contains
10235 //
10236 // -- a declaration of a class member, or
10237 //
10238 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010239 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010240 //
10241 // -- a declaration that is neither a function or a function
10242 // template
10243 //
10244 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010245
John McCall57500772009-12-16 12:17:52 +000010246 if (ULE->requiresADL()) {
10247 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10248 E = ULE->decls_end(); I != E; ++I) {
10249 assert(!(*I)->getDeclContext()->isRecord());
10250 assert(isa<UsingShadowDecl>(*I) ||
10251 !(*I)->getDeclContext()->isFunctionOrMethod());
10252 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010253 }
10254 }
10255#endif
10256
John McCall57500772009-12-16 12:17:52 +000010257 // It would be nice to avoid this copy.
10258 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010259 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010260 if (ULE->hasExplicitTemplateArgs()) {
10261 ULE->copyTemplateArgumentsInto(TABuffer);
10262 ExplicitTemplateArgs = &TABuffer;
10263 }
10264
10265 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10266 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010267 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10268 CandidateSet, PartialOverloading,
10269 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010270
John McCall57500772009-12-16 12:17:52 +000010271 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010272 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010273 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010274 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010275}
John McCalld681c392009-12-16 08:11:27 +000010276
Richard Smith0603bbb2013-06-12 22:56:54 +000010277/// Determine whether a declaration with the specified name could be moved into
10278/// a different namespace.
10279static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10280 switch (Name.getCXXOverloadedOperator()) {
10281 case OO_New: case OO_Array_New:
10282 case OO_Delete: case OO_Array_Delete:
10283 return false;
10284
10285 default:
10286 return true;
10287 }
10288}
10289
Richard Smith998a5912011-06-05 22:42:48 +000010290/// Attempt to recover from an ill-formed use of a non-dependent name in a
10291/// template, where the non-dependent name was declared after the template
10292/// was defined. This is common in code written for a compilers which do not
10293/// correctly implement two-stage name lookup.
10294///
10295/// Returns true if a viable candidate was found and a diagnostic was issued.
10296static bool
10297DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10298 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010299 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010300 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010301 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010302 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10303 return false;
10304
10305 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010306 if (DC->isTransparentContext())
10307 continue;
10308
Richard Smith998a5912011-06-05 22:42:48 +000010309 SemaRef.LookupQualifiedName(R, DC);
10310
10311 if (!R.empty()) {
10312 R.suppressDiagnostics();
10313
10314 if (isa<CXXRecordDecl>(DC)) {
10315 // Don't diagnose names we find in classes; we get much better
10316 // diagnostics for these from DiagnoseEmptyLookup.
10317 R.clear();
10318 return false;
10319 }
10320
Richard Smith100b24a2014-04-17 01:52:14 +000010321 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010322 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10323 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010324 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010325 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010326
10327 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010328 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010329 // No viable functions. Don't bother the user with notes for functions
10330 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010331 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010332 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010333 }
Richard Smith998a5912011-06-05 22:42:48 +000010334
10335 // Find the namespaces where ADL would have looked, and suggest
10336 // declaring the function there instead.
10337 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10338 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010339 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010340 AssociatedNamespaces,
10341 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010342 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010343 if (canBeDeclaredInNamespace(R.getLookupName())) {
10344 DeclContext *Std = SemaRef.getStdNamespace();
10345 for (Sema::AssociatedNamespaceSet::iterator
10346 it = AssociatedNamespaces.begin(),
10347 end = AssociatedNamespaces.end(); it != end; ++it) {
10348 // Never suggest declaring a function within namespace 'std'.
10349 if (Std && Std->Encloses(*it))
10350 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010351
Richard Smith0603bbb2013-06-12 22:56:54 +000010352 // Never suggest declaring a function within a namespace with a
10353 // reserved name, like __gnu_cxx.
10354 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10355 if (NS &&
10356 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10357 continue;
10358
10359 SuggestedNamespaces.insert(*it);
10360 }
Richard Smith998a5912011-06-05 22:42:48 +000010361 }
10362
10363 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10364 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010365 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010366 SemaRef.Diag(Best->Function->getLocation(),
10367 diag::note_not_found_by_two_phase_lookup)
10368 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010369 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010370 SemaRef.Diag(Best->Function->getLocation(),
10371 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010372 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010373 } else {
10374 // FIXME: It would be useful to list the associated namespaces here,
10375 // but the diagnostics infrastructure doesn't provide a way to produce
10376 // a localized representation of a list of items.
10377 SemaRef.Diag(Best->Function->getLocation(),
10378 diag::note_not_found_by_two_phase_lookup)
10379 << R.getLookupName() << 2;
10380 }
10381
10382 // Try to recover by calling this function.
10383 return true;
10384 }
10385
10386 R.clear();
10387 }
10388
10389 return false;
10390}
10391
10392/// Attempt to recover from ill-formed use of a non-dependent operator in a
10393/// template, where the non-dependent operator was declared after the template
10394/// was defined.
10395///
10396/// Returns true if a viable candidate was found and a diagnostic was issued.
10397static bool
10398DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10399 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010400 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010401 DeclarationName OpName =
10402 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10403 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10404 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010405 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010406 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010407}
10408
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010409namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010410class BuildRecoveryCallExprRAII {
10411 Sema &SemaRef;
10412public:
10413 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10414 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10415 SemaRef.IsBuildingRecoveryCallExpr = true;
10416 }
10417
10418 ~BuildRecoveryCallExprRAII() {
10419 SemaRef.IsBuildingRecoveryCallExpr = false;
10420 }
10421};
10422
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010423}
10424
John McCalld681c392009-12-16 08:11:27 +000010425/// Attempts to recover from a call where no functions were found.
10426///
10427/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010428static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010429BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010430 UnresolvedLookupExpr *ULE,
10431 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010432 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010433 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010434 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010435 // Do not try to recover if it is already building a recovery call.
10436 // This stops infinite loops for template instantiations like
10437 //
10438 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10439 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10440 //
10441 if (SemaRef.IsBuildingRecoveryCallExpr)
10442 return ExprError();
10443 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010444
10445 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010446 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010447 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010448
John McCall57500772009-12-16 12:17:52 +000010449 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010450 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010451 if (ULE->hasExplicitTemplateArgs()) {
10452 ULE->copyTemplateArgumentsInto(TABuffer);
10453 ExplicitTemplateArgs = &TABuffer;
10454 }
10455
John McCalld681c392009-12-16 08:11:27 +000010456 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10457 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010458 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010459 ExplicitTemplateArgs != nullptr,
Kaelyn Takatafb271f02014-04-04 22:16:30 +000010460 dyn_cast<MemberExpr>(Fn));
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010461 NoTypoCorrectionCCC RejectAll;
10462 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10463 (CorrectionCandidateCallback*)&Validator :
10464 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010465 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010466 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010467 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010468 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010469 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010470 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010471 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010472
John McCall57500772009-12-16 12:17:52 +000010473 assert(!R.empty() && "lookup results empty despite recovery");
10474
10475 // Build an implicit member call if appropriate. Just drop the
10476 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010477 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010478 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010479 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10480 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010481 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010482 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010483 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010484 else
10485 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10486
10487 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010488 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010489
10490 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010491 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010492 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010493 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010494 MultiExprArg(Args.data(), Args.size()),
10495 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010496}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010497
Sam Panzer0f384432012-08-21 00:52:01 +000010498/// \brief Constructs and populates an OverloadedCandidateSet from
10499/// the given function.
10500/// \returns true when an the ExprResult output parameter has been set.
10501bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10502 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010503 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010504 SourceLocation RParenLoc,
10505 OverloadCandidateSet *CandidateSet,
10506 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010507#ifndef NDEBUG
10508 if (ULE->requiresADL()) {
10509 // To do ADL, we must have found an unqualified name.
10510 assert(!ULE->getQualifier() && "qualified name with ADL");
10511
10512 // We don't perform ADL for implicit declarations of builtins.
10513 // Verify that this was correctly set up.
10514 FunctionDecl *F;
10515 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10516 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10517 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010518 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010519
John McCall57500772009-12-16 12:17:52 +000010520 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010521 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010522 }
John McCall57500772009-12-16 12:17:52 +000010523#endif
10524
John McCall4124c492011-10-17 18:40:02 +000010525 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010526 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010527 *Result = ExprError();
10528 return true;
10529 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010530
John McCall57500772009-12-16 12:17:52 +000010531 // Add the functions denoted by the callee to the set of candidate
10532 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010533 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010534
10535 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010536 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10537 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010538 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010539 // In Microsoft mode, if we are inside a template class member function then
10540 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010541 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010542 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010543 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010544 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010545 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010546 Context.DependentTy, VK_RValue,
10547 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010548 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010549 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010550 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010551 }
Sam Panzer0f384432012-08-21 00:52:01 +000010552 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010553 }
John McCalld681c392009-12-16 08:11:27 +000010554
John McCall4124c492011-10-17 18:40:02 +000010555 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010556 return false;
10557}
John McCall4124c492011-10-17 18:40:02 +000010558
Sam Panzer0f384432012-08-21 00:52:01 +000010559/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10560/// the completed call expression. If overload resolution fails, emits
10561/// diagnostics and returns ExprError()
10562static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10563 UnresolvedLookupExpr *ULE,
10564 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010565 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010566 SourceLocation RParenLoc,
10567 Expr *ExecConfig,
10568 OverloadCandidateSet *CandidateSet,
10569 OverloadCandidateSet::iterator *Best,
10570 OverloadingResult OverloadResult,
10571 bool AllowTypoCorrection) {
10572 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010573 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010574 RParenLoc, /*EmptyLookup=*/true,
10575 AllowTypoCorrection);
10576
10577 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010578 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010579 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010580 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010581 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10582 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010583 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010584 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10585 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010586 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010587
Richard Smith998a5912011-06-05 22:42:48 +000010588 case OR_No_Viable_Function: {
10589 // Try to recover by looking for viable functions which the user might
10590 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010591 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010592 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010593 /*EmptyLookup=*/false,
10594 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010595 if (!Recovery.isInvalid())
10596 return Recovery;
10597
Sam Panzer0f384432012-08-21 00:52:01 +000010598 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010599 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010600 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010601 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010602 break;
Richard Smith998a5912011-06-05 22:42:48 +000010603 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010604
10605 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010606 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010607 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010608 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010609 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010610
Sam Panzer0f384432012-08-21 00:52:01 +000010611 case OR_Deleted: {
10612 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10613 << (*Best)->Function->isDeleted()
10614 << ULE->getName()
10615 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10616 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010617 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010618
Sam Panzer0f384432012-08-21 00:52:01 +000010619 // We emitted an error for the unvailable/deleted function call but keep
10620 // the call in the AST.
10621 FunctionDecl *FDecl = (*Best)->Function;
10622 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010623 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10624 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010625 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010626 }
10627
Douglas Gregorb412e172010-07-25 18:17:45 +000010628 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010629 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010630}
10631
Sam Panzer0f384432012-08-21 00:52:01 +000010632/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10633/// (which eventually refers to the declaration Func) and the call
10634/// arguments Args/NumArgs, attempt to resolve the function call down
10635/// to a specific function. If overload resolution succeeds, returns
10636/// the call expression produced by overload resolution.
10637/// Otherwise, emits diagnostics and returns ExprError.
10638ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10639 UnresolvedLookupExpr *ULE,
10640 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010641 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010642 SourceLocation RParenLoc,
10643 Expr *ExecConfig,
10644 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010645 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10646 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010647 ExprResult result;
10648
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010649 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10650 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010651 return result;
10652
10653 OverloadCandidateSet::iterator Best;
10654 OverloadingResult OverloadResult =
10655 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10656
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010657 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010658 RParenLoc, ExecConfig, &CandidateSet,
10659 &Best, OverloadResult,
10660 AllowTypoCorrection);
10661}
10662
John McCall4c4c1df2010-01-26 03:27:55 +000010663static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010664 return Functions.size() > 1 ||
10665 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10666}
10667
Douglas Gregor084d8552009-03-13 23:49:33 +000010668/// \brief Create a unary operation that may resolve to an overloaded
10669/// operator.
10670///
10671/// \param OpLoc The location of the operator itself (e.g., '*').
10672///
10673/// \param OpcIn The UnaryOperator::Opcode that describes this
10674/// operator.
10675///
James Dennett18348b62012-06-22 08:52:37 +000010676/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010677/// considered by overload resolution. The caller needs to build this
10678/// set based on the context using, e.g.,
10679/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10680/// set should not contain any member functions; those will be added
10681/// by CreateOverloadedUnaryOp().
10682///
James Dennett91738ff2012-06-22 10:32:46 +000010683/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010684ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010685Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10686 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010687 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010688 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010689
10690 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10691 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10692 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010693 // TODO: provide better source location info.
10694 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010695
John McCall4124c492011-10-17 18:40:02 +000010696 if (checkPlaceholderForOverload(*this, Input))
10697 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010698
Craig Topperc3ec1492014-05-26 06:22:03 +000010699 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010700 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010701
Douglas Gregor084d8552009-03-13 23:49:33 +000010702 // For post-increment and post-decrement, add the implicit '0' as
10703 // the second argument, so that we know this is a post-increment or
10704 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010705 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010706 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010707 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10708 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010709 NumArgs = 2;
10710 }
10711
Richard Smithe54c3072013-05-05 15:51:06 +000010712 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10713
Douglas Gregor084d8552009-03-13 23:49:33 +000010714 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010715 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010716 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10717 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010718
Craig Topperc3ec1492014-05-26 06:22:03 +000010719 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010720 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010721 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010722 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010723 /*ADL*/ true, IsOverloaded(Fns),
10724 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010725 return new (Context)
10726 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10727 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010728 }
10729
10730 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010731 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010732
10733 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010734 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010735
10736 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010737 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010738
John McCall4c4c1df2010-01-26 03:27:55 +000010739 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010740 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010741 /*ExplicitTemplateArgs*/nullptr,
10742 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010743
Douglas Gregor084d8552009-03-13 23:49:33 +000010744 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010745 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010746
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10748
Douglas Gregor084d8552009-03-13 23:49:33 +000010749 // Perform overload resolution.
10750 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010751 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010752 case OR_Success: {
10753 // We found a built-in operator or an overloaded operator.
10754 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010755
Douglas Gregor084d8552009-03-13 23:49:33 +000010756 if (FnDecl) {
10757 // We matched an overloaded operator. Build a call to that
10758 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010759
Douglas Gregor084d8552009-03-13 23:49:33 +000010760 // Convert the arguments.
10761 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010762 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010763
John Wiegley01296292011-04-08 18:41:53 +000010764 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010765 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010766 Best->FoundDecl, Method);
10767 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010768 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010769 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010770 } else {
10771 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010772 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010773 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010774 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010775 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010776 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010777 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010778 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010779 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010780 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010781 }
10782
Douglas Gregor084d8552009-03-13 23:49:33 +000010783 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010784 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010785 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010786 if (FnExpr.isInvalid())
10787 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010788
Richard Smithc1564702013-11-15 02:58:23 +000010789 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010790 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010791 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10792 ResultTy = ResultTy.getNonLValueExprType(Context);
10793
Eli Friedman030eee42009-11-18 03:58:17 +000010794 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010795 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010796 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010797 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010798
Alp Toker314cc812014-01-25 16:55:45 +000010799 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010800 return ExprError();
10801
John McCallb268a282010-08-23 23:25:46 +000010802 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010803 } else {
10804 // We matched a built-in operator. Convert the arguments, then
10805 // break out so that we will build the appropriate built-in
10806 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010807 ExprResult InputRes =
10808 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10809 Best->Conversions[0], AA_Passing);
10810 if (InputRes.isInvalid())
10811 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010812 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010813 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010814 }
John Wiegley01296292011-04-08 18:41:53 +000010815 }
10816
10817 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010818 // This is an erroneous use of an operator which can be overloaded by
10819 // a non-member function. Check for non-member operators which were
10820 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010821 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010822 // FIXME: Recover by calling the found function.
10823 return ExprError();
10824
John Wiegley01296292011-04-08 18:41:53 +000010825 // No viable function; fall through to handling this as a
10826 // built-in operator, which will produce an error message for us.
10827 break;
10828
10829 case OR_Ambiguous:
10830 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10831 << UnaryOperator::getOpcodeStr(Opc)
10832 << Input->getType()
10833 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010834 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010835 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10836 return ExprError();
10837
10838 case OR_Deleted:
10839 Diag(OpLoc, diag::err_ovl_deleted_oper)
10840 << Best->Function->isDeleted()
10841 << UnaryOperator::getOpcodeStr(Opc)
10842 << getDeletedOrUnavailableSuffix(Best->Function)
10843 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010844 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010845 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010846 return ExprError();
10847 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010848
10849 // Either we found no viable overloaded operator or we matched a
10850 // built-in operator. In either case, fall through to trying to
10851 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010852 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010853}
10854
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010855/// \brief Create a binary operation that may resolve to an overloaded
10856/// operator.
10857///
10858/// \param OpLoc The location of the operator itself (e.g., '+').
10859///
10860/// \param OpcIn The BinaryOperator::Opcode that describes this
10861/// operator.
10862///
James Dennett18348b62012-06-22 08:52:37 +000010863/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010864/// considered by overload resolution. The caller needs to build this
10865/// set based on the context using, e.g.,
10866/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10867/// set should not contain any member functions; those will be added
10868/// by CreateOverloadedBinOp().
10869///
10870/// \param LHS Left-hand argument.
10871/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010872ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010873Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010874 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010875 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010876 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010877 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000010878 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010879
10880 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10881 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10882 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10883
10884 // If either side is type-dependent, create an appropriate dependent
10885 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010886 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010887 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010888 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010889 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010890 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010891 return new (Context) BinaryOperator(
10892 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
10893 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010895 return new (Context) CompoundAssignOperator(
10896 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
10897 Context.DependentTy, Context.DependentTy, OpLoc,
10898 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000010899 }
John McCall4c4c1df2010-01-26 03:27:55 +000010900
10901 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000010902 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010903 // TODO: provide better source location info in DNLoc component.
10904 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010905 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010906 = UnresolvedLookupExpr::Create(Context, NamingClass,
10907 NestedNameSpecifierLoc(), OpNameInfo,
10908 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010909 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010910 return new (Context)
10911 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
10912 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010913 }
10914
John McCall4124c492011-10-17 18:40:02 +000010915 // Always do placeholder-like conversions on the RHS.
10916 if (checkPlaceholderForOverload(*this, Args[1]))
10917 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010918
John McCall526ab472011-10-25 17:37:35 +000010919 // Do placeholder-like conversion on the LHS; note that we should
10920 // not get here with a PseudoObject LHS.
10921 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010922 if (checkPlaceholderForOverload(*this, Args[0]))
10923 return ExprError();
10924
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010925 // If this is the assignment operator, we only perform overload resolution
10926 // if the left-hand side is a class or enumeration type. This is actually
10927 // a hack. The standard requires that we do overload resolution between the
10928 // various built-in candidates, but as DR507 points out, this can lead to
10929 // problems. So we do it this way, which pretty much follows what GCC does.
10930 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010931 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010932 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010933
John McCalle26a8722010-12-04 08:14:53 +000010934 // If this is the .* operator, which is not overloadable, just
10935 // create a built-in binary operator.
10936 if (Opc == BO_PtrMemD)
10937 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10938
Douglas Gregor084d8552009-03-13 23:49:33 +000010939 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010940 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010941
10942 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010943 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010944
10945 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010946 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010947
John McCall4c4c1df2010-01-26 03:27:55 +000010948 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010949 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
Craig Topperc3ec1492014-05-26 06:22:03 +000010950 /*ExplicitTemplateArgs*/ nullptr,
John McCall4c4c1df2010-01-26 03:27:55 +000010951 CandidateSet);
10952
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010953 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010954 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010955
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010956 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10957
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010958 // Perform overload resolution.
10959 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010960 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010961 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010962 // We found a built-in operator or an overloaded operator.
10963 FunctionDecl *FnDecl = Best->Function;
10964
10965 if (FnDecl) {
10966 // We matched an overloaded operator. Build a call to that
10967 // operator.
10968
10969 // Convert the arguments.
10970 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010971 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010972 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010973
Chandler Carruth8e543b32010-12-12 08:17:55 +000010974 ExprResult Arg1 =
10975 PerformCopyInitialization(
10976 InitializedEntity::InitializeParameter(Context,
10977 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010978 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010979 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010980 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010981
John Wiegley01296292011-04-08 18:41:53 +000010982 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000010983 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010984 Best->FoundDecl, Method);
10985 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010986 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010987 Args[0] = Arg0.getAs<Expr>();
10988 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010989 } else {
10990 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010991 ExprResult Arg0 = PerformCopyInitialization(
10992 InitializedEntity::InitializeParameter(Context,
10993 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010994 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010995 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010996 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010997
Chandler Carruth8e543b32010-12-12 08:17:55 +000010998 ExprResult Arg1 =
10999 PerformCopyInitialization(
11000 InitializedEntity::InitializeParameter(Context,
11001 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011002 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011003 if (Arg1.isInvalid())
11004 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011005 Args[0] = LHS = Arg0.getAs<Expr>();
11006 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011007 }
11008
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011009 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011010 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011011 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011012 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011013 if (FnExpr.isInvalid())
11014 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011015
Richard Smithc1564702013-11-15 02:58:23 +000011016 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011017 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011018 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11019 ResultTy = ResultTy.getNonLValueExprType(Context);
11020
John McCallb268a282010-08-23 23:25:46 +000011021 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011022 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011023 Args, ResultTy, VK, OpLoc,
11024 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011025
Alp Toker314cc812014-01-25 16:55:45 +000011026 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011027 FnDecl))
11028 return ExprError();
11029
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011030 ArrayRef<const Expr *> ArgsArray(Args, 2);
11031 // Cut off the implicit 'this'.
11032 if (isa<CXXMethodDecl>(FnDecl))
11033 ArgsArray = ArgsArray.slice(1);
11034 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11035 TheCall->getSourceRange(), VariadicDoesNotApply);
11036
John McCallb268a282010-08-23 23:25:46 +000011037 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011038 } else {
11039 // We matched a built-in operator. Convert the arguments, then
11040 // break out so that we will build the appropriate built-in
11041 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011042 ExprResult ArgsRes0 =
11043 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11044 Best->Conversions[0], AA_Passing);
11045 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011046 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011047 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011048
John Wiegley01296292011-04-08 18:41:53 +000011049 ExprResult ArgsRes1 =
11050 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11051 Best->Conversions[1], AA_Passing);
11052 if (ArgsRes1.isInvalid())
11053 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011054 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011055 break;
11056 }
11057 }
11058
Douglas Gregor66950a32009-09-30 21:46:01 +000011059 case OR_No_Viable_Function: {
11060 // C++ [over.match.oper]p9:
11061 // If the operator is the operator , [...] and there are no
11062 // viable functions, then the operator is assumed to be the
11063 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011064 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011065 break;
11066
Chandler Carruth8e543b32010-12-12 08:17:55 +000011067 // For class as left operand for assignment or compound assigment
11068 // operator do not fall through to handling in built-in, but report that
11069 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011070 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011071 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011072 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011073 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11074 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011075 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011076 if (Args[0]->getType()->isIncompleteType()) {
11077 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11078 << Args[0]->getType()
11079 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11080 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011081 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011082 // This is an erroneous use of an operator which can be overloaded by
11083 // a non-member function. Check for non-member operators which were
11084 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011085 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011086 // FIXME: Recover by calling the found function.
11087 return ExprError();
11088
Douglas Gregor66950a32009-09-30 21:46:01 +000011089 // No viable function; try to create a built-in operation, which will
11090 // produce an error. Then, show the non-viable candidates.
11091 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011093 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011094 "C++ binary operator overloading is missing candidates!");
11095 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011096 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011097 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011098 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011099 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011100
11101 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011102 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011103 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011104 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011105 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011106 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011107 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011108 return ExprError();
11109
11110 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011111 if (isImplicitlyDeleted(Best->Function)) {
11112 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11113 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011114 << Context.getRecordType(Method->getParent())
11115 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011116
Richard Smithde1a4872012-12-28 12:23:24 +000011117 // The user probably meant to call this special member. Just
11118 // explain why it's deleted.
11119 NoteDeletedFunction(Method);
11120 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011121 } else {
11122 Diag(OpLoc, diag::err_ovl_deleted_oper)
11123 << Best->Function->isDeleted()
11124 << BinaryOperator::getOpcodeStr(Opc)
11125 << getDeletedOrUnavailableSuffix(Best->Function)
11126 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11127 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011129 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011130 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011131 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011132
Douglas Gregor66950a32009-09-30 21:46:01 +000011133 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011134 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011135}
11136
John McCalldadc5752010-08-24 06:29:42 +000011137ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011138Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11139 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011140 Expr *Base, Expr *Idx) {
11141 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011142 DeclarationName OpName =
11143 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11144
11145 // If either side is type-dependent, create an appropriate dependent
11146 // expression.
11147 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11148
Craig Topperc3ec1492014-05-26 06:22:03 +000011149 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011150 // CHECKME: no 'operator' keyword?
11151 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11152 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011153 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011154 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011155 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011156 /*ADL*/ true, /*Overloaded*/ false,
11157 UnresolvedSetIterator(),
11158 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011159 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011160
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011161 return new (Context)
11162 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11163 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011164 }
11165
John McCall4124c492011-10-17 18:40:02 +000011166 // Handle placeholders on both operands.
11167 if (checkPlaceholderForOverload(*this, Args[0]))
11168 return ExprError();
11169 if (checkPlaceholderForOverload(*this, Args[1]))
11170 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011171
Sebastian Redladba46e2009-10-29 20:17:01 +000011172 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011173 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011174
11175 // Subscript can only be overloaded as a member function.
11176
11177 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011178 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011179
11180 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011181 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011182
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011183 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11184
Sebastian Redladba46e2009-10-29 20:17:01 +000011185 // Perform overload resolution.
11186 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011187 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011188 case OR_Success: {
11189 // We found a built-in operator or an overloaded operator.
11190 FunctionDecl *FnDecl = Best->Function;
11191
11192 if (FnDecl) {
11193 // We matched an overloaded operator. Build a call to that
11194 // operator.
11195
John McCalla0296f72010-03-19 07:35:19 +000011196 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011197
Sebastian Redladba46e2009-10-29 20:17:01 +000011198 // Convert the arguments.
11199 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011200 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011201 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011202 Best->FoundDecl, Method);
11203 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011204 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011205 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011206
Anders Carlssona68e51e2010-01-29 18:37:50 +000011207 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011208 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011209 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011210 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011211 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011212 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011213 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011214 if (InputInit.isInvalid())
11215 return ExprError();
11216
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011217 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011218
Sebastian Redladba46e2009-10-29 20:17:01 +000011219 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011220 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11221 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011222 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011223 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011224 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011225 OpLocInfo.getLoc(),
11226 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011227 if (FnExpr.isInvalid())
11228 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011229
Richard Smithc1564702013-11-15 02:58:23 +000011230 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011231 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011232 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11233 ResultTy = ResultTy.getNonLValueExprType(Context);
11234
John McCallb268a282010-08-23 23:25:46 +000011235 CXXOperatorCallExpr *TheCall =
11236 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011237 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011238 ResultTy, VK, RLoc,
11239 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011240
Alp Toker314cc812014-01-25 16:55:45 +000011241 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011242 return ExprError();
11243
John McCallb268a282010-08-23 23:25:46 +000011244 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011245 } else {
11246 // We matched a built-in operator. Convert the arguments, then
11247 // break out so that we will build the appropriate built-in
11248 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011249 ExprResult ArgsRes0 =
11250 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11251 Best->Conversions[0], AA_Passing);
11252 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011253 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011254 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011255
11256 ExprResult ArgsRes1 =
11257 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11258 Best->Conversions[1], AA_Passing);
11259 if (ArgsRes1.isInvalid())
11260 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011261 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011262
11263 break;
11264 }
11265 }
11266
11267 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011268 if (CandidateSet.empty())
11269 Diag(LLoc, diag::err_ovl_no_oper)
11270 << Args[0]->getType() << /*subscript*/ 0
11271 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11272 else
11273 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11274 << Args[0]->getType()
11275 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011277 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011278 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011279 }
11280
11281 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011282 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011283 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011284 << Args[0]->getType() << Args[1]->getType()
11285 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011286 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011287 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011288 return ExprError();
11289
11290 case OR_Deleted:
11291 Diag(LLoc, diag::err_ovl_deleted_oper)
11292 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011293 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011294 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011295 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011296 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011297 return ExprError();
11298 }
11299
11300 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011301 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011302}
11303
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011304/// BuildCallToMemberFunction - Build a call to a member
11305/// function. MemExpr is the expression that refers to the member
11306/// function (and includes the object parameter), Args/NumArgs are the
11307/// arguments to the function call (not including the object
11308/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011309/// expression refers to a non-static member function or an overloaded
11310/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011311ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011312Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011313 SourceLocation LParenLoc,
11314 MultiExprArg Args,
11315 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011316 assert(MemExprE->getType() == Context.BoundMemberTy ||
11317 MemExprE->getType() == Context.OverloadTy);
11318
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011319 // Dig out the member expression. This holds both the object
11320 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011321 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011322
John McCall0009fcc2011-04-26 20:42:42 +000011323 // Determine whether this is a call to a pointer-to-member function.
11324 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11325 assert(op->getType() == Context.BoundMemberTy);
11326 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11327
11328 QualType fnType =
11329 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11330
11331 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11332 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011333 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011334
11335 // Check that the object type isn't more qualified than the
11336 // member function we're calling.
11337 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11338
11339 QualType objectType = op->getLHS()->getType();
11340 if (op->getOpcode() == BO_PtrMemI)
11341 objectType = objectType->castAs<PointerType>()->getPointeeType();
11342 Qualifiers objectQuals = objectType.getQualifiers();
11343
11344 Qualifiers difference = objectQuals - funcQuals;
11345 difference.removeObjCGCAttr();
11346 difference.removeAddressSpace();
11347 if (difference) {
11348 std::string qualsString = difference.getAsString();
11349 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11350 << fnType.getUnqualifiedType()
11351 << qualsString
11352 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11353 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011354
John McCall0009fcc2011-04-26 20:42:42 +000011355 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011356 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011357 resultType, valueKind, RParenLoc);
11358
Alp Toker314cc812014-01-25 16:55:45 +000011359 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011360 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011361 return ExprError();
11362
Craig Topperc3ec1492014-05-26 06:22:03 +000011363 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011364 return ExprError();
11365
Richard Trieu9be9c682013-06-22 02:30:38 +000011366 if (CheckOtherCall(call, proto))
11367 return ExprError();
11368
John McCall0009fcc2011-04-26 20:42:42 +000011369 return MaybeBindToTemporary(call);
11370 }
11371
John McCall4124c492011-10-17 18:40:02 +000011372 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011373 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011374 return ExprError();
11375
John McCall10eae182009-11-30 22:42:35 +000011376 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011377 CXXMethodDecl *Method = nullptr;
11378 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11379 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011380 if (isa<MemberExpr>(NakedMemExpr)) {
11381 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011382 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011383 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011384 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011385 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011386 } else {
11387 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011388 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011389
John McCall6e9f8f62009-12-03 04:06:58 +000011390 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011391 Expr::Classification ObjectClassification
11392 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11393 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011394
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011395 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011396 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11397 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011398
John McCall2d74de92009-12-01 22:10:20 +000011399 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011400 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011401 if (UnresExpr->hasExplicitTemplateArgs()) {
11402 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11403 TemplateArgs = &TemplateArgsBuffer;
11404 }
11405
John McCall10eae182009-11-30 22:42:35 +000011406 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11407 E = UnresExpr->decls_end(); I != E; ++I) {
11408
John McCall6e9f8f62009-12-03 04:06:58 +000011409 NamedDecl *Func = *I;
11410 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11411 if (isa<UsingShadowDecl>(Func))
11412 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11413
Douglas Gregor02824322011-01-26 19:30:28 +000011414
Francois Pichet64225792011-01-18 05:04:39 +000011415 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011416 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011417 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011418 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011419 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011420 // If explicit template arguments were provided, we can't call a
11421 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011422 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011423 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011424
John McCalla0296f72010-03-19 07:35:19 +000011425 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011426 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011427 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011428 } else {
John McCall10eae182009-11-30 22:42:35 +000011429 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011430 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011431 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011432 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011433 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011434 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011435 }
Mike Stump11289f42009-09-09 15:08:12 +000011436
John McCall10eae182009-11-30 22:42:35 +000011437 DeclarationName DeclName = UnresExpr->getMemberName();
11438
John McCall4124c492011-10-17 18:40:02 +000011439 UnbridgedCasts.restore();
11440
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011441 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011442 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011443 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011444 case OR_Success:
11445 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011446 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011447 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011448 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11449 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011450 // If FoundDecl is different from Method (such as if one is a template
11451 // and the other a specialization), make sure DiagnoseUseOfDecl is
11452 // called on both.
11453 // FIXME: This would be more comprehensively addressed by modifying
11454 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11455 // being used.
11456 if (Method != FoundDecl.getDecl() &&
11457 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11458 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011459 break;
11460
11461 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011462 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011463 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011464 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011465 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011466 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011467 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011468
11469 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011470 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011471 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011472 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011473 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011474 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011475
11476 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011477 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011478 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011479 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011480 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011481 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011483 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011484 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011485 }
11486
John McCall16df1e52010-03-30 21:47:33 +000011487 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011488
John McCall2d74de92009-12-01 22:10:20 +000011489 // If overload resolution picked a static member, build a
11490 // non-member call based on that function.
11491 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011492 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11493 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011494 }
11495
John McCall10eae182009-11-30 22:42:35 +000011496 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011497 }
11498
Alp Toker314cc812014-01-25 16:55:45 +000011499 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011500 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11501 ResultType = ResultType.getNonLValueExprType(Context);
11502
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011503 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011504 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011505 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011506 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011507
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011508 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011509 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011510 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011511 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011512
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011513 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011514 // We only need to do this if there was actually an overload; otherwise
11515 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011516 if (!Method->isStatic()) {
11517 ExprResult ObjectArg =
11518 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11519 FoundDecl, Method);
11520 if (ObjectArg.isInvalid())
11521 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011522 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011523 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011524
11525 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011526 const FunctionProtoType *Proto =
11527 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011528 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011529 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011530 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011531
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011532 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011533
Richard Smith55ce3522012-06-25 20:30:08 +000011534 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011535 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011536
Anders Carlsson47061ee2011-05-06 14:25:31 +000011537 if ((isa<CXXConstructorDecl>(CurContext) ||
11538 isa<CXXDestructorDecl>(CurContext)) &&
11539 TheCall->getMethodDecl()->isPure()) {
11540 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11541
Chandler Carruth59259262011-06-27 08:31:58 +000011542 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011543 Diag(MemExpr->getLocStart(),
11544 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11545 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11546 << MD->getParent()->getDeclName();
11547
11548 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011549 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011550 }
John McCallb268a282010-08-23 23:25:46 +000011551 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011552}
11553
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011554/// BuildCallToObjectOfClassType - Build a call to an object of class
11555/// type (C++ [over.call.object]), which can end up invoking an
11556/// overloaded function call operator (@c operator()) or performing a
11557/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011558ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011559Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011560 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011561 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011562 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011563 if (checkPlaceholderForOverload(*this, Obj))
11564 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011565 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011566
11567 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011568 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011569 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011570
John Wiegley01296292011-04-08 18:41:53 +000011571 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11572 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011573
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011574 // C++ [over.call.object]p1:
11575 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011576 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011577 // candidate functions includes at least the function call
11578 // operators of T. The function call operators of T are obtained by
11579 // ordinary lookup of the name operator() in the context of
11580 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011581 OverloadCandidateSet CandidateSet(LParenLoc,
11582 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011583 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011584
John Wiegley01296292011-04-08 18:41:53 +000011585 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011586 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011587 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011588
John McCall27b18f82009-11-17 02:14:36 +000011589 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11590 LookupQualifiedName(R, Record->getDecl());
11591 R.suppressDiagnostics();
11592
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011593 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011594 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011595 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011596 Object.get()->Classify(Context),
11597 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011598 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011600
Douglas Gregorab7897a2008-11-19 22:57:39 +000011601 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011602 // In addition, for each (non-explicit in C++0x) conversion function
11603 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011604 //
11605 // operator conversion-type-id () cv-qualifier;
11606 //
11607 // where cv-qualifier is the same cv-qualification as, or a
11608 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011609 // denotes the type "pointer to function of (P1,...,Pn) returning
11610 // R", or the type "reference to pointer to function of
11611 // (P1,...,Pn) returning R", or the type "reference to function
11612 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011613 // is also considered as a candidate function. Similarly,
11614 // surrogate call functions are added to the set of candidate
11615 // functions for each conversion function declared in an
11616 // accessible base class provided the function is not hidden
11617 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011618 std::pair<CXXRecordDecl::conversion_iterator,
11619 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011620 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011621 for (CXXRecordDecl::conversion_iterator
11622 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011623 NamedDecl *D = *I;
11624 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11625 if (isa<UsingShadowDecl>(D))
11626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011627
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011628 // Skip over templated conversion functions; they aren't
11629 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011630 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011631 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011632
John McCall6e9f8f62009-12-03 04:06:58 +000011633 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011634 if (!Conv->isExplicit()) {
11635 // Strip the reference type (if any) and then the pointer type (if
11636 // any) to get down to what might be a function type.
11637 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11638 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11639 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011640
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011641 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11642 {
11643 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011644 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011645 }
11646 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011647 }
Mike Stump11289f42009-09-09 15:08:12 +000011648
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011649 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11650
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011651 // Perform overload resolution.
11652 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011653 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011654 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011655 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011656 // Overload resolution succeeded; we'll build the appropriate call
11657 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011658 break;
11659
11660 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011661 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011662 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011663 << Object.get()->getType() << /*call*/ 1
11664 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011665 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011666 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011667 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011668 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011669 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011670 break;
11671
11672 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011673 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011674 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011675 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011676 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011677 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011678
11679 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011680 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011681 diag::err_ovl_deleted_object_call)
11682 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011683 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011684 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011685 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011687 break;
Mike Stump11289f42009-09-09 15:08:12 +000011688 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011689
Douglas Gregorb412e172010-07-25 18:17:45 +000011690 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011691 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011692
John McCall4124c492011-10-17 18:40:02 +000011693 UnbridgedCasts.restore();
11694
Craig Topperc3ec1492014-05-26 06:22:03 +000011695 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011696 // Since there is no function declaration, this is one of the
11697 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011698 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011699 = cast<CXXConversionDecl>(
11700 Best->Conversions[0].UserDefined.ConversionFunction);
11701
Craig Topperc3ec1492014-05-26 06:22:03 +000011702 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11703 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011704 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11705 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011706 assert(Conv == Best->FoundDecl.getDecl() &&
11707 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011708 // We selected one of the surrogate functions that converts the
11709 // object parameter to a function pointer. Perform the conversion
11710 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011711
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011712 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011713 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011714 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11715 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011716 if (Call.isInvalid())
11717 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011718 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011719 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11720 CK_UserDefinedConversion, Call.get(),
11721 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011722
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011723 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011724 }
11725
Craig Topperc3ec1492014-05-26 06:22:03 +000011726 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011727
Douglas Gregorab7897a2008-11-19 22:57:39 +000011728 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11729 // that calls this method, using Object for the implicit object
11730 // parameter and passing along the remaining arguments.
11731 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011732
11733 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011734 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011735 return ExprError();
11736
Chandler Carruth8e543b32010-12-12 08:17:55 +000011737 const FunctionProtoType *Proto =
11738 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011739
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011740 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011741
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011742 DeclarationNameInfo OpLocInfo(
11743 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11744 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011745 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011746 HadMultipleCandidates,
11747 OpLocInfo.getLoc(),
11748 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011749 if (NewFn.isInvalid())
11750 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011751
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011752 // Build the full argument list for the method call (the implicit object
11753 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011754 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011755 MethodArgs[0] = Object.get();
11756 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11757
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011758 // Once we've built TheCall, all of the expressions are properly
11759 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011760 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011761 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11762 ResultTy = ResultTy.getNonLValueExprType(Context);
11763
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011764 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011765 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011766 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11767 ResultTy, VK, RParenLoc, false);
11768 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011769
Alp Toker314cc812014-01-25 16:55:45 +000011770 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011771 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011772
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011773 // We may have default arguments. If so, we need to allocate more
11774 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011775 if (Args.size() < NumParams)
11776 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011777
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011778 bool IsError = false;
11779
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011780 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011781 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011782 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011783 Best->FoundDecl, Method);
11784 if (ObjRes.isInvalid())
11785 IsError = true;
11786 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011787 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011788 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011789
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011790 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011791 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011792 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011793 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011794 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011795
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011796 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011797
John McCalldadc5752010-08-24 06:29:42 +000011798 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011799 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011800 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011801 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011802 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011803
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011804 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011805 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011806 } else {
John McCalldadc5752010-08-24 06:29:42 +000011807 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011808 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11809 if (DefArg.isInvalid()) {
11810 IsError = true;
11811 break;
11812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011813
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011814 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011815 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011816
11817 TheCall->setArg(i + 1, Arg);
11818 }
11819
11820 // If this is a variadic call, handle args passed through "...".
11821 if (Proto->isVariadic()) {
11822 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011823 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011824 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11825 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000011826 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011827 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011828 }
11829 }
11830
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011831 if (IsError) return true;
11832
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011833 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011834
Richard Smith55ce3522012-06-25 20:30:08 +000011835 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011836 return true;
11837
John McCalle172be52010-08-24 06:09:16 +000011838 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011839}
11840
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011841/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011842/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011843/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011844ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011845Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11846 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011847 assert(Base->getType()->isRecordType() &&
11848 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011849
John McCall4124c492011-10-17 18:40:02 +000011850 if (checkPlaceholderForOverload(*this, Base))
11851 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011852
John McCallbc077cf2010-02-08 23:07:23 +000011853 SourceLocation Loc = Base->getExprLoc();
11854
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011855 // C++ [over.ref]p1:
11856 //
11857 // [...] An expression x->m is interpreted as (x.operator->())->m
11858 // for a class object x of type T if T::operator->() exists and if
11859 // the operator is selected as the best match function by the
11860 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011861 DeclarationName OpName =
11862 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000011863 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011864 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011865
John McCallbc077cf2010-02-08 23:07:23 +000011866 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011867 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011868 return ExprError();
11869
John McCall27b18f82009-11-17 02:14:36 +000011870 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11871 LookupQualifiedName(R, BaseRecord->getDecl());
11872 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011873
11874 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011875 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011876 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011877 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011878 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011879
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011880 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11881
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011882 // Perform overload resolution.
11883 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011884 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011885 case OR_Success:
11886 // Overload resolution succeeded; we'll build the call below.
11887 break;
11888
11889 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011890 if (CandidateSet.empty()) {
11891 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011892 if (NoArrowOperatorFound) {
11893 // Report this specific error to the caller instead of emitting a
11894 // diagnostic, as requested.
11895 *NoArrowOperatorFound = true;
11896 return ExprError();
11897 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011898 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11899 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011900 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011901 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011902 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011903 }
11904 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011905 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011906 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011908 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011909
11910 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011911 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11912 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011913 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011914 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011915
11916 case OR_Deleted:
11917 Diag(OpLoc, diag::err_ovl_deleted_oper)
11918 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011919 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011920 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011921 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011922 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011923 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011924 }
11925
Craig Topperc3ec1492014-05-26 06:22:03 +000011926 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000011927
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011928 // Convert the object parameter.
11929 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011930 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000011931 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011932 Best->FoundDecl, Method);
11933 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011934 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011935 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011936
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011937 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011938 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011939 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011940 if (FnExpr.isInvalid())
11941 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011942
Alp Toker314cc812014-01-25 16:55:45 +000011943 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011944 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11945 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011946 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011947 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011948 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011949
Alp Toker314cc812014-01-25 16:55:45 +000011950 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011951 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011952
11953 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011954}
11955
Richard Smithbcc22fc2012-03-09 08:00:36 +000011956/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11957/// a literal operator described by the provided lookup results.
11958ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11959 DeclarationNameInfo &SuffixInfo,
11960 ArrayRef<Expr*> Args,
11961 SourceLocation LitEndLoc,
11962 TemplateArgumentListInfo *TemplateArgs) {
11963 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011964
Richard Smith100b24a2014-04-17 01:52:14 +000011965 OverloadCandidateSet CandidateSet(UDSuffixLoc,
11966 OverloadCandidateSet::CSK_Normal);
Richard Smithbcc22fc2012-03-09 08:00:36 +000011967 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11968 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011969
Richard Smithbcc22fc2012-03-09 08:00:36 +000011970 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11971
Richard Smithbcc22fc2012-03-09 08:00:36 +000011972 // Perform overload resolution. This will usually be trivial, but might need
11973 // to perform substitutions for a literal operator template.
11974 OverloadCandidateSet::iterator Best;
11975 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11976 case OR_Success:
11977 case OR_Deleted:
11978 break;
11979
11980 case OR_No_Viable_Function:
11981 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11982 << R.getLookupName();
11983 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11984 return ExprError();
11985
11986 case OR_Ambiguous:
11987 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11988 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11989 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011990 }
11991
Richard Smithbcc22fc2012-03-09 08:00:36 +000011992 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011993 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11994 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011995 SuffixInfo.getLoc(),
11996 SuffixInfo.getInfo());
11997 if (Fn.isInvalid())
11998 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011999
12000 // Check the argument types. This should almost always be a no-op, except
12001 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012002 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012003 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012004 ExprResult InputInit = PerformCopyInitialization(
12005 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12006 SourceLocation(), Args[ArgIdx]);
12007 if (InputInit.isInvalid())
12008 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012009 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012010 }
12011
Alp Toker314cc812014-01-25 16:55:45 +000012012 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012013 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12014 ResultTy = ResultTy.getNonLValueExprType(Context);
12015
Richard Smithc67fdd42012-03-07 08:35:16 +000012016 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012017 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012018 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012019 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12020
Alp Toker314cc812014-01-25 16:55:45 +000012021 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012022 return ExprError();
12023
Craig Topperc3ec1492014-05-26 06:22:03 +000012024 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012025 return ExprError();
12026
12027 return MaybeBindToTemporary(UDL);
12028}
12029
Sam Panzer0f384432012-08-21 00:52:01 +000012030/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12031/// given LookupResult is non-empty, it is assumed to describe a member which
12032/// will be invoked. Otherwise, the function will be found via argument
12033/// dependent lookup.
12034/// CallExpr is set to a valid expression and FRS_Success returned on success,
12035/// otherwise CallExpr is set to ExprError() and some non-success value
12036/// is returned.
12037Sema::ForRangeStatus
12038Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12039 SourceLocation RangeLoc, VarDecl *Decl,
12040 BeginEndFunction BEF,
12041 const DeclarationNameInfo &NameInfo,
12042 LookupResult &MemberLookup,
12043 OverloadCandidateSet *CandidateSet,
12044 Expr *Range, ExprResult *CallExpr) {
12045 CandidateSet->clear();
12046 if (!MemberLookup.empty()) {
12047 ExprResult MemberRef =
12048 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12049 /*IsPtr=*/false, CXXScopeSpec(),
12050 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012051 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012052 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012053 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012054 if (MemberRef.isInvalid()) {
12055 *CallExpr = ExprError();
12056 Diag(Range->getLocStart(), diag::note_in_for_range)
12057 << RangeLoc << BEF << Range->getType();
12058 return FRS_DiagnosticIssued;
12059 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012060 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012061 if (CallExpr->isInvalid()) {
12062 *CallExpr = ExprError();
12063 Diag(Range->getLocStart(), diag::note_in_for_range)
12064 << RangeLoc << BEF << Range->getType();
12065 return FRS_DiagnosticIssued;
12066 }
12067 } else {
12068 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012069 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012070 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012071 NestedNameSpecifierLoc(), NameInfo,
12072 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012073 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012074
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012075 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012076 CandidateSet, CallExpr);
12077 if (CandidateSet->empty() || CandidateSetError) {
12078 *CallExpr = ExprError();
12079 return FRS_NoViableFunction;
12080 }
12081 OverloadCandidateSet::iterator Best;
12082 OverloadingResult OverloadResult =
12083 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12084
12085 if (OverloadResult == OR_No_Viable_Function) {
12086 *CallExpr = ExprError();
12087 return FRS_NoViableFunction;
12088 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012089 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012090 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012091 OverloadResult,
12092 /*AllowTypoCorrection=*/false);
12093 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12094 *CallExpr = ExprError();
12095 Diag(Range->getLocStart(), diag::note_in_for_range)
12096 << RangeLoc << BEF << Range->getType();
12097 return FRS_DiagnosticIssued;
12098 }
12099 }
12100 return FRS_Success;
12101}
12102
12103
Douglas Gregorcd695e52008-11-10 20:40:00 +000012104/// FixOverloadedFunctionReference - E is an expression that refers to
12105/// a C++ overloaded function (possibly with some parentheses and
12106/// perhaps a '&' around it). We have resolved the overloaded function
12107/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012108/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012109Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012110 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012111 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012112 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12113 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012114 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012115 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012116
Douglas Gregor51c538b2009-11-20 19:42:02 +000012117 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012118 }
12119
Douglas Gregor51c538b2009-11-20 19:42:02 +000012120 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012121 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12122 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012123 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012124 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012125 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012126 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012127 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012128 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012129
12130 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012131 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012133 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012134 }
12135
Douglas Gregor51c538b2009-11-20 19:42:02 +000012136 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012137 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012138 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12140 if (Method->isStatic()) {
12141 // Do nothing: static member functions aren't any different
12142 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012143 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012144 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012145 // UnresolvedLookupExpr holding an overloaded member function
12146 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012147 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12148 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012149 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012150 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012151
John McCalld14a8642009-11-21 08:51:07 +000012152 assert(isa<DeclRefExpr>(SubExpr)
12153 && "fixed to something other than a decl ref");
12154 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12155 && "fixed to a member ref with no nested name qualifier");
12156
12157 // We have taken the address of a pointer to member
12158 // function. Perform the computation here so that we get the
12159 // appropriate pointer to member type.
12160 QualType ClassType
12161 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12162 QualType MemPtrType
12163 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12164
John McCall7decc9e2010-11-18 06:31:45 +000012165 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12166 VK_RValue, OK_Ordinary,
12167 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012168 }
12169 }
John McCall16df1e52010-03-30 21:47:33 +000012170 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12171 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012172 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012173 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012174
John McCalle3027922010-08-25 11:45:40 +000012175 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012176 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012177 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012178 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012179 }
John McCalld14a8642009-11-21 08:51:07 +000012180
12181 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012182 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012183 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012184 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012185 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12186 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012187 }
12188
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012189 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12190 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012191 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012192 Fn,
John McCall113bee02012-03-10 09:33:50 +000012193 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012194 ULE->getNameLoc(),
12195 Fn->getType(),
12196 VK_LValue,
12197 Found.getDecl(),
12198 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012199 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012200 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12201 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012202 }
12203
John McCall10eae182009-11-30 22:42:35 +000012204 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012205 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012206 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012207 if (MemExpr->hasExplicitTemplateArgs()) {
12208 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12209 TemplateArgs = &TemplateArgsBuffer;
12210 }
John McCall6b51f282009-11-23 01:53:49 +000012211
John McCall2d74de92009-12-01 22:10:20 +000012212 Expr *Base;
12213
John McCall7decc9e2010-11-18 06:31:45 +000012214 // If we're filling in a static method where we used to have an
12215 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012216 if (MemExpr->isImplicitAccess()) {
12217 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012218 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12219 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012220 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012221 Fn,
John McCall113bee02012-03-10 09:33:50 +000012222 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012223 MemExpr->getMemberLoc(),
12224 Fn->getType(),
12225 VK_LValue,
12226 Found.getDecl(),
12227 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012228 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012229 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12230 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012231 } else {
12232 SourceLocation Loc = MemExpr->getMemberLoc();
12233 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012234 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012235 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012236 Base = new (Context) CXXThisExpr(Loc,
12237 MemExpr->getBaseType(),
12238 /*isImplicit=*/true);
12239 }
John McCall2d74de92009-12-01 22:10:20 +000012240 } else
John McCallc3007a22010-10-26 07:05:15 +000012241 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012242
John McCall4adb38c2011-04-27 00:36:17 +000012243 ExprValueKind valueKind;
12244 QualType type;
12245 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12246 valueKind = VK_LValue;
12247 type = Fn->getType();
12248 } else {
12249 valueKind = VK_RValue;
12250 type = Context.BoundMemberTy;
12251 }
12252
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012253 MemberExpr *ME = MemberExpr::Create(Context, Base,
12254 MemExpr->isArrow(),
12255 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012256 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012257 Fn,
12258 Found,
12259 MemExpr->getMemberNameInfo(),
12260 TemplateArgs,
12261 type, valueKind, OK_Ordinary);
12262 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012263 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012264 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012266
John McCallc3007a22010-10-26 07:05:15 +000012267 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012268}
12269
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012270ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012271 DeclAccessPair Found,
12272 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012273 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012274}
12275
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012276} // end namespace clang