blob: d3d027b8a56bd058fdcb21ee921673c3fcc75525 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
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"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
John McCall7decc9e2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000053 return E;
John McCall7decc9e2010-11-18 06:31:45 +000054}
55
John McCall5c32be02010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000061
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000204}
205
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000244bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith66e05fe2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000408 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != 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(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 break;
John McCall0d1da222010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000513 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520}
521
John McCall0d1da222010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
539 // template parameter and template argument information.
540 struct DFIParamWithArguments {
541 TemplateParameter Param;
542 TemplateArgument FirstArg;
543 TemplateArgument SecondArg;
544 };
545}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000550static MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000552 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 OverloadCandidate::DeductionFailureInfo Result;
554 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000556 Result.Data = 0;
557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000570 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000571 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Saved->Param = Info.Param;
575 Saved->FirstArg = Info.FirstArg;
576 Saved->SecondArg = Info.SecondArg;
577 Result.Data = Saved;
578 break;
579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000582 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000583 if (Info.hasSFINAEDiagnostic()) {
584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585 SourceLocation(), PartialDiagnostic::NullDiagnostic());
586 Info.takeSFINAEDiagnostic(*Diag);
587 Result.HasDiagnostic = true;
588 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000611 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000612 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 Data = 0;
614 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000615
616 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000617 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620 Diag->~PartialDiagnosticAt();
621 HasDiagnostic = false;
622 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor461761d2010-05-08 18:20:53 +0000625 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
628 break;
629 }
630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Richard Smith9ca64612012-05-07 09:03:25 +0000632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636 return 0;
637}
638
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000645 case Sema::TDK_TooManyArguments:
646 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000651 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653
654 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 case Sema::TDK_FailedOverloadResolution:
661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregord09efd42010-05-08 20:07:26 +0000667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregord09efd42010-05-08 20:07:26 +0000672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 return 0;
680
681 case Sema::TDK_SubstitutionFailure:
682 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregord09efd42010-05-08 20:07:26 +0000684 // Unhandled
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 break;
688 }
689
690 return 0;
691}
692
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 return 0;
704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000706 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708
Douglas Gregor461761d2010-05-08 18:20:53 +0000709 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711 case Sema::TDK_FailedOverloadResolution:
712 break;
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
Douglas Gregor461761d2010-05-08 18:20:53 +0000735 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737 case Sema::TDK_FailedOverloadResolution:
738 break;
739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000741 return 0;
742}
743
Benjamin Kramer97e59492012-10-09 15:52:25 +0000744void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000745 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749 i->DeductionFailure.Destroy();
750 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000751}
752
753void OverloadCandidateSet::clear() {
754 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000755 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000756 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757 Functions.clear();
758}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759
John McCall4124c492011-10-17 18:40:02 +0000760namespace {
761 class UnbridgedCastsSet {
762 struct Entry {
763 Expr **Addr;
764 Expr *Saved;
765 };
766 SmallVector<Entry, 2> Entries;
767
768 public:
769 void save(Sema &S, Expr *&E) {
770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771 Entry entry = { &E, E };
772 Entries.push_back(entry);
773 E = S.stripARCUnbridgedCast(E);
774 }
775
776 void restore() {
777 for (SmallVectorImpl<Entry>::iterator
778 i = Entries.begin(), e = Entries.end(); i != e; ++i)
779 *i->Addr = i->Saved;
780 }
781 };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788/// without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
794 // We can't handle overloaded expressions here because overload
795 // resolution might reasonably tweak them.
796 if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798 // If the context potentially accepts unbridged ARC casts, strip
799 // the unbridged cast and add it to the collection for later restoration.
800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801 unbridgedCasts) {
802 unbridgedCasts->save(S, E);
803 return false;
804 }
805
806 // Go ahead and check everything else.
807 ExprResult result = S.CheckPlaceholderExpr(E);
808 if (result.isInvalid())
809 return true;
810
811 E = result.take();
812 return false;
813 }
814
815 // Nothing to do.
816 return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822 unsigned numArgs,
823 UnbridgedCastsSet &unbridged) {
824 for (unsigned i = 0; i != numArgs; ++i)
825 if (checkPlaceholderForOverload(S, args[i], &unbridged))
826 return true;
827
828 return false;
829}
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with. This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839//
840// Example: Given the following input:
841//
842// void f(int, float); // #1
843// void f(int, int); // #2
844// int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000847// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848//
John McCall3d988d92009-12-02 08:47:38 +0000849// When we process #2, Old contains only the FunctionDecl for #1. By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853//
John McCall3d988d92009-12-02 08:47:38 +0000854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration. The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000865Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000868 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000869 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000870 NamedDecl *OldD = *I;
871
872 bool OldIsUsingDecl = false;
873 if (isa<UsingShadowDecl>(OldD)) {
874 OldIsUsingDecl = true;
875
876 // We can always introduce two using declarations into the same
877 // context, even if they have identical signatures.
878 if (NewIsUsingDecl) continue;
879
880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881 }
882
883 // If either declaration was introduced by a using declaration,
884 // we'll need to use slightly different rules for matching.
885 // Essentially, these rules are the normal rules, except that
886 // function templates hide function templates with different
887 // return types or template parameter lists.
888 bool UseMemberUsingDeclRules =
889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
John McCall3d988d92009-12-02 08:47:38 +0000891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895 continue;
896 }
897
John McCalldaa3d6b2009-12-09 03:35:25 +0000898 Match = *I;
899 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900 }
John McCall3d988d92009-12-02 08:47:38 +0000901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905 continue;
906 }
907
John McCalldaa3d6b2009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000910 }
John McCalla8987a2942010-11-10 03:01:53 +0000911 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000912 // We can overload with these, which can show up when doing
913 // redeclaration checks for UsingDecls.
914 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000915 } else if (isa<TagDecl>(OldD)) {
916 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918 // Optimistically assume that an unresolved using decl will
919 // overload; if it doesn't, we'll have to diagnose during
920 // template instantiation.
921 } else {
John McCall1f82f242009-11-18 22:49:29 +0000922 // (C++ 13p1):
923 // Only function declarations can be overloaded; object and type
924 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000925 Match = *I;
926 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000927 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928 }
John McCall1f82f242009-11-18 22:49:29 +0000929
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000931}
932
Rafael Espindola576127d2012-12-28 14:21:58 +0000933static bool canBeOverloaded(const FunctionDecl &D) {
934 if (D.getAttr<OverloadableAttr>())
935 return true;
936 if (D.hasCLanguageLinkage())
937 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000938
939 // Main cannot be overloaded (basic.start.main).
940 if (D.isMain())
941 return false;
942
Rafael Espindola576127d2012-12-28 14:21:58 +0000943 return true;
944}
945
John McCalle9cccd82010-06-16 08:42:20 +0000946bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
947 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000948 // If both of the functions are extern "C", then they are not
949 // overloads.
Rafael Espindola576127d2012-12-28 14:21:58 +0000950 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall8246e352010-08-12 07:09:11 +0000951 return false;
952
John McCall1f82f242009-11-18 22:49:29 +0000953 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
954 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
955
956 // C++ [temp.fct]p2:
957 // A function template can be overloaded with other function templates
958 // and with normal (non-template) functions.
959 if ((OldTemplate == 0) != (NewTemplate == 0))
960 return true;
961
962 // Is the function New an overload of the function Old?
963 QualType OldQType = Context.getCanonicalType(Old->getType());
964 QualType NewQType = Context.getCanonicalType(New->getType());
965
966 // Compare the signatures (C++ 1.3.10) of the two functions to
967 // determine whether they are overloads. If we find any mismatch
968 // in the signature, they are overloads.
969
970 // If either of these functions is a K&R-style function (no
971 // prototype), then we consider them to have matching signatures.
972 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
973 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
974 return false;
975
John McCall424cec92011-01-19 06:33:43 +0000976 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
977 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000978
979 // The signature of a function includes the types of its
980 // parameters (C++ 1.3.10), which includes the presence or absence
981 // of the ellipsis; see C++ DR 357).
982 if (OldQType != NewQType &&
983 (OldType->getNumArgs() != NewType->getNumArgs() ||
984 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000985 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000986 return true;
987
988 // C++ [temp.over.link]p4:
989 // The signature of a function template consists of its function
990 // signature, its return type and its template parameter list. The names
991 // of the template parameters are significant only for establishing the
992 // relationship between the template parameters and the rest of the
993 // signature.
994 //
995 // We check the return type and template parameter lists for function
996 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000997 //
998 // However, we don't consider either of these when deciding whether
999 // a member introduced by a shadow declaration is hidden.
1000 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +00001001 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1002 OldTemplate->getTemplateParameters(),
1003 false, TPL_TemplateMatch) ||
1004 OldType->getResultType() != NewType->getResultType()))
1005 return true;
1006
1007 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001008 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001009 //
1010 // As part of this, also check whether one of the member functions
1011 // is static, in which case they are not overloads (C++
1012 // 13.1p2). While not part of the definition of the signature,
1013 // this check is important to determine whether these functions
1014 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001015 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1016 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001017 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001018 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1019 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1020 if (!UseUsingDeclRules &&
1021 (OldMethod->getRefQualifier() == RQ_None ||
1022 NewMethod->getRefQualifier() == RQ_None)) {
1023 // C++0x [over.load]p2:
1024 // - Member function declarations with the same name and the same
1025 // parameter-type-list as well as member function template
1026 // declarations with the same name, the same parameter-type-list, and
1027 // the same template parameter lists cannot be overloaded if any of
1028 // them, but not all, have a ref-qualifier (8.3.5).
1029 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1030 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1031 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1032 }
1033 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
Richard Smith574f4f62013-01-14 05:37:29 +00001036 // We may not have applied the implicit const for a constexpr member
1037 // function yet (because we haven't yet resolved whether this is a static
1038 // or non-static member function). Add it now, on the assumption that this
1039 // is a redeclaration of OldMethod.
1040 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith59b8e702013-01-14 08:00:39 +00001041 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001042 NewQuals |= Qualifiers::Const;
1043 if (OldMethod->getTypeQualifiers() != NewQuals)
1044 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
John McCall1f82f242009-11-18 22:49:29 +00001047 // The signatures match; this is not an overload.
1048 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049}
1050
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001051/// \brief Checks availability of the function depending on the current
1052/// function context. Inside an unavailable function, unavailability is ignored.
1053///
1054/// \returns true if \arg FD is unavailable and current context is inside
1055/// an available function, false otherwise.
1056bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1057 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1058}
1059
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001060/// \brief Tries a user-defined conversion from From to ToType.
1061///
1062/// Produces an implicit conversion sequence for when a standard conversion
1063/// is not an option. See TryImplicitConversion for more information.
1064static ImplicitConversionSequence
1065TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1066 bool SuppressUserConversions,
1067 bool AllowExplicit,
1068 bool InOverloadResolution,
1069 bool CStyle,
1070 bool AllowObjCWritebackConversion) {
1071 ImplicitConversionSequence ICS;
1072
1073 if (SuppressUserConversions) {
1074 // We're not in the case above, so there is no conversion that
1075 // we can perform.
1076 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1077 return ICS;
1078 }
1079
1080 // Attempt user-defined conversion.
1081 OverloadCandidateSet Conversions(From->getExprLoc());
1082 OverloadingResult UserDefResult
1083 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1084 AllowExplicit);
1085
1086 if (UserDefResult == OR_Success) {
1087 ICS.setUserDefined();
1088 // C++ [over.ics.user]p4:
1089 // A conversion of an expression of class type to the same class
1090 // type is given Exact Match rank, and a conversion of an
1091 // expression of class type to a base class of that type is
1092 // given Conversion rank, in spite of the fact that a copy
1093 // constructor (i.e., a user-defined conversion function) is
1094 // called for those cases.
1095 if (CXXConstructorDecl *Constructor
1096 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1097 QualType FromCanon
1098 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1099 QualType ToCanon
1100 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1101 if (Constructor->isCopyConstructor() &&
1102 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1103 // Turn this into a "standard" conversion sequence, so that it
1104 // gets ranked with standard conversion sequences.
1105 ICS.setStandard();
1106 ICS.Standard.setAsIdentityConversion();
1107 ICS.Standard.setFromType(From->getType());
1108 ICS.Standard.setAllToTypes(ToType);
1109 ICS.Standard.CopyConstructor = Constructor;
1110 if (ToCanon != FromCanon)
1111 ICS.Standard.Second = ICK_Derived_To_Base;
1112 }
1113 }
1114
1115 // C++ [over.best.ics]p4:
1116 // However, when considering the argument of a user-defined
1117 // conversion function that is a candidate by 13.3.1.3 when
1118 // invoked for the copying of the temporary in the second step
1119 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1120 // 13.3.1.6 in all cases, only standard conversion sequences and
1121 // ellipsis conversion sequences are allowed.
1122 if (SuppressUserConversions && ICS.isUserDefined()) {
1123 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1124 }
1125 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1126 ICS.setAmbiguous();
1127 ICS.Ambiguous.setFromType(From->getType());
1128 ICS.Ambiguous.setToType(ToType);
1129 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1130 Cand != Conversions.end(); ++Cand)
1131 if (Cand->Viable)
1132 ICS.Ambiguous.addConversion(Cand->Function);
1133 } else {
1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1135 }
1136
1137 return ICS;
1138}
1139
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001140/// TryImplicitConversion - Attempt to perform an implicit conversion
1141/// from the given expression (Expr) to the given type (ToType). This
1142/// function returns an implicit conversion sequence that can be used
1143/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144///
1145/// void f(float f);
1146/// void g(int i) { f(i); }
1147///
1148/// this routine would produce an implicit conversion sequence to
1149/// describe the initialization of f from i, which will be a standard
1150/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1151/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1152//
1153/// Note that this routine only determines how the conversion can be
1154/// performed; it does not actually perform the conversion. As such,
1155/// it will not produce any diagnostics if no conversion is available,
1156/// but will instead return an implicit conversion sequence of kind
1157/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001158///
1159/// If @p SuppressUserConversions, then user-defined conversions are
1160/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001161/// If @p AllowExplicit, then explicit user-defined conversions are
1162/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001163///
1164/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1165/// writeback conversion, which allows __autoreleasing id* parameters to
1166/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001167static ImplicitConversionSequence
1168TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1169 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001171 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001172 bool CStyle,
1173 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001175 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001176 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001177 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001178 return ICS;
1179 }
1180
David Blaikiebbafb8a2012-03-11 07:00:24 +00001181 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001183 return ICS;
1184 }
1185
Douglas Gregor836a7e82010-08-11 02:15:33 +00001186 // C++ [over.ics.user]p4:
1187 // A conversion of an expression of class type to the same class
1188 // type is given Exact Match rank, and a conversion of an
1189 // expression of class type to a base class of that type is
1190 // given Conversion rank, in spite of the fact that a copy/move
1191 // constructor (i.e., a user-defined conversion function) is
1192 // called for those cases.
1193 QualType FromType = From->getType();
1194 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001195 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1196 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001197 ICS.setStandard();
1198 ICS.Standard.setAsIdentityConversion();
1199 ICS.Standard.setFromType(FromType);
1200 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201
Douglas Gregor5ab11652010-04-17 22:01:05 +00001202 // We don't actually check at this point whether there is a valid
1203 // copy/move constructor, since overloading just assumes that it
1204 // exists. When we actually perform initialization, we'll find the
1205 // appropriate constructor to copy the returned object, if needed.
1206 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001207
Douglas Gregor5ab11652010-04-17 22:01:05 +00001208 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001209 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001210 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211
Douglas Gregor836a7e82010-08-11 02:15:33 +00001212 return ICS;
1213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001215 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1216 AllowExplicit, InOverloadResolution, CStyle,
1217 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001218}
1219
John McCall31168b02011-06-15 23:02:42 +00001220ImplicitConversionSequence
1221Sema::TryImplicitConversion(Expr *From, QualType ToType,
1222 bool SuppressUserConversions,
1223 bool AllowExplicit,
1224 bool InOverloadResolution,
1225 bool CStyle,
1226 bool AllowObjCWritebackConversion) {
1227 return clang::TryImplicitConversion(*this, From, ToType,
1228 SuppressUserConversions, AllowExplicit,
1229 InOverloadResolution, CStyle,
1230 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001231}
1232
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001233/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001234/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001235/// converted expression. Flavor is the kind of conversion we're
1236/// performing, used in the error message. If @p AllowExplicit,
1237/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001238ExprResult
1239Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001240 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001241 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001242 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001243}
1244
John Wiegley01296292011-04-08 18:41:53 +00001245ExprResult
1246Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001247 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001248 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001249 if (checkPlaceholderForOverload(*this, From))
1250 return ExprError();
1251
John McCall31168b02011-06-15 23:02:42 +00001252 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1253 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001254 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001255 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001256
John McCall5c32be02010-08-24 20:38:10 +00001257 ICS = clang::TryImplicitConversion(*this, From, ToType,
1258 /*SuppressUserConversions=*/false,
1259 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001260 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001261 /*CStyle=*/false,
1262 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001263 return PerformImplicitConversion(From, ToType, ICS, Action);
1264}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
1266/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001267/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001268bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1269 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001270 if (Context.hasSameUnqualifiedType(FromType, ToType))
1271 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
John McCall991eb4b2010-12-21 00:44:39 +00001273 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1274 // where F adds one of the following at most once:
1275 // - a pointer
1276 // - a member pointer
1277 // - a block pointer
1278 CanQualType CanTo = Context.getCanonicalType(ToType);
1279 CanQualType CanFrom = Context.getCanonicalType(FromType);
1280 Type::TypeClass TyClass = CanTo->getTypeClass();
1281 if (TyClass != CanFrom->getTypeClass()) return false;
1282 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1283 if (TyClass == Type::Pointer) {
1284 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1285 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1286 } else if (TyClass == Type::BlockPointer) {
1287 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1288 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1289 } else if (TyClass == Type::MemberPointer) {
1290 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1291 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1292 } else {
1293 return false;
1294 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001295
John McCall991eb4b2010-12-21 00:44:39 +00001296 TyClass = CanTo->getTypeClass();
1297 if (TyClass != CanFrom->getTypeClass()) return false;
1298 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1299 return false;
1300 }
1301
1302 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1303 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1304 if (!EInfo.getNoReturn()) return false;
1305
1306 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1307 assert(QualType(FromFn, 0).isCanonical());
1308 if (QualType(FromFn, 0) != CanTo) return false;
1309
1310 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001311 return true;
1312}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313
Douglas Gregor46188682010-05-18 22:42:18 +00001314/// \brief Determine whether the conversion from FromType to ToType is a valid
1315/// vector conversion.
1316///
1317/// \param ICK Will be set to the vector conversion kind, if this is a vector
1318/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1320 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001321 // We need at least one of these types to be a vector type to have a vector
1322 // conversion.
1323 if (!ToType->isVectorType() && !FromType->isVectorType())
1324 return false;
1325
1326 // Identical types require no conversions.
1327 if (Context.hasSameUnqualifiedType(FromType, ToType))
1328 return false;
1329
1330 // There are no conversions between extended vector types, only identity.
1331 if (ToType->isExtVectorType()) {
1332 // There are no conversions between extended vector types other than the
1333 // identity conversion.
1334 if (FromType->isExtVectorType())
1335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Douglas Gregor46188682010-05-18 22:42:18 +00001337 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001338 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001339 ICK = ICK_Vector_Splat;
1340 return true;
1341 }
1342 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001343
1344 // We can perform the conversion between vector types in the following cases:
1345 // 1)vector types are equivalent AltiVec and GCC vector types
1346 // 2)lax vector conversions are permitted and the vector types are of the
1347 // same size
1348 if (ToType->isVectorType() && FromType->isVectorType()) {
1349 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001350 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001351 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001352 ICK = ICK_Vector_Conversion;
1353 return true;
1354 }
Douglas Gregor46188682010-05-18 22:42:18 +00001355 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001356
Douglas Gregor46188682010-05-18 22:42:18 +00001357 return false;
1358}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001360static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1361 bool InOverloadResolution,
1362 StandardConversionSequence &SCS,
1363 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001364
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001365/// IsStandardConversion - Determines whether there is a standard
1366/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1367/// expression From to the type ToType. Standard conversion sequences
1368/// only consider non-class types; for conversions that involve class
1369/// types, use TryImplicitConversion. If a conversion exists, SCS will
1370/// contain the standard conversion sequence required to perform this
1371/// conversion and this routine will return true. Otherwise, this
1372/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001373static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1374 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001375 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001376 bool CStyle,
1377 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001378 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001380 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001381 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001382 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001383 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001384 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001385 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001386
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001387 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001388 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001389 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001390 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001391 return false;
1392
Mike Stump11289f42009-09-09 15:08:12 +00001393 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001394 }
1395
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001396 // The first conversion can be an lvalue-to-rvalue conversion,
1397 // array-to-pointer conversion, or function-to-pointer conversion
1398 // (C++ 4p1).
1399
John McCall5c32be02010-08-24 20:38:10 +00001400 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001401 DeclAccessPair AccessPair;
1402 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001404 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001405 // We were able to resolve the address of the overloaded function,
1406 // so we can convert to the type of that function.
1407 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001408
1409 // we can sometimes resolve &foo<int> regardless of ToType, so check
1410 // if the type matches (identity) or we are converting to bool
1411 if (!S.Context.hasSameUnqualifiedType(
1412 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1413 QualType resultTy;
1414 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001415 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001416 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1417 // otherwise, only a boolean conversion is standard
1418 if (!ToType->isBooleanType())
1419 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
Chandler Carruthffce2452011-03-29 08:08:18 +00001422 // Check if the "from" expression is taking the address of an overloaded
1423 // function and recompute the FromType accordingly. Take advantage of the
1424 // fact that non-static member functions *must* have such an address-of
1425 // expression.
1426 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1427 if (Method && !Method->isStatic()) {
1428 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1429 "Non-unary operator on non-static member address");
1430 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1431 == UO_AddrOf &&
1432 "Non-address-of operator on non-static member address");
1433 const Type *ClassType
1434 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1435 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001436 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1437 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1438 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001439 "Non-address-of operator for overloaded function expression");
1440 FromType = S.Context.getPointerType(FromType);
1441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442
Douglas Gregor980fb162010-04-29 18:24:40 +00001443 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001444 assert(S.Context.hasSameType(
1445 FromType,
1446 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001447 } else {
1448 return false;
1449 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001450 }
John McCall154a2fd2011-08-30 00:57:29 +00001451 // Lvalue-to-rvalue conversion (C++11 4.1):
1452 // A glvalue (3.10) of a non-function, non-array type T can
1453 // be converted to a prvalue.
1454 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001455 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001456 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001457 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001458 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459
Douglas Gregorc79862f2012-04-12 17:51:55 +00001460 // C11 6.3.2.1p2:
1461 // ... if the lvalue has atomic type, the value has the non-atomic version
1462 // of the type of the lvalue ...
1463 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1464 FromType = Atomic->getValueType();
1465
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001466 // If T is a non-class type, the type of the rvalue is the
1467 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001468 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1469 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001471 } else if (FromType->isArrayType()) {
1472 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001473 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001474
1475 // An lvalue or rvalue of type "array of N T" or "array of unknown
1476 // bound of T" can be converted to an rvalue of type "pointer to
1477 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001478 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479
John McCall5c32be02010-08-24 20:38:10 +00001480 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001481 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001482 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483
1484 // For the purpose of ranking in overload resolution
1485 // (13.3.3.1.1), this conversion is considered an
1486 // array-to-pointer conversion followed by a qualification
1487 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 SCS.Second = ICK_Identity;
1489 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001490 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001491 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 }
John McCall086a4642010-11-24 05:12:34 +00001494 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001495 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497
1498 // An lvalue of function type T can be converted to an rvalue of
1499 // type "pointer to T." The result is a pointer to the
1500 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001501 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001502 } else {
1503 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001504 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001506 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507
1508 // The second conversion can be an integral promotion, floating
1509 // point promotion, integral conversion, floating point conversion,
1510 // floating-integral conversion, pointer conversion,
1511 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001512 // For overloading in C, this can also be a "compatible-type"
1513 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001514 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001515 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001516 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001517 // The unqualified versions of the types are the same: there's no
1518 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001520 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001521 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001524 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001528 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001529 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001530 SCS.Second = ICK_Complex_Promotion;
1531 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001532 } else if (ToType->isBooleanType() &&
1533 (FromType->isArithmeticType() ||
1534 FromType->isAnyPointerType() ||
1535 FromType->isBlockPointerType() ||
1536 FromType->isMemberPointerType() ||
1537 FromType->isNullPtrType())) {
1538 // Boolean conversions (C++ 4.12).
1539 SCS.Second = ICK_Boolean_Conversion;
1540 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001541 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001542 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001543 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001544 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001546 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001547 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001548 SCS.Second = ICK_Complex_Conversion;
1549 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001550 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1551 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001552 // Complex-real conversions (C99 6.3.1.7)
1553 SCS.Second = ICK_Complex_Real;
1554 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001555 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001556 // Floating point conversions (C++ 4.8).
1557 SCS.Second = ICK_Floating_Conversion;
1558 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001559 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001560 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001561 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001562 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001563 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001566 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001567 SCS.Second = ICK_Block_Pointer_Conversion;
1568 } else if (AllowObjCWritebackConversion &&
1569 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1570 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001571 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1572 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001573 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001574 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001575 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001576 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001578 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001579 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001580 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001581 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001582 SCS.Second = SecondICK;
1583 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001584 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001585 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001586 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001587 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001588 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001589 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001590 // Treat a conversion that strips "noreturn" as an identity conversion.
1591 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001592 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1593 InOverloadResolution,
1594 SCS, CStyle)) {
1595 SCS.Second = ICK_TransparentUnionConversion;
1596 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1598 CStyle)) {
1599 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001600 // appropriately.
1601 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602 } else {
1603 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001604 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001605 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001606 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001607
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001608 QualType CanonFrom;
1609 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001611 bool ObjCLifetimeConversion;
1612 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1613 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001614 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001615 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001617 CanonFrom = S.Context.getCanonicalType(FromType);
1618 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 } else {
1620 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Third = ICK_Identity;
1622
Mike Stump11289f42009-09-09 15:08:12 +00001623 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 // [...] Any difference in top-level cv-qualification is
1625 // subsumed by the initialization itself and does not constitute
1626 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001627 CanonFrom = S.Context.getCanonicalType(FromType);
1628 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001630 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001631 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001632 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1633 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001634 FromType = ToType;
1635 CanonFrom = CanonTo;
1636 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001637 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001638 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
1640 // If we have not converted the argument type to the parameter type,
1641 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001642 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001647
1648static bool
1649IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1650 QualType &ToType,
1651 bool InOverloadResolution,
1652 StandardConversionSequence &SCS,
1653 bool CStyle) {
1654
1655 const RecordType *UT = ToType->getAsUnionType();
1656 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1657 return false;
1658 // The field to initialize within the transparent union.
1659 RecordDecl *UD = UT->getDecl();
1660 // It's compatible if the expression matches any of the fields.
1661 for (RecordDecl::field_iterator it = UD->field_begin(),
1662 itend = UD->field_end();
1663 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001664 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1665 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001666 ToType = it->getType();
1667 return true;
1668 }
1669 }
1670 return false;
1671}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672
1673/// IsIntegralPromotion - Determines whether the conversion from the
1674/// expression From (whose potentially-adjusted type is FromType) to
1675/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1676/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001677bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001678 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001679 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001680 if (!To) {
1681 return false;
1682 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683
1684 // An rvalue of type char, signed char, unsigned char, short int, or
1685 // unsigned short int can be converted to an rvalue of type int if
1686 // int can represent all the values of the source type; otherwise,
1687 // the source rvalue can be converted to an rvalue of type unsigned
1688 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001689 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1690 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001691 if (// We can promote any signed, promotable integer type to an int
1692 (FromType->isSignedIntegerType() ||
1693 // We can promote any unsigned integer type whose size is
1694 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001695 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001696 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001698 }
1699
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 return To->getKind() == BuiltinType::UInt;
1701 }
1702
Richard Smithb9c5a602012-09-13 21:18:54 +00001703 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 // A prvalue of an unscoped enumeration type whose underlying type is not
1705 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1706 // following types that can represent all the values of the enumeration
1707 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1708 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001709 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001711 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712 // with lowest integer conversion rank (4.13) greater than the rank of long
1713 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001714 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001715 // C++11 [conv.prom]p4:
1716 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1717 // can be converted to a prvalue of its underlying type. Moreover, if
1718 // integral promotion can be applied to its underlying type, a prvalue of an
1719 // unscoped enumeration type whose underlying type is fixed can also be
1720 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001721 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1722 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1723 // provided for a scoped enumeration.
1724 if (FromEnumType->getDecl()->isScoped())
1725 return false;
1726
Richard Smithb9c5a602012-09-13 21:18:54 +00001727 // We can perform an integral promotion to the underlying type of the enum,
1728 // even if that's not the promoted type.
1729 if (FromEnumType->getDecl()->isFixed()) {
1730 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1731 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1732 IsIntegralPromotion(From, Underlying, ToType);
1733 }
1734
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001735 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001737 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001738 return Context.hasSameUnqualifiedType(ToType,
1739 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001740 }
John McCall56774992009-12-09 09:09:27 +00001741
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001742 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1744 // to an rvalue a prvalue of the first of the following types that can
1745 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001746 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001748 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001749 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001750 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001752 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753 // Determine whether the type we're converting from is signed or
1754 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001755 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 // The types we'll try to promote to, in the appropriate
1759 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001760 QualType PromoteTypes[6] = {
1761 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001762 Context.LongTy, Context.UnsignedLongTy ,
1763 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001765 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1767 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001768 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001769 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1770 // We found the type that we can promote to. If this is the
1771 // type we wanted, we have a promotion. Otherwise, no
1772 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001773 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001774 }
1775 }
1776 }
1777
1778 // An rvalue for an integral bit-field (9.6) can be converted to an
1779 // rvalue of type int if int can represent all the values of the
1780 // bit-field; otherwise, it can be converted to unsigned int if
1781 // unsigned int can represent all the values of the bit-field. If
1782 // the bit-field is larger yet, no integral promotion applies to
1783 // it. If the bit-field has an enumerated type, it is treated as any
1784 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001785 // FIXME: We should delay checking of bit-fields until we actually perform the
1786 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001787 using llvm::APSInt;
1788 if (From)
1789 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001790 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001791 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001792 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1793 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1794 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001796 // Are we promoting to an int from a bitfield that fits in an int?
1797 if (BitWidth < ToSize ||
1798 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1799 return To->getKind() == BuiltinType::Int;
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001802 // Are we promoting to an unsigned int from an unsigned bitfield
1803 // that fits into an unsigned int?
1804 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1805 return To->getKind() == BuiltinType::UInt;
1806 }
Mike Stump11289f42009-09-09 15:08:12 +00001807
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001808 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001809 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001810 }
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812 // An rvalue of type bool can be converted to an rvalue of type int,
1813 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001814 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001815 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001816 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817
1818 return false;
1819}
1820
1821/// IsFloatingPointPromotion - Determines whether the conversion from
1822/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1823/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001824bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001825 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1826 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001827 /// An rvalue of type float can be converted to an rvalue of type
1828 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 if (FromBuiltin->getKind() == BuiltinType::Float &&
1830 ToBuiltin->getKind() == BuiltinType::Double)
1831 return true;
1832
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001833 // C99 6.3.1.5p1:
1834 // When a float is promoted to double or long double, or a
1835 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001836 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001837 (FromBuiltin->getKind() == BuiltinType::Float ||
1838 FromBuiltin->getKind() == BuiltinType::Double) &&
1839 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1840 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001841
1842 // Half can be promoted to float.
1843 if (FromBuiltin->getKind() == BuiltinType::Half &&
1844 ToBuiltin->getKind() == BuiltinType::Float)
1845 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001846 }
1847
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848 return false;
1849}
1850
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001851/// \brief Determine if a conversion is a complex promotion.
1852///
1853/// A complex promotion is defined as a complex -> complex conversion
1854/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001855/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001856bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001857 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001858 if (!FromComplex)
1859 return false;
1860
John McCall9dd450b2009-09-21 23:43:11 +00001861 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001862 if (!ToComplex)
1863 return false;
1864
1865 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001866 ToComplex->getElementType()) ||
1867 IsIntegralPromotion(0, FromComplex->getElementType(),
1868 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001869}
1870
Douglas Gregor237f96c2008-11-26 23:31:11 +00001871/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1872/// the pointer type FromPtr to a pointer to type ToPointee, with the
1873/// same type qualifiers as FromPtr has on its pointee type. ToType,
1874/// if non-empty, will be a pointer to ToType that may or may not have
1875/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001876///
Mike Stump11289f42009-09-09 15:08:12 +00001877static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001878BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001879 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001880 ASTContext &Context,
1881 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001882 assert((FromPtr->getTypeClass() == Type::Pointer ||
1883 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1884 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885
John McCall31168b02011-06-15 23:02:42 +00001886 /// Conversions to 'id' subsume cv-qualifier conversions.
1887 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001888 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001889
1890 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001891 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001892 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001893 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall31168b02011-06-15 23:02:42 +00001895 if (StripObjCLifetime)
1896 Quals.removeObjCLifetime();
1897
Mike Stump11289f42009-09-09 15:08:12 +00001898 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001899 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001900 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001901 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001902 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001903
1904 // Build a pointer to ToPointee. It has the right qualifiers
1905 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001906 if (isa<ObjCObjectPointerType>(ToType))
1907 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001908 return Context.getPointerType(ToPointee);
1909 }
1910
1911 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001912 QualType QualifiedCanonToPointee
1913 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001915 if (isa<ObjCObjectPointerType>(ToType))
1916 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1917 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001918}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
Mike Stump11289f42009-09-09 15:08:12 +00001920static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001921 bool InOverloadResolution,
1922 ASTContext &Context) {
1923 // Handle value-dependent integral null pointer constants correctly.
1924 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1925 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001926 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001927 return !InOverloadResolution;
1928
Douglas Gregor56751b52009-09-25 04:25:58 +00001929 return Expr->isNullPointerConstant(Context,
1930 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1931 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001932}
Mike Stump11289f42009-09-09 15:08:12 +00001933
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934/// IsPointerConversion - Determines whether the conversion of the
1935/// expression From, which has the (possibly adjusted) type FromType,
1936/// can be converted to the type ToType via a pointer conversion (C++
1937/// 4.10). If so, returns true and places the converted type (that
1938/// might differ from ToType in its cv-qualifiers at some level) into
1939/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001940///
Douglas Gregora29dc052008-11-27 01:19:21 +00001941/// This routine also supports conversions to and from block pointers
1942/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1943/// pointers to interfaces. FIXME: Once we've determined the
1944/// appropriate overloading rules for Objective-C, we may want to
1945/// split the Objective-C checks into a different routine; however,
1946/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001947/// conversions, so for now they live here. IncompatibleObjC will be
1948/// set if the conversion is an allowed Objective-C conversion that
1949/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001951 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001952 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001953 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001954 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001955 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1956 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001957 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001958
Mike Stump11289f42009-09-09 15:08:12 +00001959 // Conversion from a null pointer constant to any Objective-C pointer type.
1960 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001962 ConvertedType = ToType;
1963 return true;
1964 }
1965
Douglas Gregor231d1c62008-11-27 00:15:41 +00001966 // Blocks: Block pointers can be converted to void*.
1967 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001968 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001969 ConvertedType = ToType;
1970 return true;
1971 }
1972 // Blocks: A null pointer constant can be converted to a block
1973 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001974 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001975 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001976 ConvertedType = ToType;
1977 return true;
1978 }
1979
Sebastian Redl576fd422009-05-10 18:38:11 +00001980 // If the left-hand-side is nullptr_t, the right side can be a null
1981 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001982 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001983 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001984 ConvertedType = ToType;
1985 return true;
1986 }
1987
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001988 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001989 if (!ToTypePtr)
1990 return false;
1991
1992 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001993 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001994 ConvertedType = ToType;
1995 return true;
1996 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001997
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001999 // , including objective-c pointers.
2000 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002001 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002002 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002003 ConvertedType = BuildSimilarlyQualifiedPointerType(
2004 FromType->getAs<ObjCObjectPointerType>(),
2005 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002006 ToType, Context);
2007 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002008 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002009 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002010 if (!FromTypePtr)
2011 return false;
2012
2013 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002014
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002016 // pointer conversion, so don't do all of the work below.
2017 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2018 return false;
2019
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002020 // An rvalue of type "pointer to cv T," where T is an object type,
2021 // can be converted to an rvalue of type "pointer to cv void" (C++
2022 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002023 if (FromPointeeType->isIncompleteOrObjectType() &&
2024 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002026 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002027 ToType, Context,
2028 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029 return true;
2030 }
2031
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002032 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002033 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002034 ToPointeeType->isVoidType()) {
2035 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2036 ToPointeeType,
2037 ToType, Context);
2038 return true;
2039 }
2040
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002041 // When we're overloading in C, we allow a special kind of pointer
2042 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002043 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002044 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002045 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002046 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002047 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002048 return true;
2049 }
2050
Douglas Gregor5c407d92008-10-23 00:40:37 +00002051 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002052 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002053 // An rvalue of type "pointer to cv D," where D is a class type,
2054 // can be converted to an rvalue of type "pointer to cv B," where
2055 // B is a base class (clause 10) of D. If B is an inaccessible
2056 // (clause 11) or ambiguous (10.2) base class of D, a program that
2057 // necessitates this conversion is ill-formed. The result of the
2058 // conversion is a pointer to the base class sub-object of the
2059 // derived class object. The null pointer value is converted to
2060 // the null pointer value of the destination type.
2061 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002062 // Note that we do not check for ambiguity or inaccessibility
2063 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002064 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002065 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002066 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002067 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002068 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002070 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002071 ToType, Context);
2072 return true;
2073 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002074
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002075 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2076 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2078 ToPointeeType,
2079 ToType, Context);
2080 return true;
2081 }
2082
Douglas Gregora119f102008-12-19 19:13:09 +00002083 return false;
2084}
Douglas Gregoraec25842011-04-26 23:16:46 +00002085
2086/// \brief Adopt the given qualifiers for the given type.
2087static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2088 Qualifiers TQs = T.getQualifiers();
2089
2090 // Check whether qualifiers already match.
2091 if (TQs == Qs)
2092 return T;
2093
2094 if (Qs.compatiblyIncludes(TQs))
2095 return Context.getQualifiedType(T, Qs);
2096
2097 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2098}
Douglas Gregora119f102008-12-19 19:13:09 +00002099
2100/// isObjCPointerConversion - Determines whether this is an
2101/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2102/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002103bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002104 QualType& ConvertedType,
2105 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002106 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002107 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Douglas Gregoraec25842011-04-26 23:16:46 +00002109 // The set of qualifiers on the type we're converting from.
2110 Qualifiers FromQualifiers = FromType.getQualifiers();
2111
Steve Naroff7cae42b2009-07-10 23:34:53 +00002112 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002113 const ObjCObjectPointerType* ToObjCPtr =
2114 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002115 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002116 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002117
Steve Naroff7cae42b2009-07-10 23:34:53 +00002118 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002119 // If the pointee types are the same (ignoring qualifications),
2120 // then this is not a pointer conversion.
2121 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2122 FromObjCPtr->getPointeeType()))
2123 return false;
2124
Douglas Gregoraec25842011-04-26 23:16:46 +00002125 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002126 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002127 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002128 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002129 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002130 return true;
2131 }
2132 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002133 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002134 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002135 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002136 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002137 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002138 return true;
2139 }
2140 // Objective C++: We're able to convert from a pointer to an
2141 // interface to a pointer to a different interface.
2142 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002143 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2144 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002145 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002146 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2147 FromObjCPtr->getPointeeType()))
2148 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002150 ToObjCPtr->getPointeeType(),
2151 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002152 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002153 return true;
2154 }
2155
2156 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2157 // Okay: this is some kind of implicit downcast of Objective-C
2158 // interfaces, which is permitted. However, we're going to
2159 // complain about it.
2160 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002162 ToObjCPtr->getPointeeType(),
2163 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002164 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002165 return true;
2166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002169 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002170 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002171 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002172 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002173 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002174 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002175 // to a block pointer type.
2176 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002177 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002178 return true;
2179 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002180 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002183 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002185 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002186 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002187 return true;
2188 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002189 else
Douglas Gregora119f102008-12-19 19:13:09 +00002190 return false;
2191
Douglas Gregor033f56d2008-12-23 00:53:59 +00002192 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002193 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002194 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002195 else if (const BlockPointerType *FromBlockPtr =
2196 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002197 FromPointeeType = FromBlockPtr->getPointeeType();
2198 else
Douglas Gregora119f102008-12-19 19:13:09 +00002199 return false;
2200
Douglas Gregora119f102008-12-19 19:13:09 +00002201 // If we have pointers to pointers, recursively check whether this
2202 // is an Objective-C conversion.
2203 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2204 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2205 IncompatibleObjC)) {
2206 // We always complain about this conversion.
2207 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002208 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002209 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002210 return true;
2211 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002212 // Allow conversion of pointee being objective-c pointer to another one;
2213 // as in I* to id.
2214 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2215 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2216 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2217 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002218
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002219 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002221 return true;
2222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002223
Douglas Gregor033f56d2008-12-23 00:53:59 +00002224 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002225 // differences in the argument and result types are in Objective-C
2226 // pointer conversions. If so, we permit the conversion (but
2227 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002228 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002229 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002230 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002231 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002232 if (FromFunctionType && ToFunctionType) {
2233 // If the function types are exactly the same, this isn't an
2234 // Objective-C pointer conversion.
2235 if (Context.getCanonicalType(FromPointeeType)
2236 == Context.getCanonicalType(ToPointeeType))
2237 return false;
2238
2239 // Perform the quick checks that will tell us whether these
2240 // function types are obviously different.
2241 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2242 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2243 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2244 return false;
2245
2246 bool HasObjCConversion = false;
2247 if (Context.getCanonicalType(FromFunctionType->getResultType())
2248 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2249 // Okay, the types match exactly. Nothing to do.
2250 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2251 ToFunctionType->getResultType(),
2252 ConvertedType, IncompatibleObjC)) {
2253 // Okay, we have an Objective-C pointer conversion.
2254 HasObjCConversion = true;
2255 } else {
2256 // Function types are too different. Abort.
2257 return false;
2258 }
Mike Stump11289f42009-09-09 15:08:12 +00002259
Douglas Gregora119f102008-12-19 19:13:09 +00002260 // Check argument types.
2261 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2262 ArgIdx != NumArgs; ++ArgIdx) {
2263 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2264 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2265 if (Context.getCanonicalType(FromArgType)
2266 == Context.getCanonicalType(ToArgType)) {
2267 // Okay, the types match exactly. Nothing to do.
2268 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2269 ConvertedType, IncompatibleObjC)) {
2270 // Okay, we have an Objective-C pointer conversion.
2271 HasObjCConversion = true;
2272 } else {
2273 // Argument types are too different. Abort.
2274 return false;
2275 }
2276 }
2277
2278 if (HasObjCConversion) {
2279 // We had an Objective-C conversion. Allow this pointer
2280 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002281 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002282 IncompatibleObjC = true;
2283 return true;
2284 }
2285 }
2286
Sebastian Redl72b597d2009-01-25 19:43:20 +00002287 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002288}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289
John McCall31168b02011-06-15 23:02:42 +00002290/// \brief Determine whether this is an Objective-C writeback conversion,
2291/// used for parameter passing when performing automatic reference counting.
2292///
2293/// \param FromType The type we're converting form.
2294///
2295/// \param ToType The type we're converting to.
2296///
2297/// \param ConvertedType The type that will be produced after applying
2298/// this conversion.
2299bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2300 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002301 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002302 Context.hasSameUnqualifiedType(FromType, ToType))
2303 return false;
2304
2305 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2306 QualType ToPointee;
2307 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2308 ToPointee = ToPointer->getPointeeType();
2309 else
2310 return false;
2311
2312 Qualifiers ToQuals = ToPointee.getQualifiers();
2313 if (!ToPointee->isObjCLifetimeType() ||
2314 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002315 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002316 return false;
2317
2318 // Argument must be a pointer to __strong to __weak.
2319 QualType FromPointee;
2320 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2321 FromPointee = FromPointer->getPointeeType();
2322 else
2323 return false;
2324
2325 Qualifiers FromQuals = FromPointee.getQualifiers();
2326 if (!FromPointee->isObjCLifetimeType() ||
2327 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2328 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2329 return false;
2330
2331 // Make sure that we have compatible qualifiers.
2332 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2333 if (!ToQuals.compatiblyIncludes(FromQuals))
2334 return false;
2335
2336 // Remove qualifiers from the pointee type we're converting from; they
2337 // aren't used in the compatibility check belong, and we'll be adding back
2338 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2339 FromPointee = FromPointee.getUnqualifiedType();
2340
2341 // The unqualified form of the pointee types must be compatible.
2342 ToPointee = ToPointee.getUnqualifiedType();
2343 bool IncompatibleObjC;
2344 if (Context.typesAreCompatible(FromPointee, ToPointee))
2345 FromPointee = ToPointee;
2346 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2347 IncompatibleObjC))
2348 return false;
2349
2350 /// \brief Construct the type we're converting to, which is a pointer to
2351 /// __autoreleasing pointee.
2352 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2353 ConvertedType = Context.getPointerType(FromPointee);
2354 return true;
2355}
2356
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002357bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2358 QualType& ConvertedType) {
2359 QualType ToPointeeType;
2360 if (const BlockPointerType *ToBlockPtr =
2361 ToType->getAs<BlockPointerType>())
2362 ToPointeeType = ToBlockPtr->getPointeeType();
2363 else
2364 return false;
2365
2366 QualType FromPointeeType;
2367 if (const BlockPointerType *FromBlockPtr =
2368 FromType->getAs<BlockPointerType>())
2369 FromPointeeType = FromBlockPtr->getPointeeType();
2370 else
2371 return false;
2372 // We have pointer to blocks, check whether the only
2373 // differences in the argument and result types are in Objective-C
2374 // pointer conversions. If so, we permit the conversion.
2375
2376 const FunctionProtoType *FromFunctionType
2377 = FromPointeeType->getAs<FunctionProtoType>();
2378 const FunctionProtoType *ToFunctionType
2379 = ToPointeeType->getAs<FunctionProtoType>();
2380
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002381 if (!FromFunctionType || !ToFunctionType)
2382 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002383
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002384 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002385 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002386
2387 // Perform the quick checks that will tell us whether these
2388 // function types are obviously different.
2389 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2390 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2391 return false;
2392
2393 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2394 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2395 if (FromEInfo != ToEInfo)
2396 return false;
2397
2398 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002399 if (Context.hasSameType(FromFunctionType->getResultType(),
2400 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002401 // Okay, the types match exactly. Nothing to do.
2402 } else {
2403 QualType RHS = FromFunctionType->getResultType();
2404 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002405 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002406 !RHS.hasQualifiers() && LHS.hasQualifiers())
2407 LHS = LHS.getUnqualifiedType();
2408
2409 if (Context.hasSameType(RHS,LHS)) {
2410 // OK exact match.
2411 } else if (isObjCPointerConversion(RHS, LHS,
2412 ConvertedType, IncompatibleObjC)) {
2413 if (IncompatibleObjC)
2414 return false;
2415 // Okay, we have an Objective-C pointer conversion.
2416 }
2417 else
2418 return false;
2419 }
2420
2421 // Check argument types.
2422 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2423 ArgIdx != NumArgs; ++ArgIdx) {
2424 IncompatibleObjC = false;
2425 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2426 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2427 if (Context.hasSameType(FromArgType, ToArgType)) {
2428 // Okay, the types match exactly. Nothing to do.
2429 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2430 ConvertedType, IncompatibleObjC)) {
2431 if (IncompatibleObjC)
2432 return false;
2433 // Okay, we have an Objective-C pointer conversion.
2434 } else
2435 // Argument types are too different. Abort.
2436 return false;
2437 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002438 if (LangOpts.ObjCAutoRefCount &&
2439 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2440 ToFunctionType))
2441 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002442
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002443 ConvertedType = ToType;
2444 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002445}
2446
Richard Trieucaff2472011-11-23 22:32:32 +00002447enum {
2448 ft_default,
2449 ft_different_class,
2450 ft_parameter_arity,
2451 ft_parameter_mismatch,
2452 ft_return_type,
2453 ft_qualifer_mismatch
2454};
2455
2456/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2457/// function types. Catches different number of parameter, mismatch in
2458/// parameter types, and different return types.
2459void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2460 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002461 // If either type is not valid, include no extra info.
2462 if (FromType.isNull() || ToType.isNull()) {
2463 PDiag << ft_default;
2464 return;
2465 }
2466
Richard Trieucaff2472011-11-23 22:32:32 +00002467 // Get the function type from the pointers.
2468 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2469 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2470 *ToMember = ToType->getAs<MemberPointerType>();
2471 if (FromMember->getClass() != ToMember->getClass()) {
2472 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2473 << QualType(FromMember->getClass(), 0);
2474 return;
2475 }
2476 FromType = FromMember->getPointeeType();
2477 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002478 }
2479
Richard Trieu96ed5b62011-12-13 23:19:45 +00002480 if (FromType->isPointerType())
2481 FromType = FromType->getPointeeType();
2482 if (ToType->isPointerType())
2483 ToType = ToType->getPointeeType();
2484
2485 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002486 FromType = FromType.getNonReferenceType();
2487 ToType = ToType.getNonReferenceType();
2488
Richard Trieucaff2472011-11-23 22:32:32 +00002489 // Don't print extra info for non-specialized template functions.
2490 if (FromType->isInstantiationDependentType() &&
2491 !FromType->getAs<TemplateSpecializationType>()) {
2492 PDiag << ft_default;
2493 return;
2494 }
2495
Richard Trieu96ed5b62011-12-13 23:19:45 +00002496 // No extra info for same types.
2497 if (Context.hasSameType(FromType, ToType)) {
2498 PDiag << ft_default;
2499 return;
2500 }
2501
Richard Trieucaff2472011-11-23 22:32:32 +00002502 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2503 *ToFunction = ToType->getAs<FunctionProtoType>();
2504
2505 // Both types need to be function types.
2506 if (!FromFunction || !ToFunction) {
2507 PDiag << ft_default;
2508 return;
2509 }
2510
2511 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2512 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2513 << FromFunction->getNumArgs();
2514 return;
2515 }
2516
2517 // Handle different parameter types.
2518 unsigned ArgPos;
2519 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2520 PDiag << ft_parameter_mismatch << ArgPos + 1
2521 << ToFunction->getArgType(ArgPos)
2522 << FromFunction->getArgType(ArgPos);
2523 return;
2524 }
2525
2526 // Handle different return type.
2527 if (!Context.hasSameType(FromFunction->getResultType(),
2528 ToFunction->getResultType())) {
2529 PDiag << ft_return_type << ToFunction->getResultType()
2530 << FromFunction->getResultType();
2531 return;
2532 }
2533
2534 unsigned FromQuals = FromFunction->getTypeQuals(),
2535 ToQuals = ToFunction->getTypeQuals();
2536 if (FromQuals != ToQuals) {
2537 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2538 return;
2539 }
2540
2541 // Unable to find a difference, so add no extra info.
2542 PDiag << ft_default;
2543}
2544
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002545/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002546/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002547/// they have same number of arguments. This routine assumes that Objective-C
2548/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002549/// If the parameters are different, ArgPos will have the parameter index
Richard Trieucaff2472011-11-23 22:32:32 +00002550/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002552 const FunctionProtoType *NewType,
2553 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002554 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002555 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2556 N = NewType->arg_type_begin(),
2557 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2558 if (!Context.hasSameType(*O, *N)) {
2559 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2560 return false;
2561 }
2562 }
2563 return true;
2564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002566 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2567 N = NewType->arg_type_begin(),
2568 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2569 QualType ToType = (*O);
2570 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002571 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002572 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2573 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002574 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2575 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2576 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2577 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002578 continue;
2579 }
John McCall8b07ec22010-05-15 11:32:37 +00002580 else if (const ObjCObjectPointerType *PTTo =
2581 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002583 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002584 if (Context.hasSameUnqualifiedType(
2585 PTTo->getObjectType()->getBaseType(),
2586 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002587 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002588 }
Richard Trieucaff2472011-11-23 22:32:32 +00002589 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002591 }
2592 }
2593 return true;
2594}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002595
Douglas Gregor39c16d42008-10-24 04:54:22 +00002596/// CheckPointerConversion - Check the pointer conversion from the
2597/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002598/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002599/// conversions for which IsPointerConversion has already returned
2600/// true. It returns true and produces a diagnostic if there was an
2601/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002602bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002603 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002604 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002605 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002606 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002607 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002608
John McCall8cb679e2010-11-15 09:13:47 +00002609 Kind = CK_BitCast;
2610
David Blaikie1c7c8f72012-08-08 17:33:31 +00002611 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2612 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2613 Expr::NPCK_ZeroExpression) {
2614 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2615 DiagRuntimeBehavior(From->getExprLoc(), From,
2616 PDiag(diag::warn_impcast_bool_to_null_pointer)
2617 << ToType << From->getSourceRange());
2618 else if (!isUnevaluatedContext())
2619 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2620 << ToType << From->getSourceRange();
2621 }
John McCall9320b872011-09-09 05:25:32 +00002622 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2623 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002624 QualType FromPointeeType = FromPtrType->getPointeeType(),
2625 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002626
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002627 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2628 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002629 // We must have a derived-to-base conversion. Check an
2630 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002631 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2632 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002633 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002634 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002635 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002637 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002638 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002639 }
2640 }
John McCall9320b872011-09-09 05:25:32 +00002641 } else if (const ObjCObjectPointerType *ToPtrType =
2642 ToType->getAs<ObjCObjectPointerType>()) {
2643 if (const ObjCObjectPointerType *FromPtrType =
2644 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002645 // Objective-C++ conversions are always okay.
2646 // FIXME: We should have a different class of conversions for the
2647 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002648 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002649 return false;
John McCall9320b872011-09-09 05:25:32 +00002650 } else if (FromType->isBlockPointerType()) {
2651 Kind = CK_BlockPointerToObjCPointerCast;
2652 } else {
2653 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002654 }
John McCall9320b872011-09-09 05:25:32 +00002655 } else if (ToType->isBlockPointerType()) {
2656 if (!FromType->isBlockPointerType())
2657 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002658 }
John McCall8cb679e2010-11-15 09:13:47 +00002659
2660 // We shouldn't fall into this case unless it's valid for other
2661 // reasons.
2662 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2663 Kind = CK_NullToPointer;
2664
Douglas Gregor39c16d42008-10-24 04:54:22 +00002665 return false;
2666}
2667
Sebastian Redl72b597d2009-01-25 19:43:20 +00002668/// IsMemberPointerConversion - Determines whether the conversion of the
2669/// expression From, which has the (possibly adjusted) type FromType, can be
2670/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2671/// If so, returns true and places the converted type (that might differ from
2672/// ToType in its cv-qualifiers at some level) into ConvertedType.
2673bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002675 bool InOverloadResolution,
2676 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002677 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002678 if (!ToTypePtr)
2679 return false;
2680
2681 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002682 if (From->isNullPointerConstant(Context,
2683 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2684 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002685 ConvertedType = ToType;
2686 return true;
2687 }
2688
2689 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002690 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002691 if (!FromTypePtr)
2692 return false;
2693
2694 // A pointer to member of B can be converted to a pointer to member of D,
2695 // where D is derived from B (C++ 4.11p2).
2696 QualType FromClass(FromTypePtr->getClass(), 0);
2697 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002698
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002699 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002700 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002701 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002702 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2703 ToClass.getTypePtr());
2704 return true;
2705 }
2706
2707 return false;
2708}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709
Sebastian Redl72b597d2009-01-25 19:43:20 +00002710/// CheckMemberPointerConversion - Check the member pointer conversion from the
2711/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002712/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002713/// for which IsMemberPointerConversion has already returned true. It returns
2714/// true and produces a diagnostic if there was an error, or returns false
2715/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002716bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002717 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002718 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002719 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002721 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002722 if (!FromPtrType) {
2723 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002724 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002725 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002726 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002727 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002728 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002729 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002730
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002731 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002732 assert(ToPtrType && "No member pointer cast has a target type "
2733 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734
Sebastian Redled8f2002009-01-28 18:33:18 +00002735 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2736 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002737
Sebastian Redled8f2002009-01-28 18:33:18 +00002738 // FIXME: What about dependent types?
2739 assert(FromClass->isRecordType() && "Pointer into non-class.");
2740 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002741
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002743 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002744 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2745 assert(DerivationOkay &&
2746 "Should not have been called if derivation isn't OK.");
2747 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002748
Sebastian Redled8f2002009-01-28 18:33:18 +00002749 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2750 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2752 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2753 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2754 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002755 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002756
Douglas Gregor89ee6822009-02-28 01:32:25 +00002757 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002758 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2759 << FromClass << ToClass << QualType(VBase, 0)
2760 << From->getSourceRange();
2761 return true;
2762 }
2763
John McCall5b0829a2010-02-10 09:31:12 +00002764 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002765 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2766 Paths.front(),
2767 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002768
Anders Carlssond7923c62009-08-22 23:33:40 +00002769 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002770 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002771 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002772 return false;
2773}
2774
Douglas Gregor9a657932008-10-21 23:43:52 +00002775/// IsQualificationConversion - Determines whether the conversion from
2776/// an rvalue of type FromType to ToType is a qualification conversion
2777/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002778///
2779/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2780/// when the qualification conversion involves a change in the Objective-C
2781/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002782bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002784 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002785 FromType = Context.getCanonicalType(FromType);
2786 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002787 ObjCLifetimeConversion = false;
2788
Douglas Gregor9a657932008-10-21 23:43:52 +00002789 // If FromType and ToType are the same type, this is not a
2790 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002791 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002792 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002793
Douglas Gregor9a657932008-10-21 23:43:52 +00002794 // (C++ 4.4p4):
2795 // A conversion can add cv-qualifiers at levels other than the first
2796 // in multi-level pointers, subject to the following rules: [...]
2797 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002798 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002799 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002800 // Within each iteration of the loop, we check the qualifiers to
2801 // determine if this still looks like a qualification
2802 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002803 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002804 // until there are no more pointers or pointers-to-members left to
2805 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002806 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002807
Douglas Gregor90609aa2011-04-25 18:40:17 +00002808 Qualifiers FromQuals = FromType.getQualifiers();
2809 Qualifiers ToQuals = ToType.getQualifiers();
2810
John McCall31168b02011-06-15 23:02:42 +00002811 // Objective-C ARC:
2812 // Check Objective-C lifetime conversions.
2813 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2814 UnwrappedAnyPointer) {
2815 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2816 ObjCLifetimeConversion = true;
2817 FromQuals.removeObjCLifetime();
2818 ToQuals.removeObjCLifetime();
2819 } else {
2820 // Qualification conversions cannot cast between different
2821 // Objective-C lifetime qualifiers.
2822 return false;
2823 }
2824 }
2825
Douglas Gregorf30053d2011-05-08 06:09:53 +00002826 // Allow addition/removal of GC attributes but not changing GC attributes.
2827 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2828 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2829 FromQuals.removeObjCGCAttr();
2830 ToQuals.removeObjCGCAttr();
2831 }
2832
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 // -- for every j > 0, if const is in cv 1,j then const is in cv
2834 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002835 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002836 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002837
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 // -- if the cv 1,j and cv 2,j are different, then const is in
2839 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002840 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002841 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002842 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002843
Douglas Gregor9a657932008-10-21 23:43:52 +00002844 // Keep track of whether all prior cv-qualifiers in the "to" type
2845 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002846 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002847 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002848 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002849
2850 // We are left with FromType and ToType being the pointee types
2851 // after unwrapping the original FromType and ToType the same number
2852 // of types. If we unwrapped any pointers, and if FromType and
2853 // ToType have the same unqualified type (since we checked
2854 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002855 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002856}
2857
Douglas Gregorc79862f2012-04-12 17:51:55 +00002858/// \brief - Determine whether this is a conversion from a scalar type to an
2859/// atomic type.
2860///
2861/// If successful, updates \c SCS's second and third steps in the conversion
2862/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002863static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2864 bool InOverloadResolution,
2865 StandardConversionSequence &SCS,
2866 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002867 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2868 if (!ToAtomic)
2869 return false;
2870
2871 StandardConversionSequence InnerSCS;
2872 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2873 InOverloadResolution, InnerSCS,
2874 CStyle, /*AllowObjCWritebackConversion=*/false))
2875 return false;
2876
2877 SCS.Second = InnerSCS.Second;
2878 SCS.setToType(1, InnerSCS.getToType(1));
2879 SCS.Third = InnerSCS.Third;
2880 SCS.QualificationIncludesObjCLifetime
2881 = InnerSCS.QualificationIncludesObjCLifetime;
2882 SCS.setToType(2, InnerSCS.getToType(2));
2883 return true;
2884}
2885
Sebastian Redle5417162012-03-27 18:33:03 +00002886static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2887 CXXConstructorDecl *Constructor,
2888 QualType Type) {
2889 const FunctionProtoType *CtorType =
2890 Constructor->getType()->getAs<FunctionProtoType>();
2891 if (CtorType->getNumArgs() > 0) {
2892 QualType FirstArg = CtorType->getArgType(0);
2893 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2894 return true;
2895 }
2896 return false;
2897}
2898
Sebastian Redl82ace982012-02-11 23:51:08 +00002899static OverloadingResult
2900IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2901 CXXRecordDecl *To,
2902 UserDefinedConversionSequence &User,
2903 OverloadCandidateSet &CandidateSet,
2904 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002905 DeclContext::lookup_result R = S.LookupConstructors(To);
2906 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002907 Con != ConEnd; ++Con) {
2908 NamedDecl *D = *Con;
2909 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2910
2911 // Find the constructor (which may be a template).
2912 CXXConstructorDecl *Constructor = 0;
2913 FunctionTemplateDecl *ConstructorTmpl
2914 = dyn_cast<FunctionTemplateDecl>(D);
2915 if (ConstructorTmpl)
2916 Constructor
2917 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2918 else
2919 Constructor = cast<CXXConstructorDecl>(D);
2920
2921 bool Usable = !Constructor->isInvalidDecl() &&
2922 S.isInitListConstructor(Constructor) &&
2923 (AllowExplicit || !Constructor->isExplicit());
2924 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002925 // If the first argument is (a reference to) the target type,
2926 // suppress conversions.
2927 bool SuppressUserConversions =
2928 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002929 if (ConstructorTmpl)
2930 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2931 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002932 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002933 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002934 else
2935 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002936 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002937 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002938 }
2939 }
2940
2941 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2942
2943 OverloadCandidateSet::iterator Best;
2944 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2945 case OR_Success: {
2946 // Record the standard conversion we used and the conversion function.
2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002948 QualType ThisType = Constructor->getThisType(S.Context);
2949 // Initializer lists don't have conversions as such.
2950 User.Before.setAsIdentityConversion();
2951 User.HadMultipleCandidates = HadMultipleCandidates;
2952 User.ConversionFunction = Constructor;
2953 User.FoundConversionFunction = Best->FoundDecl;
2954 User.After.setAsIdentityConversion();
2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2956 User.After.setAllToTypes(ToType);
2957 return OR_Success;
2958 }
2959
2960 case OR_No_Viable_Function:
2961 return OR_No_Viable_Function;
2962 case OR_Deleted:
2963 return OR_Deleted;
2964 case OR_Ambiguous:
2965 return OR_Ambiguous;
2966 }
2967
2968 llvm_unreachable("Invalid OverloadResult!");
2969}
2970
Douglas Gregor576e98c2009-01-30 23:27:23 +00002971/// Determines whether there is a user-defined conversion sequence
2972/// (C++ [over.ics.user]) that converts expression From to the type
2973/// ToType. If such a conversion exists, User will contain the
2974/// user-defined conversion sequence that performs such a conversion
2975/// and this routine will return true. Otherwise, this routine returns
2976/// false and User is unspecified.
2977///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002978/// \param AllowExplicit true if the conversion should consider C++0x
2979/// "explicit" conversion functions as well as non-explicit conversion
2980/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002981static OverloadingResult
2982IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002983 UserDefinedConversionSequence &User,
2984 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002985 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002986 // Whether we will only visit constructors.
2987 bool ConstructorsOnly = false;
2988
2989 // If the type we are conversion to is a class type, enumerate its
2990 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002991 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002992 // C++ [over.match.ctor]p1:
2993 // When objects of class type are direct-initialized (8.5), or
2994 // copy-initialized from an expression of the same or a
2995 // derived class type (8.5), overload resolution selects the
2996 // constructor. [...] For copy-initialization, the candidate
2997 // functions are all the converting constructors (12.3.1) of
2998 // that class. The argument list is the expression-list within
2999 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003000 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003001 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003002 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003003 ConstructorsOnly = true;
3004
Benjamin Kramer90633e32012-11-23 17:04:52 +00003005 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003006 // RequireCompleteType may have returned true due to some invalid decl
3007 // during template instantiation, but ToType may be complete enough now
3008 // to try to recover.
3009 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003010 // We're not going to find any constructors.
3011 } else if (CXXRecordDecl *ToRecordDecl
3012 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003013
3014 Expr **Args = &From;
3015 unsigned NumArgs = 1;
3016 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003017 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00003018 // But first, see if there is an init-list-contructor that will work.
3019 OverloadingResult Result = IsInitializerListConstructorConversion(
3020 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3021 if (Result != OR_No_Viable_Function)
3022 return Result;
3023 // Never mind.
3024 CandidateSet.clear();
3025
3026 // If we're list-initializing, we pass the individual elements as
3027 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003028 Args = InitList->getInits();
3029 NumArgs = InitList->getNumInits();
3030 ListInitializing = true;
3031 }
3032
David Blaikieff7d47a2012-12-19 00:45:41 +00003033 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3034 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003035 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003036 NamedDecl *D = *Con;
3037 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3038
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003039 // Find the constructor (which may be a template).
3040 CXXConstructorDecl *Constructor = 0;
3041 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003042 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003043 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003044 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003045 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3046 else
John McCalla0296f72010-03-19 07:35:19 +00003047 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003049 bool Usable = !Constructor->isInvalidDecl();
3050 if (ListInitializing)
3051 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3052 else
3053 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3054 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003055 bool SuppressUserConversions = !ConstructorsOnly;
3056 if (SuppressUserConversions && ListInitializing) {
3057 SuppressUserConversions = false;
3058 if (NumArgs == 1) {
3059 // If the first argument is (a reference to) the target type,
3060 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003061 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3062 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003063 }
3064 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003065 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003066 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3067 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003068 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003069 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003070 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003071 // Allow one user-defined conversion when user specifies a
3072 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003073 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003074 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003075 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003076 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003077 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003078 }
3079 }
3080
Douglas Gregor5ab11652010-04-17 22:01:05 +00003081 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003082 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003083 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003084 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003085 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003087 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003088 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3089 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003090 std::pair<CXXRecordDecl::conversion_iterator,
3091 CXXRecordDecl::conversion_iterator>
3092 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3093 for (CXXRecordDecl::conversion_iterator
3094 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003095 DeclAccessPair FoundDecl = I.getPair();
3096 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003097 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3098 if (isa<UsingShadowDecl>(D))
3099 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3100
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003101 CXXConversionDecl *Conv;
3102 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003103 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3104 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003105 else
John McCallda4458e2010-03-31 01:36:47 +00003106 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003107
3108 if (AllowExplicit || !Conv->isExplicit()) {
3109 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003110 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3111 ActingContext, From, ToType,
3112 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003113 else
John McCall5c32be02010-08-24 20:38:10 +00003114 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3115 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003116 }
3117 }
3118 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003119 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003120
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003121 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3122
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003123 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003124 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003125 case OR_Success:
3126 // Record the standard conversion we used and the conversion function.
3127 if (CXXConstructorDecl *Constructor
3128 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3129 // C++ [over.ics.user]p1:
3130 // If the user-defined conversion is specified by a
3131 // constructor (12.3.1), the initial standard conversion
3132 // sequence converts the source type to the type required by
3133 // the argument of the constructor.
3134 //
3135 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003136 if (isa<InitListExpr>(From)) {
3137 // Initializer lists don't have conversions as such.
3138 User.Before.setAsIdentityConversion();
3139 } else {
3140 if (Best->Conversions[0].isEllipsis())
3141 User.EllipsisConversion = true;
3142 else {
3143 User.Before = Best->Conversions[0].Standard;
3144 User.EllipsisConversion = false;
3145 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003146 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003147 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003148 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003149 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003150 User.After.setAsIdentityConversion();
3151 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3152 User.After.setAllToTypes(ToType);
3153 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003154 }
3155 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003156 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3157 // C++ [over.ics.user]p1:
3158 //
3159 // [...] If the user-defined conversion is specified by a
3160 // conversion function (12.3.2), the initial standard
3161 // conversion sequence converts the source type to the
3162 // implicit object parameter of the conversion function.
3163 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003164 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003165 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003166 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003167 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003168
John McCall5c32be02010-08-24 20:38:10 +00003169 // C++ [over.ics.user]p2:
3170 // The second standard conversion sequence converts the
3171 // result of the user-defined conversion to the target type
3172 // for the sequence. Since an implicit conversion sequence
3173 // is an initialization, the special rules for
3174 // initialization by user-defined conversion apply when
3175 // selecting the best user-defined conversion for a
3176 // user-defined conversion sequence (see 13.3.3 and
3177 // 13.3.3.1).
3178 User.After = Best->FinalConversion;
3179 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003180 }
David Blaikie8a40f702012-01-17 06:56:22 +00003181 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003182
John McCall5c32be02010-08-24 20:38:10 +00003183 case OR_No_Viable_Function:
3184 return OR_No_Viable_Function;
3185 case OR_Deleted:
3186 // No conversion here! We're done.
3187 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
John McCall5c32be02010-08-24 20:38:10 +00003189 case OR_Ambiguous:
3190 return OR_Ambiguous;
3191 }
3192
David Blaikie8a40f702012-01-17 06:56:22 +00003193 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003194}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003196bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003197Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003198 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003199 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003201 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003202 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003203 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003204 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003205 diag::err_typecheck_ambiguous_condition)
3206 << From->getType() << ToType << From->getSourceRange();
3207 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003208 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003209 diag::err_typecheck_nonviable_condition)
3210 << From->getType() << ToType << From->getSourceRange();
3211 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003212 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003215}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003216
Douglas Gregor2837aa22012-02-22 17:32:19 +00003217/// \brief Compare the user-defined conversion functions or constructors
3218/// of two user-defined conversion sequences to determine whether any ordering
3219/// is possible.
3220static ImplicitConversionSequence::CompareKind
3221compareConversionFunctions(Sema &S,
3222 FunctionDecl *Function1,
3223 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003224 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003225 return ImplicitConversionSequence::Indistinguishable;
3226
3227 // Objective-C++:
3228 // If both conversion functions are implicitly-declared conversions from
3229 // a lambda closure type to a function pointer and a block pointer,
3230 // respectively, always prefer the conversion to a function pointer,
3231 // because the function pointer is more lightweight and is more likely
3232 // to keep code working.
3233 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3234 if (!Conv1)
3235 return ImplicitConversionSequence::Indistinguishable;
3236
3237 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3238 if (!Conv2)
3239 return ImplicitConversionSequence::Indistinguishable;
3240
3241 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3242 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3243 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3244 if (Block1 != Block2)
3245 return Block1? ImplicitConversionSequence::Worse
3246 : ImplicitConversionSequence::Better;
3247 }
3248
3249 return ImplicitConversionSequence::Indistinguishable;
3250}
3251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003252/// CompareImplicitConversionSequences - Compare two implicit
3253/// conversion sequences to determine whether one is better than the
3254/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003255static ImplicitConversionSequence::CompareKind
3256CompareImplicitConversionSequences(Sema &S,
3257 const ImplicitConversionSequence& ICS1,
3258 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003259{
3260 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3261 // conversion sequences (as defined in 13.3.3.1)
3262 // -- a standard conversion sequence (13.3.3.1.1) is a better
3263 // conversion sequence than a user-defined conversion sequence or
3264 // an ellipsis conversion sequence, and
3265 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3266 // conversion sequence than an ellipsis conversion sequence
3267 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003268 //
John McCall0d1da222010-01-12 00:44:57 +00003269 // C++0x [over.best.ics]p10:
3270 // For the purpose of ranking implicit conversion sequences as
3271 // described in 13.3.3.2, the ambiguous conversion sequence is
3272 // treated as a user-defined sequence that is indistinguishable
3273 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003274 if (ICS1.getKindRank() < ICS2.getKindRank())
3275 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003276 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003277 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003278
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003279 // The following checks require both conversion sequences to be of
3280 // the same kind.
3281 if (ICS1.getKind() != ICS2.getKind())
3282 return ImplicitConversionSequence::Indistinguishable;
3283
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003284 ImplicitConversionSequence::CompareKind Result =
3285 ImplicitConversionSequence::Indistinguishable;
3286
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003287 // Two implicit conversion sequences of the same form are
3288 // indistinguishable conversion sequences unless one of the
3289 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003290 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003291 Result = CompareStandardConversionSequences(S,
3292 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003293 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003294 // User-defined conversion sequence U1 is a better conversion
3295 // sequence than another user-defined conversion sequence U2 if
3296 // they contain the same user-defined conversion function or
3297 // constructor and if the second standard conversion sequence of
3298 // U1 is better than the second standard conversion sequence of
3299 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003300 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003301 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003302 Result = CompareStandardConversionSequences(S,
3303 ICS1.UserDefined.After,
3304 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003305 else
3306 Result = compareConversionFunctions(S,
3307 ICS1.UserDefined.ConversionFunction,
3308 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003309 }
3310
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003311 // List-initialization sequence L1 is a better conversion sequence than
3312 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3313 // for some X and L2 does not.
3314 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003315 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003316 ICS1.isListInitializationSequence() &&
3317 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003318 if (ICS1.isStdInitializerListElement() &&
3319 !ICS2.isStdInitializerListElement())
3320 return ImplicitConversionSequence::Better;
3321 if (!ICS1.isStdInitializerListElement() &&
3322 ICS2.isStdInitializerListElement())
3323 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003324 }
3325
3326 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003327}
3328
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003329static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3330 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3331 Qualifiers Quals;
3332 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003336 return Context.hasSameUnqualifiedType(T1, T2);
3337}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003338
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003339// Per 13.3.3.2p3, compare the given standard conversion sequences to
3340// determine if one is a proper subset of the other.
3341static ImplicitConversionSequence::CompareKind
3342compareStandardConversionSubsets(ASTContext &Context,
3343 const StandardConversionSequence& SCS1,
3344 const StandardConversionSequence& SCS2) {
3345 ImplicitConversionSequence::CompareKind Result
3346 = ImplicitConversionSequence::Indistinguishable;
3347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003349 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003350 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3351 return ImplicitConversionSequence::Better;
3352 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3353 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003355 if (SCS1.Second != SCS2.Second) {
3356 if (SCS1.Second == ICK_Identity)
3357 Result = ImplicitConversionSequence::Better;
3358 else if (SCS2.Second == ICK_Identity)
3359 Result = ImplicitConversionSequence::Worse;
3360 else
3361 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003362 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003363 return ImplicitConversionSequence::Indistinguishable;
3364
3365 if (SCS1.Third == SCS2.Third) {
3366 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3367 : ImplicitConversionSequence::Indistinguishable;
3368 }
3369
3370 if (SCS1.Third == ICK_Identity)
3371 return Result == ImplicitConversionSequence::Worse
3372 ? ImplicitConversionSequence::Indistinguishable
3373 : ImplicitConversionSequence::Better;
3374
3375 if (SCS2.Third == ICK_Identity)
3376 return Result == ImplicitConversionSequence::Better
3377 ? ImplicitConversionSequence::Indistinguishable
3378 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003380 return ImplicitConversionSequence::Indistinguishable;
3381}
3382
Douglas Gregore696ebb2011-01-26 14:52:12 +00003383/// \brief Determine whether one of the given reference bindings is better
3384/// than the other based on what kind of bindings they are.
3385static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3386 const StandardConversionSequence &SCS2) {
3387 // C++0x [over.ics.rank]p3b4:
3388 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3389 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003391 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003393 // reference*.
3394 //
3395 // FIXME: Rvalue references. We're going rogue with the above edits,
3396 // because the semantics in the current C++0x working paper (N3225 at the
3397 // time of this writing) break the standard definition of std::forward
3398 // and std::reference_wrapper when dealing with references to functions.
3399 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003400 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3401 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3402 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregore696ebb2011-01-26 14:52:12 +00003404 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3405 SCS2.IsLvalueReference) ||
3406 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3407 !SCS2.IsLvalueReference);
3408}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003410/// CompareStandardConversionSequences - Compare two standard
3411/// conversion sequences to determine whether one is better than the
3412/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003413static ImplicitConversionSequence::CompareKind
3414CompareStandardConversionSequences(Sema &S,
3415 const StandardConversionSequence& SCS1,
3416 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003417{
3418 // Standard conversion sequence S1 is a better conversion sequence
3419 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3420
3421 // -- S1 is a proper subsequence of S2 (comparing the conversion
3422 // sequences in the canonical form defined by 13.3.3.1.1,
3423 // excluding any Lvalue Transformation; the identity conversion
3424 // sequence is considered to be a subsequence of any
3425 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003426 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003427 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003428 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003429
3430 // -- the rank of S1 is better than the rank of S2 (by the rules
3431 // defined below), or, if not that,
3432 ImplicitConversionRank Rank1 = SCS1.getRank();
3433 ImplicitConversionRank Rank2 = SCS2.getRank();
3434 if (Rank1 < Rank2)
3435 return ImplicitConversionSequence::Better;
3436 else if (Rank2 < Rank1)
3437 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003438
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003439 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3440 // are indistinguishable unless one of the following rules
3441 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003442
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003443 // A conversion that is not a conversion of a pointer, or
3444 // pointer to member, to bool is better than another conversion
3445 // that is such a conversion.
3446 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3447 return SCS2.isPointerConversionToBool()
3448 ? ImplicitConversionSequence::Better
3449 : ImplicitConversionSequence::Worse;
3450
Douglas Gregor5c407d92008-10-23 00:40:37 +00003451 // C++ [over.ics.rank]p4b2:
3452 //
3453 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003454 // conversion of B* to A* is better than conversion of B* to
3455 // void*, and conversion of A* to void* is better than conversion
3456 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003457 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003458 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003459 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003460 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003461 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3462 // Exactly one of the conversion sequences is a conversion to
3463 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003464 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3465 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003466 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3467 // Neither conversion sequence converts to a void pointer; compare
3468 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003469 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003470 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003471 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003472 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3473 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003474 // Both conversion sequences are conversions to void
3475 // pointers. Compare the source types to determine if there's an
3476 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003477 QualType FromType1 = SCS1.getFromType();
3478 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003479
3480 // Adjust the types we're converting from via the array-to-pointer
3481 // conversion, if we need to.
3482 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003483 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003484 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003485 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003486
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003487 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3488 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003489
John McCall5c32be02010-08-24 20:38:10 +00003490 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003491 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003492 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003493 return ImplicitConversionSequence::Worse;
3494
3495 // Objective-C++: If one interface is more specific than the
3496 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003497 const ObjCObjectPointerType* FromObjCPtr1
3498 = FromType1->getAs<ObjCObjectPointerType>();
3499 const ObjCObjectPointerType* FromObjCPtr2
3500 = FromType2->getAs<ObjCObjectPointerType>();
3501 if (FromObjCPtr1 && FromObjCPtr2) {
3502 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3503 FromObjCPtr2);
3504 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3505 FromObjCPtr1);
3506 if (AssignLeft != AssignRight) {
3507 return AssignLeft? ImplicitConversionSequence::Better
3508 : ImplicitConversionSequence::Worse;
3509 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003510 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003511 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003512
3513 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3514 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003515 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003516 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003517 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003518
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003519 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003520 // Check for a better reference binding based on the kind of bindings.
3521 if (isBetterReferenceBindingKind(SCS1, SCS2))
3522 return ImplicitConversionSequence::Better;
3523 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3524 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Sebastian Redlb28b4072009-03-22 23:49:27 +00003526 // C++ [over.ics.rank]p3b4:
3527 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3528 // which the references refer are the same type except for
3529 // top-level cv-qualifiers, and the type to which the reference
3530 // initialized by S2 refers is more cv-qualified than the type
3531 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003532 QualType T1 = SCS1.getToType(2);
3533 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003534 T1 = S.Context.getCanonicalType(T1);
3535 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003536 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003539 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003540 // Objective-C++ ARC: If the references refer to objects with different
3541 // lifetimes, prefer bindings that don't change lifetime.
3542 if (SCS1.ObjCLifetimeConversionBinding !=
3543 SCS2.ObjCLifetimeConversionBinding) {
3544 return SCS1.ObjCLifetimeConversionBinding
3545 ? ImplicitConversionSequence::Worse
3546 : ImplicitConversionSequence::Better;
3547 }
3548
Chandler Carruth8e543b32010-12-12 08:17:55 +00003549 // If the type is an array type, promote the element qualifiers to the
3550 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003551 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003553 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003555 if (T2.isMoreQualifiedThan(T1))
3556 return ImplicitConversionSequence::Better;
3557 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003558 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003559 }
3560 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003561
Francois Pichet08d2fa02011-09-18 21:37:37 +00003562 // In Microsoft mode, prefer an integral conversion to a
3563 // floating-to-integral conversion if the integral conversion
3564 // is between types of the same size.
3565 // For example:
3566 // void f(float);
3567 // void f(int);
3568 // int main {
3569 // long a;
3570 // f(a);
3571 // }
3572 // Here, MSVC will call f(int) instead of generating a compile error
3573 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003574 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003575 SCS1.Second == ICK_Integral_Conversion &&
3576 SCS2.Second == ICK_Floating_Integral &&
3577 S.Context.getTypeSize(SCS1.getFromType()) ==
3578 S.Context.getTypeSize(SCS1.getToType(2)))
3579 return ImplicitConversionSequence::Better;
3580
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003581 return ImplicitConversionSequence::Indistinguishable;
3582}
3583
3584/// CompareQualificationConversions - Compares two standard conversion
3585/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003586/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3587ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003588CompareQualificationConversions(Sema &S,
3589 const StandardConversionSequence& SCS1,
3590 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003591 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003592 // -- S1 and S2 differ only in their qualification conversion and
3593 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3594 // cv-qualification signature of type T1 is a proper subset of
3595 // the cv-qualification signature of type T2, and S1 is not the
3596 // deprecated string literal array-to-pointer conversion (4.2).
3597 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3598 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3599 return ImplicitConversionSequence::Indistinguishable;
3600
3601 // FIXME: the example in the standard doesn't use a qualification
3602 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003603 QualType T1 = SCS1.getToType(2);
3604 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003605 T1 = S.Context.getCanonicalType(T1);
3606 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003607 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003608 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3609 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003610
3611 // If the types are the same, we won't learn anything by unwrapped
3612 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003613 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003614 return ImplicitConversionSequence::Indistinguishable;
3615
Chandler Carruth607f38e2009-12-29 07:16:59 +00003616 // If the type is an array type, promote the element qualifiers to the type
3617 // for comparison.
3618 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003619 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003620 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003621 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003622
Mike Stump11289f42009-09-09 15:08:12 +00003623 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003624 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003625
3626 // Objective-C++ ARC:
3627 // Prefer qualification conversions not involving a change in lifetime
3628 // to qualification conversions that do not change lifetime.
3629 if (SCS1.QualificationIncludesObjCLifetime !=
3630 SCS2.QualificationIncludesObjCLifetime) {
3631 Result = SCS1.QualificationIncludesObjCLifetime
3632 ? ImplicitConversionSequence::Worse
3633 : ImplicitConversionSequence::Better;
3634 }
3635
John McCall5c32be02010-08-24 20:38:10 +00003636 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003637 // Within each iteration of the loop, we check the qualifiers to
3638 // determine if this still looks like a qualification
3639 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003640 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003641 // until there are no more pointers or pointers-to-members left
3642 // to unwrap. This essentially mimics what
3643 // IsQualificationConversion does, but here we're checking for a
3644 // strict subset of qualifiers.
3645 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3646 // The qualifiers are the same, so this doesn't tell us anything
3647 // about how the sequences rank.
3648 ;
3649 else if (T2.isMoreQualifiedThan(T1)) {
3650 // T1 has fewer qualifiers, so it could be the better sequence.
3651 if (Result == ImplicitConversionSequence::Worse)
3652 // Neither has qualifiers that are a subset of the other's
3653 // qualifiers.
3654 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003655
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003656 Result = ImplicitConversionSequence::Better;
3657 } else if (T1.isMoreQualifiedThan(T2)) {
3658 // T2 has fewer qualifiers, so it could be the better sequence.
3659 if (Result == ImplicitConversionSequence::Better)
3660 // Neither has qualifiers that are a subset of the other's
3661 // qualifiers.
3662 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003663
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664 Result = ImplicitConversionSequence::Worse;
3665 } else {
3666 // Qualifiers are disjoint.
3667 return ImplicitConversionSequence::Indistinguishable;
3668 }
3669
3670 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003671 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003672 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003673 }
3674
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003675 // Check that the winning standard conversion sequence isn't using
3676 // the deprecated string literal array to pointer conversion.
3677 switch (Result) {
3678 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003679 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003680 Result = ImplicitConversionSequence::Indistinguishable;
3681 break;
3682
3683 case ImplicitConversionSequence::Indistinguishable:
3684 break;
3685
3686 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003687 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003688 Result = ImplicitConversionSequence::Indistinguishable;
3689 break;
3690 }
3691
3692 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003693}
3694
Douglas Gregor5c407d92008-10-23 00:40:37 +00003695/// CompareDerivedToBaseConversions - Compares two standard conversion
3696/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003697/// various kinds of derived-to-base conversions (C++
3698/// [over.ics.rank]p4b3). As part of these checks, we also look at
3699/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003700ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003701CompareDerivedToBaseConversions(Sema &S,
3702 const StandardConversionSequence& SCS1,
3703 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003704 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003705 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003706 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003707 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003708
3709 // Adjust the types we're converting from via the array-to-pointer
3710 // conversion, if we need to.
3711 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003712 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003713 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003714 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003715
3716 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003717 FromType1 = S.Context.getCanonicalType(FromType1);
3718 ToType1 = S.Context.getCanonicalType(ToType1);
3719 FromType2 = S.Context.getCanonicalType(FromType2);
3720 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003721
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003722 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003723 //
3724 // If class B is derived directly or indirectly from class A and
3725 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003726 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003727 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003728 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003729 SCS2.Second == ICK_Pointer_Conversion &&
3730 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3731 FromType1->isPointerType() && FromType2->isPointerType() &&
3732 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003733 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003734 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003735 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003736 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003737 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003738 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003739 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003740 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003741
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003742 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003743 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003744 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003745 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003746 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003747 return ImplicitConversionSequence::Worse;
3748 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003749
3750 // -- conversion of B* to A* is better than conversion of C* to A*,
3751 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003752 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003753 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003754 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003755 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003756 }
3757 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3758 SCS2.Second == ICK_Pointer_Conversion) {
3759 const ObjCObjectPointerType *FromPtr1
3760 = FromType1->getAs<ObjCObjectPointerType>();
3761 const ObjCObjectPointerType *FromPtr2
3762 = FromType2->getAs<ObjCObjectPointerType>();
3763 const ObjCObjectPointerType *ToPtr1
3764 = ToType1->getAs<ObjCObjectPointerType>();
3765 const ObjCObjectPointerType *ToPtr2
3766 = ToType2->getAs<ObjCObjectPointerType>();
3767
3768 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3769 // Apply the same conversion ranking rules for Objective-C pointer types
3770 // that we do for C++ pointers to class types. However, we employ the
3771 // Objective-C pseudo-subtyping relationship used for assignment of
3772 // Objective-C pointer types.
3773 bool FromAssignLeft
3774 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3775 bool FromAssignRight
3776 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3777 bool ToAssignLeft
3778 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3779 bool ToAssignRight
3780 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3781
3782 // A conversion to an a non-id object pointer type or qualified 'id'
3783 // type is better than a conversion to 'id'.
3784 if (ToPtr1->isObjCIdType() &&
3785 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3786 return ImplicitConversionSequence::Worse;
3787 if (ToPtr2->isObjCIdType() &&
3788 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3789 return ImplicitConversionSequence::Better;
3790
3791 // A conversion to a non-id object pointer type is better than a
3792 // conversion to a qualified 'id' type
3793 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3794 return ImplicitConversionSequence::Worse;
3795 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3796 return ImplicitConversionSequence::Better;
3797
3798 // A conversion to an a non-Class object pointer type or qualified 'Class'
3799 // type is better than a conversion to 'Class'.
3800 if (ToPtr1->isObjCClassType() &&
3801 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3802 return ImplicitConversionSequence::Worse;
3803 if (ToPtr2->isObjCClassType() &&
3804 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3805 return ImplicitConversionSequence::Better;
3806
3807 // A conversion to a non-Class object pointer type is better than a
3808 // conversion to a qualified 'Class' type.
3809 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3810 return ImplicitConversionSequence::Worse;
3811 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3812 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003813
Douglas Gregor058d3de2011-01-31 18:51:41 +00003814 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3815 if (S.Context.hasSameType(FromType1, FromType2) &&
3816 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3817 (ToAssignLeft != ToAssignRight))
3818 return ToAssignLeft? ImplicitConversionSequence::Worse
3819 : ImplicitConversionSequence::Better;
3820
3821 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3822 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3823 (FromAssignLeft != FromAssignRight))
3824 return FromAssignLeft? ImplicitConversionSequence::Better
3825 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003826 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003827 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003828
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003829 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003830 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3831 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3832 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003834 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003836 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003838 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003840 ToType2->getAs<MemberPointerType>();
3841 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3842 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3843 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3844 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3845 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3846 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3847 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3848 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003849 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003850 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003851 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003852 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003853 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003854 return ImplicitConversionSequence::Better;
3855 }
3856 // conversion of B::* to C::* is better than conversion of A::* to C::*
3857 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003858 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003859 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003860 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003861 return ImplicitConversionSequence::Worse;
3862 }
3863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864
Douglas Gregor5ab11652010-04-17 22:01:05 +00003865 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003866 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003867 // -- binding of an expression of type C to a reference of type
3868 // B& is better than binding an expression of type C to a
3869 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003870 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3871 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3872 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003873 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003874 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003875 return ImplicitConversionSequence::Worse;
3876 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003877
Douglas Gregor2fe98832008-11-03 19:09:14 +00003878 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003879 // -- binding of an expression of type B to a reference of type
3880 // A& is better than binding an expression of type C to a
3881 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003882 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3883 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3884 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003885 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003886 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003887 return ImplicitConversionSequence::Worse;
3888 }
3889 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003890
Douglas Gregor5c407d92008-10-23 00:40:37 +00003891 return ImplicitConversionSequence::Indistinguishable;
3892}
3893
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003894/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3895/// determine whether they are reference-related,
3896/// reference-compatible, reference-compatible with added
3897/// qualification, or incompatible, for use in C++ initialization by
3898/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3899/// type, and the first type (T1) is the pointee type of the reference
3900/// type being initialized.
3901Sema::ReferenceCompareResult
3902Sema::CompareReferenceRelationship(SourceLocation Loc,
3903 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003904 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003905 bool &ObjCConversion,
3906 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003907 assert(!OrigT1->isReferenceType() &&
3908 "T1 must be the pointee type of the reference type");
3909 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3910
3911 QualType T1 = Context.getCanonicalType(OrigT1);
3912 QualType T2 = Context.getCanonicalType(OrigT2);
3913 Qualifiers T1Quals, T2Quals;
3914 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3915 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3916
3917 // C++ [dcl.init.ref]p4:
3918 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3919 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3920 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003921 DerivedToBase = false;
3922 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003923 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003924 if (UnqualT1 == UnqualT2) {
3925 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003926 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003927 IsDerivedFrom(UnqualT2, UnqualT1))
3928 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003929 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3930 UnqualT2->isObjCObjectOrInterfaceType() &&
3931 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3932 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003933 else
3934 return Ref_Incompatible;
3935
3936 // At this point, we know that T1 and T2 are reference-related (at
3937 // least).
3938
3939 // If the type is an array type, promote the element qualifiers to the type
3940 // for comparison.
3941 if (isa<ArrayType>(T1) && T1Quals)
3942 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3943 if (isa<ArrayType>(T2) && T2Quals)
3944 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3945
3946 // C++ [dcl.init.ref]p4:
3947 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3948 // reference-related to T2 and cv1 is the same cv-qualification
3949 // as, or greater cv-qualification than, cv2. For purposes of
3950 // overload resolution, cases for which cv1 is greater
3951 // cv-qualification than cv2 are identified as
3952 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003953 //
3954 // Note that we also require equivalence of Objective-C GC and address-space
3955 // qualifiers when performing these computations, so that e.g., an int in
3956 // address space 1 is not reference-compatible with an int in address
3957 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003958 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3959 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3960 T1Quals.removeObjCLifetime();
3961 T2Quals.removeObjCLifetime();
3962 ObjCLifetimeConversion = true;
3963 }
3964
Douglas Gregord517d552011-04-28 17:56:11 +00003965 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003966 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003967 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003968 return Ref_Compatible_With_Added_Qualification;
3969 else
3970 return Ref_Related;
3971}
3972
Douglas Gregor836a7e82010-08-11 02:15:33 +00003973/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003974/// with DeclType. Return true if something definite is found.
3975static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003976FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3977 QualType DeclType, SourceLocation DeclLoc,
3978 Expr *Init, QualType T2, bool AllowRvalues,
3979 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003980 assert(T2->isRecordType() && "Can only find conversions of record types.");
3981 CXXRecordDecl *T2RecordDecl
3982 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3983
3984 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003985 std::pair<CXXRecordDecl::conversion_iterator,
3986 CXXRecordDecl::conversion_iterator>
3987 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3988 for (CXXRecordDecl::conversion_iterator
3989 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003990 NamedDecl *D = *I;
3991 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3992 if (isa<UsingShadowDecl>(D))
3993 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3994
3995 FunctionTemplateDecl *ConvTemplate
3996 = dyn_cast<FunctionTemplateDecl>(D);
3997 CXXConversionDecl *Conv;
3998 if (ConvTemplate)
3999 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4000 else
4001 Conv = cast<CXXConversionDecl>(D);
4002
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004004 // explicit conversions, skip it.
4005 if (!AllowExplicit && Conv->isExplicit())
4006 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007
Douglas Gregor836a7e82010-08-11 02:15:33 +00004008 if (AllowRvalues) {
4009 bool DerivedToBase = false;
4010 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004011 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004012
4013 // If we are initializing an rvalue reference, don't permit conversion
4014 // functions that return lvalues.
4015 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4016 const ReferenceType *RefType
4017 = Conv->getConversionType()->getAs<LValueReferenceType>();
4018 if (RefType && !RefType->getPointeeType()->isFunctionType())
4019 continue;
4020 }
4021
Douglas Gregor836a7e82010-08-11 02:15:33 +00004022 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004023 S.CompareReferenceRelationship(
4024 DeclLoc,
4025 Conv->getConversionType().getNonReferenceType()
4026 .getUnqualifiedType(),
4027 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004028 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004029 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004030 continue;
4031 } else {
4032 // If the conversion function doesn't return a reference type,
4033 // it can't be considered for this conversion. An rvalue reference
4034 // is only acceptable if its referencee is a function type.
4035
4036 const ReferenceType *RefType =
4037 Conv->getConversionType()->getAs<ReferenceType>();
4038 if (!RefType ||
4039 (!RefType->isLValueReferenceType() &&
4040 !RefType->getPointeeType()->isFunctionType()))
4041 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043
Douglas Gregor836a7e82010-08-11 02:15:33 +00004044 if (ConvTemplate)
4045 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004046 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004047 else
4048 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004049 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00004050 }
4051
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004052 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4053
Sebastian Redld92badf2010-06-30 18:13:39 +00004054 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004055 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004056 case OR_Success:
4057 // C++ [over.ics.ref]p1:
4058 //
4059 // [...] If the parameter binds directly to the result of
4060 // applying a conversion function to the argument
4061 // expression, the implicit conversion sequence is a
4062 // user-defined conversion sequence (13.3.3.1.2), with the
4063 // second standard conversion sequence either an identity
4064 // conversion or, if the conversion function returns an
4065 // entity of a type that is a derived class of the parameter
4066 // type, a derived-to-base Conversion.
4067 if (!Best->FinalConversion.DirectBinding)
4068 return false;
4069
4070 ICS.setUserDefined();
4071 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4072 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004073 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004074 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004075 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004076 ICS.UserDefined.EllipsisConversion = false;
4077 assert(ICS.UserDefined.After.ReferenceBinding &&
4078 ICS.UserDefined.After.DirectBinding &&
4079 "Expected a direct reference binding!");
4080 return true;
4081
4082 case OR_Ambiguous:
4083 ICS.setAmbiguous();
4084 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4085 Cand != CandidateSet.end(); ++Cand)
4086 if (Cand->Viable)
4087 ICS.Ambiguous.addConversion(Cand->Function);
4088 return true;
4089
4090 case OR_No_Viable_Function:
4091 case OR_Deleted:
4092 // There was no suitable conversion, or we found a deleted
4093 // conversion; continue with other checks.
4094 return false;
4095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
David Blaikie8a40f702012-01-17 06:56:22 +00004097 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004098}
4099
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004100/// \brief Compute an implicit conversion sequence for reference
4101/// initialization.
4102static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004103TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004104 SourceLocation DeclLoc,
4105 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004106 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004107 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4108
4109 // Most paths end in a failed conversion.
4110 ImplicitConversionSequence ICS;
4111 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4112
4113 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4114 QualType T2 = Init->getType();
4115
4116 // If the initializer is the address of an overloaded function, try
4117 // to resolve the overloaded function. If all goes well, T2 is the
4118 // type of the resulting function.
4119 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4120 DeclAccessPair Found;
4121 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4122 false, Found))
4123 T2 = Fn->getType();
4124 }
4125
4126 // Compute some basic properties of the types and the initializer.
4127 bool isRValRef = DeclType->isRValueReferenceType();
4128 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004129 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004130 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004131 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004132 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004133 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004134 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004135
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004136
Sebastian Redld92badf2010-06-30 18:13:39 +00004137 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004138 // A reference to type "cv1 T1" is initialized by an expression
4139 // of type "cv2 T2" as follows:
4140
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004142 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004143 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4144 // reference-compatible with "cv2 T2," or
4145 //
4146 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4147 if (InitCategory.isLValue() &&
4148 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004149 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004150 // When a parameter of reference type binds directly (8.5.3)
4151 // to an argument expression, the implicit conversion sequence
4152 // is the identity conversion, unless the argument expression
4153 // has a type that is a derived class of the parameter type,
4154 // in which case the implicit conversion sequence is a
4155 // derived-to-base Conversion (13.3.3.1).
4156 ICS.setStandard();
4157 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004158 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4159 : ObjCConversion? ICK_Compatible_Conversion
4160 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004161 ICS.Standard.Third = ICK_Identity;
4162 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4163 ICS.Standard.setToType(0, T2);
4164 ICS.Standard.setToType(1, T1);
4165 ICS.Standard.setToType(2, T1);
4166 ICS.Standard.ReferenceBinding = true;
4167 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004168 ICS.Standard.IsLvalueReference = !isRValRef;
4169 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4170 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004171 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004172 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004173 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004174
Sebastian Redld92badf2010-06-30 18:13:39 +00004175 // Nothing more to do: the inaccessibility/ambiguity check for
4176 // derived-to-base conversions is suppressed when we're
4177 // computing the implicit conversion sequence (C++
4178 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004179 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004180 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004181
Sebastian Redld92badf2010-06-30 18:13:39 +00004182 // -- has a class type (i.e., T2 is a class type), where T1 is
4183 // not reference-related to T2, and can be implicitly
4184 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4185 // is reference-compatible with "cv3 T3" 92) (this
4186 // conversion is selected by enumerating the applicable
4187 // conversion functions (13.3.1.6) and choosing the best
4188 // one through overload resolution (13.3)),
4189 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004191 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004192 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4193 Init, T2, /*AllowRvalues=*/false,
4194 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004195 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004196 }
4197 }
4198
Sebastian Redld92badf2010-06-30 18:13:39 +00004199 // -- Otherwise, the reference shall be an lvalue reference to a
4200 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004201 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004203 // We actually handle one oddity of C++ [over.ics.ref] at this
4204 // point, which is that, due to p2 (which short-circuits reference
4205 // binding by only attempting a simple conversion for non-direct
4206 // bindings) and p3's strange wording, we allow a const volatile
4207 // reference to bind to an rvalue. Hence the check for the presence
4208 // of "const" rather than checking for "const" being the only
4209 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004210 // This is also the point where rvalue references and lvalue inits no longer
4211 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004212 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004213 return ICS;
4214
Douglas Gregorf143cd52011-01-24 16:14:37 +00004215 // -- If the initializer expression
4216 //
4217 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004218 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004219 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4220 (InitCategory.isXValue() ||
4221 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4222 (InitCategory.isLValue() && T2->isFunctionType()))) {
4223 ICS.setStandard();
4224 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004226 : ObjCConversion? ICK_Compatible_Conversion
4227 : ICK_Identity;
4228 ICS.Standard.Third = ICK_Identity;
4229 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4230 ICS.Standard.setToType(0, T2);
4231 ICS.Standard.setToType(1, T1);
4232 ICS.Standard.setToType(2, T1);
4233 ICS.Standard.ReferenceBinding = true;
4234 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4235 // binding unless we're binding to a class prvalue.
4236 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4237 // allow the use of rvalue references in C++98/03 for the benefit of
4238 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004240 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004241 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004242 ICS.Standard.IsLvalueReference = !isRValRef;
4243 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004245 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004246 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004247 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
Douglas Gregorf143cd52011-01-24 16:14:37 +00004251 // -- has a class type (i.e., T2 is a class type), where T1 is not
4252 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253 // an xvalue, class prvalue, or function lvalue of type
4254 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004255 // "cv3 T3",
4256 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004258 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004260 // class subobject).
4261 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004263 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4264 Init, T2, /*AllowRvalues=*/true,
4265 AllowExplicit)) {
4266 // In the second case, if the reference is an rvalue reference
4267 // and the second standard conversion sequence of the
4268 // user-defined conversion sequence includes an lvalue-to-rvalue
4269 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004271 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4272 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4273
Douglas Gregor95273c32011-01-21 16:36:05 +00004274 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004277 // -- Otherwise, a temporary of type "cv1 T1" is created and
4278 // initialized from the initializer expression using the
4279 // rules for a non-reference copy initialization (8.5). The
4280 // reference is then bound to the temporary. If T1 is
4281 // reference-related to T2, cv1 must be the same
4282 // cv-qualification as, or greater cv-qualification than,
4283 // cv2; otherwise, the program is ill-formed.
4284 if (RefRelationship == Sema::Ref_Related) {
4285 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4286 // we would be reference-compatible or reference-compatible with
4287 // added qualification. But that wasn't the case, so the reference
4288 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004289 //
4290 // Note that we only want to check address spaces and cvr-qualifiers here.
4291 // ObjC GC and lifetime qualifiers aren't important.
4292 Qualifiers T1Quals = T1.getQualifiers();
4293 Qualifiers T2Quals = T2.getQualifiers();
4294 T1Quals.removeObjCGCAttr();
4295 T1Quals.removeObjCLifetime();
4296 T2Quals.removeObjCGCAttr();
4297 T2Quals.removeObjCLifetime();
4298 if (!T1Quals.compatiblyIncludes(T2Quals))
4299 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 }
4301
4302 // If at least one of the types is a class type, the types are not
4303 // related, and we aren't allowed any user conversions, the
4304 // reference binding fails. This case is important for breaking
4305 // recursion, since TryImplicitConversion below will attempt to
4306 // create a temporary through the use of a copy constructor.
4307 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4308 (T1->isRecordType() || T2->isRecordType()))
4309 return ICS;
4310
Douglas Gregorcba72b12011-01-21 05:18:22 +00004311 // If T1 is reference-related to T2 and the reference is an rvalue
4312 // reference, the initializer expression shall not be an lvalue.
4313 if (RefRelationship >= Sema::Ref_Related &&
4314 isRValRef && Init->Classify(S.Context).isLValue())
4315 return ICS;
4316
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004317 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004318 // When a parameter of reference type is not bound directly to
4319 // an argument expression, the conversion sequence is the one
4320 // required to convert the argument expression to the
4321 // underlying type of the reference according to
4322 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4323 // to copy-initializing a temporary of the underlying type with
4324 // the argument expression. Any difference in top-level
4325 // cv-qualification is subsumed by the initialization itself
4326 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004327 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4328 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004329 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004330 /*CStyle=*/false,
4331 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004332
4333 // Of course, that's still a reference binding.
4334 if (ICS.isStandard()) {
4335 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004336 ICS.Standard.IsLvalueReference = !isRValRef;
4337 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4338 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004339 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004340 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004341 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004342 // Don't allow rvalue references to bind to lvalues.
4343 if (DeclType->isRValueReferenceType()) {
4344 if (const ReferenceType *RefType
4345 = ICS.UserDefined.ConversionFunction->getResultType()
4346 ->getAs<LValueReferenceType>()) {
4347 if (!RefType->getPointeeType()->isFunctionType()) {
4348 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4349 DeclType);
4350 return ICS;
4351 }
4352 }
4353 }
4354
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004355 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004356 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4357 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4358 ICS.UserDefined.After.BindsToRvalue = true;
4359 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4360 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004361 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004362
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004363 return ICS;
4364}
4365
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004366static ImplicitConversionSequence
4367TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4368 bool SuppressUserConversions,
4369 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004370 bool AllowObjCWritebackConversion,
4371 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004372
4373/// TryListConversion - Try to copy-initialize a value of type ToType from the
4374/// initializer list From.
4375static ImplicitConversionSequence
4376TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4377 bool SuppressUserConversions,
4378 bool InOverloadResolution,
4379 bool AllowObjCWritebackConversion) {
4380 // C++11 [over.ics.list]p1:
4381 // When an argument is an initializer list, it is not an expression and
4382 // special rules apply for converting it to a parameter type.
4383
4384 ImplicitConversionSequence Result;
4385 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004386 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004387
Sebastian Redl09edce02012-01-23 22:09:39 +00004388 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004389 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004390 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004391 return Result;
4392
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004393 // C++11 [over.ics.list]p2:
4394 // If the parameter type is std::initializer_list<X> or "array of X" and
4395 // all the elements can be implicitly converted to X, the implicit
4396 // conversion sequence is the worst conversion necessary to convert an
4397 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004398 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004399 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004400 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004401 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004402 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004403 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004404 if (!X.isNull()) {
4405 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4406 Expr *Init = From->getInit(i);
4407 ImplicitConversionSequence ICS =
4408 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4409 InOverloadResolution,
4410 AllowObjCWritebackConversion);
4411 // If a single element isn't convertible, fail.
4412 if (ICS.isBad()) {
4413 Result = ICS;
4414 break;
4415 }
4416 // Otherwise, look for the worst conversion.
4417 if (Result.isBad() ||
4418 CompareImplicitConversionSequences(S, ICS, Result) ==
4419 ImplicitConversionSequence::Worse)
4420 Result = ICS;
4421 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004422
4423 // For an empty list, we won't have computed any conversion sequence.
4424 // Introduce the identity conversion sequence.
4425 if (From->getNumInits() == 0) {
4426 Result.setStandard();
4427 Result.Standard.setAsIdentityConversion();
4428 Result.Standard.setFromType(ToType);
4429 Result.Standard.setAllToTypes(ToType);
4430 }
4431
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004432 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004433 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004434 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004435 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004436
4437 // C++11 [over.ics.list]p3:
4438 // Otherwise, if the parameter is a non-aggregate class X and overload
4439 // resolution chooses a single best constructor [...] the implicit
4440 // conversion sequence is a user-defined conversion sequence. If multiple
4441 // constructors are viable but none is better than the others, the
4442 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004443 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4444 // This function can deal with initializer lists.
4445 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4446 /*AllowExplicit=*/false,
4447 InOverloadResolution, /*CStyle=*/false,
4448 AllowObjCWritebackConversion);
4449 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004450 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004451 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004452
4453 // C++11 [over.ics.list]p4:
4454 // Otherwise, if the parameter has an aggregate type which can be
4455 // initialized from the initializer list [...] the implicit conversion
4456 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004457 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004458 // Type is an aggregate, argument is an init list. At this point it comes
4459 // down to checking whether the initialization works.
4460 // FIXME: Find out whether this parameter is consumed or not.
4461 InitializedEntity Entity =
4462 InitializedEntity::InitializeParameter(S.Context, ToType,
4463 /*Consumed=*/false);
4464 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4465 Result.setUserDefined();
4466 Result.UserDefined.Before.setAsIdentityConversion();
4467 // Initializer lists don't have a type.
4468 Result.UserDefined.Before.setFromType(QualType());
4469 Result.UserDefined.Before.setAllToTypes(QualType());
4470
4471 Result.UserDefined.After.setAsIdentityConversion();
4472 Result.UserDefined.After.setFromType(ToType);
4473 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004474 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004475 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004476 return Result;
4477 }
4478
4479 // C++11 [over.ics.list]p5:
4480 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004481 if (ToType->isReferenceType()) {
4482 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4483 // mention initializer lists in any way. So we go by what list-
4484 // initialization would do and try to extrapolate from that.
4485
4486 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4487
4488 // If the initializer list has a single element that is reference-related
4489 // to the parameter type, we initialize the reference from that.
4490 if (From->getNumInits() == 1) {
4491 Expr *Init = From->getInit(0);
4492
4493 QualType T2 = Init->getType();
4494
4495 // If the initializer is the address of an overloaded function, try
4496 // to resolve the overloaded function. If all goes well, T2 is the
4497 // type of the resulting function.
4498 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4499 DeclAccessPair Found;
4500 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4501 Init, ToType, false, Found))
4502 T2 = Fn->getType();
4503 }
4504
4505 // Compute some basic properties of the types and the initializer.
4506 bool dummy1 = false;
4507 bool dummy2 = false;
4508 bool dummy3 = false;
4509 Sema::ReferenceCompareResult RefRelationship
4510 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4511 dummy2, dummy3);
4512
4513 if (RefRelationship >= Sema::Ref_Related)
4514 return TryReferenceInit(S, Init, ToType,
4515 /*FIXME:*/From->getLocStart(),
4516 SuppressUserConversions,
4517 /*AllowExplicit=*/false);
4518 }
4519
4520 // Otherwise, we bind the reference to a temporary created from the
4521 // initializer list.
4522 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4523 InOverloadResolution,
4524 AllowObjCWritebackConversion);
4525 if (Result.isFailure())
4526 return Result;
4527 assert(!Result.isEllipsis() &&
4528 "Sub-initialization cannot result in ellipsis conversion.");
4529
4530 // Can we even bind to a temporary?
4531 if (ToType->isRValueReferenceType() ||
4532 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4533 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4534 Result.UserDefined.After;
4535 SCS.ReferenceBinding = true;
4536 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4537 SCS.BindsToRvalue = true;
4538 SCS.BindsToFunctionLvalue = false;
4539 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4540 SCS.ObjCLifetimeConversionBinding = false;
4541 } else
4542 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4543 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004544 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004545 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004546
4547 // C++11 [over.ics.list]p6:
4548 // Otherwise, if the parameter type is not a class:
4549 if (!ToType->isRecordType()) {
4550 // - if the initializer list has one element, the implicit conversion
4551 // sequence is the one required to convert the element to the
4552 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004553 unsigned NumInits = From->getNumInits();
4554 if (NumInits == 1)
4555 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4556 SuppressUserConversions,
4557 InOverloadResolution,
4558 AllowObjCWritebackConversion);
4559 // - if the initializer list has no elements, the implicit conversion
4560 // sequence is the identity conversion.
4561 else if (NumInits == 0) {
4562 Result.setStandard();
4563 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004564 Result.Standard.setFromType(ToType);
4565 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004566 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004567 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004568 return Result;
4569 }
4570
4571 // C++11 [over.ics.list]p7:
4572 // In all cases other than those enumerated above, no conversion is possible
4573 return Result;
4574}
4575
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004576/// TryCopyInitialization - Try to copy-initialize a value of type
4577/// ToType from the expression From. Return the implicit conversion
4578/// sequence required to pass this argument, which may be a bad
4579/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004580/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004581/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004582static ImplicitConversionSequence
4583TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004585 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004586 bool AllowObjCWritebackConversion,
4587 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004588 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4589 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4590 InOverloadResolution,AllowObjCWritebackConversion);
4591
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004592 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004593 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004594 /*FIXME:*/From->getLocStart(),
4595 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004596 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004597
John McCall5c32be02010-08-24 20:38:10 +00004598 return TryImplicitConversion(S, From, ToType,
4599 SuppressUserConversions,
4600 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004601 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004602 /*CStyle=*/false,
4603 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004604}
4605
Anna Zaks1b068122011-07-28 19:46:48 +00004606static bool TryCopyInitialization(const CanQualType FromQTy,
4607 const CanQualType ToQTy,
4608 Sema &S,
4609 SourceLocation Loc,
4610 ExprValueKind FromVK) {
4611 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4612 ImplicitConversionSequence ICS =
4613 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4614
4615 return !ICS.isBad();
4616}
4617
Douglas Gregor436424c2008-11-18 23:14:02 +00004618/// TryObjectArgumentInitialization - Try to initialize the object
4619/// parameter of the given member function (@c Method) from the
4620/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004621static ImplicitConversionSequence
4622TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004623 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004624 CXXMethodDecl *Method,
4625 CXXRecordDecl *ActingContext) {
4626 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004627 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4628 // const volatile object.
4629 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4630 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004631 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004632
4633 // Set up the conversion sequence as a "bad" conversion, to allow us
4634 // to exit early.
4635 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004636
4637 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004638 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004639 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004640 FromType = PT->getPointeeType();
4641
Douglas Gregor02824322011-01-26 19:30:28 +00004642 // When we had a pointer, it's implicitly dereferenced, so we
4643 // better have an lvalue.
4644 assert(FromClassification.isLValue());
4645 }
4646
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004647 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004648
Douglas Gregor02824322011-01-26 19:30:28 +00004649 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004651 // parameter is
4652 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004653 // - "lvalue reference to cv X" for functions declared without a
4654 // ref-qualifier or with the & ref-qualifier
4655 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004656 // ref-qualifier
4657 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004659 // cv-qualification on the member function declaration.
4660 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004662 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004663 // (C++ [over.match.funcs]p5). We perform a simplified version of
4664 // reference binding here, that allows class rvalues to bind to
4665 // non-constant references.
4666
Douglas Gregor02824322011-01-26 19:30:28 +00004667 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004668 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004669 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004670 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004671 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004672 ICS.setBad(BadConversionSequence::bad_qualifiers,
4673 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004674 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004675 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004676
4677 // Check that we have either the same type or a derived type. It
4678 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004679 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004680 ImplicitConversionKind SecondKind;
4681 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4682 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004683 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004684 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004685 else {
John McCall65eb8792010-02-25 01:37:24 +00004686 ICS.setBad(BadConversionSequence::unrelated_class,
4687 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004688 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004689 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004690
Douglas Gregor02824322011-01-26 19:30:28 +00004691 // Check the ref-qualifier.
4692 switch (Method->getRefQualifier()) {
4693 case RQ_None:
4694 // Do nothing; we don't care about lvalueness or rvalueness.
4695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696
Douglas Gregor02824322011-01-26 19:30:28 +00004697 case RQ_LValue:
4698 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4699 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004701 ImplicitParamType);
4702 return ICS;
4703 }
4704 break;
4705
4706 case RQ_RValue:
4707 if (!FromClassification.isRValue()) {
4708 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004710 ImplicitParamType);
4711 return ICS;
4712 }
4713 break;
4714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715
Douglas Gregor436424c2008-11-18 23:14:02 +00004716 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004717 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004718 ICS.Standard.setAsIdentityConversion();
4719 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004720 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004721 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004722 ICS.Standard.ReferenceBinding = true;
4723 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004725 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004726 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4727 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4728 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004729 return ICS;
4730}
4731
4732/// PerformObjectArgumentInitialization - Perform initialization of
4733/// the implicit object parameter for the given Method with the given
4734/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004735ExprResult
4736Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004738 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004739 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004740 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004741 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004742 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004743
Douglas Gregor02824322011-01-26 19:30:28 +00004744 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004745 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004746 FromRecordType = PT->getPointeeType();
4747 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004748 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004749 } else {
4750 FromRecordType = From->getType();
4751 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004752 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004753 }
4754
John McCall6e9f8f62009-12-03 04:06:58 +00004755 // Note that we always use the true parent context when performing
4756 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004757 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004758 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4759 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004760 if (ICS.isBad()) {
4761 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4762 Qualifiers FromQs = FromRecordType.getQualifiers();
4763 Qualifiers ToQs = DestType.getQualifiers();
4764 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4765 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004766 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004767 diag::err_member_function_call_bad_cvr)
4768 << Method->getDeclName() << FromRecordType << (CVR - 1)
4769 << From->getSourceRange();
4770 Diag(Method->getLocation(), diag::note_previous_decl)
4771 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004772 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004773 }
4774 }
4775
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004776 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004777 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004778 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
John Wiegley01296292011-04-08 18:41:53 +00004781 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4782 ExprResult FromRes =
4783 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4784 if (FromRes.isInvalid())
4785 return ExprError();
4786 From = FromRes.take();
4787 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004788
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004789 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004790 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004791 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004792 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004793}
4794
Douglas Gregor5fb53972009-01-14 15:45:31 +00004795/// TryContextuallyConvertToBool - Attempt to contextually convert the
4796/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004797static ImplicitConversionSequence
4798TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004799 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004800 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004801 // FIXME: Are these flags correct?
4802 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004803 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004804 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004805 /*CStyle=*/false,
4806 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004807}
4808
4809/// PerformContextuallyConvertToBool - Perform a contextual conversion
4810/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004811ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004812 if (checkPlaceholderForOverload(*this, From))
4813 return ExprError();
4814
John McCall5c32be02010-08-24 20:38:10 +00004815 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004816 if (!ICS.isBad())
4817 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Fariborz Jahanian76197412009-11-18 18:26:29 +00004819 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004820 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004821 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004822 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004823 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004824}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
Richard Smithf8379a02012-01-18 23:55:52 +00004826/// Check that the specified conversion is permitted in a converted constant
4827/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4828/// is acceptable.
4829static bool CheckConvertedConstantConversions(Sema &S,
4830 StandardConversionSequence &SCS) {
4831 // Since we know that the target type is an integral or unscoped enumeration
4832 // type, most conversion kinds are impossible. All possible First and Third
4833 // conversions are fine.
4834 switch (SCS.Second) {
4835 case ICK_Identity:
4836 case ICK_Integral_Promotion:
4837 case ICK_Integral_Conversion:
4838 return true;
4839
4840 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004841 // Conversion from an integral or unscoped enumeration type to bool is
4842 // classified as ICK_Boolean_Conversion, but it's also an integral
4843 // conversion, so it's permitted in a converted constant expression.
4844 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4845 SCS.getToType(2)->isBooleanType();
4846
Richard Smithf8379a02012-01-18 23:55:52 +00004847 case ICK_Floating_Integral:
4848 case ICK_Complex_Real:
4849 return false;
4850
4851 case ICK_Lvalue_To_Rvalue:
4852 case ICK_Array_To_Pointer:
4853 case ICK_Function_To_Pointer:
4854 case ICK_NoReturn_Adjustment:
4855 case ICK_Qualification:
4856 case ICK_Compatible_Conversion:
4857 case ICK_Vector_Conversion:
4858 case ICK_Vector_Splat:
4859 case ICK_Derived_To_Base:
4860 case ICK_Pointer_Conversion:
4861 case ICK_Pointer_Member:
4862 case ICK_Block_Pointer_Conversion:
4863 case ICK_Writeback_Conversion:
4864 case ICK_Floating_Promotion:
4865 case ICK_Complex_Promotion:
4866 case ICK_Complex_Conversion:
4867 case ICK_Floating_Conversion:
4868 case ICK_TransparentUnionConversion:
4869 llvm_unreachable("unexpected second conversion kind");
4870
4871 case ICK_Num_Conversion_Kinds:
4872 break;
4873 }
4874
4875 llvm_unreachable("unknown conversion kind");
4876}
4877
4878/// CheckConvertedConstantExpression - Check that the expression From is a
4879/// converted constant expression of type T, perform the conversion and produce
4880/// the converted expression, per C++11 [expr.const]p3.
4881ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4882 llvm::APSInt &Value,
4883 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004884 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004885 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4886
4887 if (checkPlaceholderForOverload(*this, From))
4888 return ExprError();
4889
4890 // C++11 [expr.const]p3 with proposed wording fixes:
4891 // A converted constant expression of type T is a core constant expression,
4892 // implicitly converted to a prvalue of type T, where the converted
4893 // expression is a literal constant expression and the implicit conversion
4894 // sequence contains only user-defined conversions, lvalue-to-rvalue
4895 // conversions, integral promotions, and integral conversions other than
4896 // narrowing conversions.
4897 ImplicitConversionSequence ICS =
4898 TryImplicitConversion(From, T,
4899 /*SuppressUserConversions=*/false,
4900 /*AllowExplicit=*/false,
4901 /*InOverloadResolution=*/false,
4902 /*CStyle=*/false,
4903 /*AllowObjcWritebackConversion=*/false);
4904 StandardConversionSequence *SCS = 0;
4905 switch (ICS.getKind()) {
4906 case ImplicitConversionSequence::StandardConversion:
4907 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004908 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004909 diag::err_typecheck_converted_constant_expression_disallowed)
4910 << From->getType() << From->getSourceRange() << T;
4911 SCS = &ICS.Standard;
4912 break;
4913 case ImplicitConversionSequence::UserDefinedConversion:
4914 // We are converting from class type to an integral or enumeration type, so
4915 // the Before sequence must be trivial.
4916 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004917 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004918 diag::err_typecheck_converted_constant_expression_disallowed)
4919 << From->getType() << From->getSourceRange() << T;
4920 SCS = &ICS.UserDefined.After;
4921 break;
4922 case ImplicitConversionSequence::AmbiguousConversion:
4923 case ImplicitConversionSequence::BadConversion:
4924 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004925 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004926 diag::err_typecheck_converted_constant_expression)
4927 << From->getType() << From->getSourceRange() << T;
4928 return ExprError();
4929
4930 case ImplicitConversionSequence::EllipsisConversion:
4931 llvm_unreachable("ellipsis conversion in converted constant expression");
4932 }
4933
4934 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4935 if (Result.isInvalid())
4936 return Result;
4937
4938 // Check for a narrowing implicit conversion.
4939 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004940 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004941 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4942 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004943 case NK_Variable_Narrowing:
4944 // Implicit conversion to a narrower type, and the value is not a constant
4945 // expression. We'll diagnose this in a moment.
4946 case NK_Not_Narrowing:
4947 break;
4948
4949 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004950 Diag(From->getLocStart(),
4951 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4952 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004953 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004954 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004955 break;
4956
4957 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004958 Diag(From->getLocStart(),
4959 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4960 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004961 << CCE << /*Constant*/0 << From->getType() << T;
4962 break;
4963 }
4964
4965 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004966 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00004967 Expr::EvalResult Eval;
4968 Eval.Diag = &Notes;
4969
4970 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4971 // The expression can't be folded, so we can't keep it at this position in
4972 // the AST.
4973 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004974 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004975 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004976
4977 if (Notes.empty()) {
4978 // It's a constant expression.
4979 return Result;
4980 }
Richard Smithf8379a02012-01-18 23:55:52 +00004981 }
4982
4983 // It's not a constant expression. Produce an appropriate diagnostic.
4984 if (Notes.size() == 1 &&
4985 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4986 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4987 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004988 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004989 << CCE << From->getSourceRange();
4990 for (unsigned I = 0; I < Notes.size(); ++I)
4991 Diag(Notes[I].first, Notes[I].second);
4992 }
Richard Smith911e1422012-01-30 22:27:01 +00004993 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004994}
4995
John McCallfec112d2011-09-09 06:11:02 +00004996/// dropPointerConversions - If the given standard conversion sequence
4997/// involves any pointer conversions, remove them. This may change
4998/// the result type of the conversion sequence.
4999static void dropPointerConversion(StandardConversionSequence &SCS) {
5000 if (SCS.Second == ICK_Pointer_Conversion) {
5001 SCS.Second = ICK_Identity;
5002 SCS.Third = ICK_Identity;
5003 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5004 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005005}
John McCall5c32be02010-08-24 20:38:10 +00005006
John McCallfec112d2011-09-09 06:11:02 +00005007/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5008/// convert the expression From to an Objective-C pointer type.
5009static ImplicitConversionSequence
5010TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5011 // Do an implicit conversion to 'id'.
5012 QualType Ty = S.Context.getObjCIdType();
5013 ImplicitConversionSequence ICS
5014 = TryImplicitConversion(S, From, Ty,
5015 // FIXME: Are these flags correct?
5016 /*SuppressUserConversions=*/false,
5017 /*AllowExplicit=*/true,
5018 /*InOverloadResolution=*/false,
5019 /*CStyle=*/false,
5020 /*AllowObjCWritebackConversion=*/false);
5021
5022 // Strip off any final conversions to 'id'.
5023 switch (ICS.getKind()) {
5024 case ImplicitConversionSequence::BadConversion:
5025 case ImplicitConversionSequence::AmbiguousConversion:
5026 case ImplicitConversionSequence::EllipsisConversion:
5027 break;
5028
5029 case ImplicitConversionSequence::UserDefinedConversion:
5030 dropPointerConversion(ICS.UserDefined.After);
5031 break;
5032
5033 case ImplicitConversionSequence::StandardConversion:
5034 dropPointerConversion(ICS.Standard);
5035 break;
5036 }
5037
5038 return ICS;
5039}
5040
5041/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5042/// conversion of the expression From to an Objective-C pointer type.
5043ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005044 if (checkPlaceholderForOverload(*this, From))
5045 return ExprError();
5046
John McCall8b07ec22010-05-15 11:32:37 +00005047 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005048 ImplicitConversionSequence ICS =
5049 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005050 if (!ICS.isBad())
5051 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005052 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005053}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005054
Richard Smith8dd34252012-02-04 07:07:42 +00005055/// Determine whether the provided type is an integral type, or an enumeration
5056/// type of a permitted flavor.
5057static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5058 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5059 : T->isIntegralOrUnscopedEnumerationType();
5060}
5061
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063/// enumeration type.
5064///
5065/// This routine will attempt to convert an expression of class type to an
5066/// integral or enumeration type, if that class type only has a single
5067/// conversion to an integral or enumeration type.
5068///
Douglas Gregor4799d032010-06-30 00:20:43 +00005069/// \param Loc The source location of the construct that requires the
5070/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005071///
James Dennett18348b62012-06-22 08:52:37 +00005072/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005073///
James Dennett18348b62012-06-22 08:52:37 +00005074/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005075///
Richard Smith8dd34252012-02-04 07:07:42 +00005076/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5077/// enumerations should be considered.
5078///
Douglas Gregor4799d032010-06-30 00:20:43 +00005079/// \returns The expression, converted to an integral or enumeration type if
5080/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081ExprResult
John McCallb268a282010-08-23 23:25:46 +00005082Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005083 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005084 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005085 // We can't perform any more checking for type-dependent expressions.
5086 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005087 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088
Eli Friedman1da70392012-01-26 00:26:18 +00005089 // Process placeholders immediately.
5090 if (From->hasPlaceholderType()) {
5091 ExprResult result = CheckPlaceholderExpr(From);
5092 if (result.isInvalid()) return result;
5093 From = result.take();
5094 }
5095
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005096 // If the expression already has integral or enumeration type, we're golden.
5097 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005098 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005099 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005100
5101 // FIXME: Check for missing '()' if T is a function type?
5102
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005104 // expression of integral or enumeration type.
5105 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005106 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005107 if (!Diagnoser.Suppress)
5108 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005109 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005112 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005113 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005114 ICEConvertDiagnoser &Diagnoser;
5115 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005116
Douglas Gregore2b37442012-05-04 22:38:52 +00005117 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5118 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005119
5120 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005121 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005122 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005123 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005124
5125 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005126 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005128 // Look for a conversion to an integral or enumeration type.
5129 UnresolvedSet<4> ViableConversions;
5130 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005131 std::pair<CXXRecordDecl::conversion_iterator,
5132 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005133 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005135 bool HadMultipleCandidates
5136 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005137
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005138 for (CXXRecordDecl::conversion_iterator
5139 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005140 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005141 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5142 if (isIntegralOrEnumerationType(
5143 Conversion->getConversionType().getNonReferenceType(),
5144 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005145 if (Conversion->isExplicit())
5146 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5147 else
5148 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5149 }
Richard Smith8dd34252012-02-04 07:07:42 +00005150 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005153 switch (ViableConversions.size()) {
5154 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005155 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005156 DeclAccessPair Found = ExplicitConversions[0];
5157 CXXConversionDecl *Conversion
5158 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005160 // The user probably meant to invoke the given explicit
5161 // conversion; use it.
5162 QualType ConvTy
5163 = Conversion->getConversionType().getNonReferenceType();
5164 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005165 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166
Douglas Gregore2b37442012-05-04 22:38:52 +00005167 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005168 << FixItHint::CreateInsertion(From->getLocStart(),
5169 "static_cast<" + TypeStr + ">(")
5170 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5171 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005172 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
5174 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005175 // explicit conversion function.
5176 if (isSFINAEContext())
5177 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005179 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005180 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5181 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005182 if (Result.isInvalid())
5183 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005184 // Record usage of conversion in an implicit cast.
5185 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5186 CK_UserDefinedConversion,
5187 Result.get(), 0,
5188 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005190
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005191 // We'll complain below about a non-integral condition type.
5192 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005193
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005194 case 1: {
5195 // Apply this conversion.
5196 DeclAccessPair Found = ViableConversions[0];
5197 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005198
Douglas Gregor4799d032010-06-30 00:20:43 +00005199 CXXConversionDecl *Conversion
5200 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5201 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005203 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005204 if (isSFINAEContext())
5205 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Douglas Gregore2b37442012-05-04 22:38:52 +00005207 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5208 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005210
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005211 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5212 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005213 if (Result.isInvalid())
5214 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005215 // Record usage of conversion in an implicit cast.
5216 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5217 CK_UserDefinedConversion,
5218 Result.get(), 0,
5219 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005220 break;
5221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005223 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005224 if (Diagnoser.Suppress)
5225 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005226
Douglas Gregore2b37442012-05-04 22:38:52 +00005227 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005228 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5229 CXXConversionDecl *Conv
5230 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5231 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005232 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005233 }
John McCallb268a282010-08-23 23:25:46 +00005234 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005236
Richard Smithf4c51d92012-02-04 09:53:13 +00005237 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005238 !Diagnoser.Suppress) {
5239 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5240 << From->getSourceRange();
5241 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005242
Eli Friedman1da70392012-01-26 00:26:18 +00005243 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005244}
5245
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005246/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005247/// candidate functions, using the given function call arguments. If
5248/// @p SuppressUserConversions, then don't allow user-defined
5249/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005250///
James Dennett2a4d13c2012-06-15 07:13:21 +00005251/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005252/// based on an incomplete set of function arguments. This feature is used by
5253/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005254void
5255Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005256 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005257 ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005258 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005259 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005260 bool PartialOverloading,
5261 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005262 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005263 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005264 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005265 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005266 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005267
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005269 if (!isa<CXXConstructorDecl>(Method)) {
5270 // If we get here, it's because we're calling a member function
5271 // that is named without a member access expression (e.g.,
5272 // "this->f") that was either written explicitly or created
5273 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005274 // function, e.g., X::f(). We use an empty type for the implied
5275 // object argument (C++ [over.call.func]p3), and the acting context
5276 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005277 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005279 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005280 return;
5281 }
5282 // We treat a constructor like a non-member function, since its object
5283 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005284 }
5285
Douglas Gregorff7028a2009-11-13 23:59:09 +00005286 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005287 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005288
Douglas Gregor27381f32009-11-23 12:27:39 +00005289 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005290 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005291
Douglas Gregorffe14e32009-11-14 01:20:54 +00005292 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5293 // C++ [class.copy]p3:
5294 // A member function template is never instantiated to perform the copy
5295 // of a class object to an object of its class type.
5296 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005297 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005298 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005299 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5300 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005301 return;
5302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005304 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005305 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005306 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005307 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005308 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005309 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005310 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005311 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005313 unsigned NumArgsInProto = Proto->getNumArgs();
5314
5315 // (C++ 13.3.2p2): A candidate function having fewer than m
5316 // parameters is viable only if it has an ellipsis in its parameter
5317 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005318 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005319 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005320 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005321 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005322 return;
5323 }
5324
5325 // (C++ 13.3.2p2): A candidate function having more than m parameters
5326 // is viable only if the (m+1)st parameter has a default argument
5327 // (8.3.6). For the purposes of overload resolution, the
5328 // parameter list is truncated on the right, so that there are
5329 // exactly m parameters.
5330 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005331 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005332 // Not enough arguments.
5333 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005334 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005335 return;
5336 }
5337
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005338 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005339 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005340 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5341 if (CheckCUDATarget(Caller, Function)) {
5342 Candidate.Viable = false;
5343 Candidate.FailureKind = ovl_fail_bad_target;
5344 return;
5345 }
5346
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005347 // Determine the implicit conversion sequences for each of the
5348 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005349 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005350 if (ArgIdx < NumArgsInProto) {
5351 // (C++ 13.3.2p3): for F to be a viable function, there shall
5352 // exist for each argument an implicit conversion sequence
5353 // (13.3.3.1) that converts that argument to the corresponding
5354 // parameter of F.
5355 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005356 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005357 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005359 /*InOverloadResolution=*/true,
5360 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005361 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005362 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005363 if (Candidate.Conversions[ArgIdx].isBad()) {
5364 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005365 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005366 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005367 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005368 } else {
5369 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5370 // argument for which there is no corresponding parameter is
5371 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005372 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005373 }
5374 }
5375}
5376
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005377/// \brief Add all of the function declarations in the given function set to
5378/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005379void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005380 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005381 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005382 bool SuppressUserConversions,
5383 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005384 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005385 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005387 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005388 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005389 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005390 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005391 Args.slice(1), CandidateSet,
5392 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005393 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005394 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005395 SuppressUserConversions);
5396 } else {
John McCalla0296f72010-03-19 07:35:19 +00005397 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005398 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5399 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005400 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005401 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005402 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005403 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005404 Args[0]->Classify(Context), Args.slice(1),
5405 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005406 else
John McCalla0296f72010-03-19 07:35:19 +00005407 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005408 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005409 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005410 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005411 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005412}
5413
John McCallf0f1cf02009-11-17 07:50:12 +00005414/// AddMethodCandidate - Adds a named decl (which is some kind of
5415/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005416void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005417 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005418 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005419 Expr **Args, unsigned NumArgs,
5420 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005421 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005422 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005423 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005424
5425 if (isa<UsingShadowDecl>(Decl))
5426 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
John McCallf0f1cf02009-11-17 07:50:12 +00005428 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5429 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5430 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005431 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5432 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005433 ObjectType, ObjectClassification,
5434 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005435 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005436 } else {
John McCalla0296f72010-03-19 07:35:19 +00005437 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005438 ObjectType, ObjectClassification,
5439 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005440 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005441 }
5442}
5443
Douglas Gregor436424c2008-11-18 23:14:02 +00005444/// AddMethodCandidate - Adds the given C++ member function to the set
5445/// of candidate functions, using the given function call arguments
5446/// and the object argument (@c Object). For example, in a call
5447/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5448/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5449/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005450/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005451void
John McCalla0296f72010-03-19 07:35:19 +00005452Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005453 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005454 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005455 ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005456 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005457 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005458 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005459 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005460 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005461 assert(!isa<CXXConstructorDecl>(Method) &&
5462 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005463
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005464 if (!CandidateSet.isNewCandidate(Method))
5465 return;
5466
Douglas Gregor27381f32009-11-23 12:27:39 +00005467 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005468 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005469
Douglas Gregor436424c2008-11-18 23:14:02 +00005470 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005471 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005472 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005473 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005474 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005475 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005476 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005477
5478 unsigned NumArgsInProto = Proto->getNumArgs();
5479
5480 // (C++ 13.3.2p2): A candidate function having fewer than m
5481 // parameters is viable only if it has an ellipsis in its parameter
5482 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005483 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005484 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005485 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005486 return;
5487 }
5488
5489 // (C++ 13.3.2p2): A candidate function having more than m parameters
5490 // is viable only if the (m+1)st parameter has a default argument
5491 // (8.3.6). For the purposes of overload resolution, the
5492 // parameter list is truncated on the right, so that there are
5493 // exactly m parameters.
5494 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005495 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005496 // Not enough arguments.
5497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005498 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005499 return;
5500 }
5501
5502 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005503
John McCall6e9f8f62009-12-03 04:06:58 +00005504 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005505 // The implicit object argument is ignored.
5506 Candidate.IgnoreObjectArgument = true;
5507 else {
5508 // Determine the implicit conversion sequence for the object
5509 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005510 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005511 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5512 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005513 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005514 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005515 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005516 return;
5517 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005518 }
5519
5520 // Determine the implicit conversion sequences for each of the
5521 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005522 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005523 if (ArgIdx < NumArgsInProto) {
5524 // (C++ 13.3.2p3): for F to be a viable function, there shall
5525 // exist for each argument an implicit conversion sequence
5526 // (13.3.3.1) that converts that argument to the corresponding
5527 // parameter of F.
5528 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005529 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005530 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005532 /*InOverloadResolution=*/true,
5533 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005534 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005535 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005536 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005537 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005538 break;
5539 }
5540 } else {
5541 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5542 // argument for which there is no corresponding parameter is
5543 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005544 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005545 }
5546 }
5547}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005548
Douglas Gregor97628d62009-08-21 00:16:32 +00005549/// \brief Add a C++ member function template as a candidate to the candidate
5550/// set, using template argument deduction to produce an appropriate member
5551/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005552void
Douglas Gregor97628d62009-08-21 00:16:32 +00005553Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005554 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005555 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005556 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005557 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005558 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005559 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005560 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005561 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005562 if (!CandidateSet.isNewCandidate(MethodTmpl))
5563 return;
5564
Douglas Gregor97628d62009-08-21 00:16:32 +00005565 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005566 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005567 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005568 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005569 // candidate functions in the usual way.113) A given name can refer to one
5570 // or more function templates and also to a set of overloaded non-template
5571 // functions. In such a case, the candidate functions generated from each
5572 // function template are combined with the set of non-template candidate
5573 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005574 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005575 FunctionDecl *Specialization = 0;
5576 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005577 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5578 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005579 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005580 Candidate.FoundDecl = FoundDecl;
5581 Candidate.Function = MethodTmpl->getTemplatedDecl();
5582 Candidate.Viable = false;
5583 Candidate.FailureKind = ovl_fail_bad_deduction;
5584 Candidate.IsSurrogate = false;
5585 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005586 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005588 Info);
5589 return;
5590 }
Mike Stump11289f42009-09-09 15:08:12 +00005591
Douglas Gregor97628d62009-08-21 00:16:32 +00005592 // Add the function template specialization produced by template argument
5593 // deduction as a candidate.
5594 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005595 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005596 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005597 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005598 ActingContext, ObjectType, ObjectClassification, Args,
5599 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005600}
5601
Douglas Gregor05155d82009-08-21 23:19:43 +00005602/// \brief Add a C++ function template specialization as a candidate
5603/// in the candidate set, using template argument deduction to produce
5604/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005605void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005606Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005607 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005608 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005609 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005610 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005611 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005612 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5613 return;
5614
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005615 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005616 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005617 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005618 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005619 // candidate functions in the usual way.113) A given name can refer to one
5620 // or more function templates and also to a set of overloaded non-template
5621 // functions. In such a case, the candidate functions generated from each
5622 // function template are combined with the set of non-template candidate
5623 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005624 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005625 FunctionDecl *Specialization = 0;
5626 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005627 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5628 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005629 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005630 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005631 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5632 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005633 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005634 Candidate.IsSurrogate = false;
5635 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005636 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005638 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005639 return;
5640 }
Mike Stump11289f42009-09-09 15:08:12 +00005641
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005642 // Add the function template specialization produced by template argument
5643 // deduction as a candidate.
5644 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005645 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005646 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005647}
Mike Stump11289f42009-09-09 15:08:12 +00005648
Douglas Gregora1f013e2008-11-07 22:36:19 +00005649/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005650/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005651/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005652/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005653/// (which may or may not be the same type as the type that the
5654/// conversion function produces).
5655void
5656Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005657 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005658 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005659 Expr *From, QualType ToType,
5660 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005661 assert(!Conversion->getDescribedFunctionTemplate() &&
5662 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005663 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005664 if (!CandidateSet.isNewCandidate(Conversion))
5665 return;
5666
Douglas Gregor27381f32009-11-23 12:27:39 +00005667 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005668 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005669
Douglas Gregora1f013e2008-11-07 22:36:19 +00005670 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005671 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005672 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005673 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005674 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005675 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005676 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005677 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005678 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005679 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005680 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005681
Douglas Gregor6affc782010-08-19 15:37:02 +00005682 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683 // For conversion functions, the function is considered to be a member of
5684 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005685 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005686 //
5687 // Determine the implicit conversion sequence for the implicit
5688 // object parameter.
5689 QualType ImplicitParamType = From->getType();
5690 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5691 ImplicitParamType = FromPtrType->getPointeeType();
5692 CXXRecordDecl *ConversionContext
5693 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005695 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696 = TryObjectArgumentInitialization(*this, From->getType(),
5697 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005698 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699
John McCall0d1da222010-01-12 00:44:57 +00005700 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005701 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005702 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005703 return;
5704 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005705
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005707 // derived to base as such conversions are given Conversion Rank. They only
5708 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5709 QualType FromCanon
5710 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5711 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5712 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5713 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005714 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005715 return;
5716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Douglas Gregora1f013e2008-11-07 22:36:19 +00005718 // To determine what the conversion from the result of calling the
5719 // conversion function to the type we're eventually trying to
5720 // convert to (ToType), we need to synthesize a call to the
5721 // conversion function and attempt copy initialization from it. This
5722 // makes sure that we get the right semantics with respect to
5723 // lvalues/rvalues and the type. Fortunately, we can allocate this
5724 // call on the stack and we don't need its arguments to be
5725 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005726 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005727 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005728 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5729 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005730 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005731 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005732
Richard Smith48d24642011-07-13 22:53:21 +00005733 QualType ConversionType = Conversion->getConversionType();
5734 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005735 Candidate.Viable = false;
5736 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5737 return;
5738 }
5739
Richard Smith48d24642011-07-13 22:53:21 +00005740 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005741
Mike Stump11289f42009-09-09 15:08:12 +00005742 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005743 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5744 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005745 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramerc215e762012-08-24 11:54:20 +00005746 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005747 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005748 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005749 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005750 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005751 /*InOverloadResolution=*/false,
5752 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005753
John McCall0d1da222010-01-12 00:44:57 +00005754 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005755 case ImplicitConversionSequence::StandardConversion:
5756 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005758 // C++ [over.ics.user]p3:
5759 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005761 // shall have exact match rank.
5762 if (Conversion->getPrimaryTemplate() &&
5763 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5764 Candidate.Viable = false;
5765 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767
Douglas Gregorcba72b12011-01-21 05:18:22 +00005768 // C++0x [dcl.init.ref]p5:
5769 // In the second case, if the reference is an rvalue reference and
5770 // the second standard conversion sequence of the user-defined
5771 // conversion sequence includes an lvalue-to-rvalue conversion, the
5772 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005774 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5775 Candidate.Viable = false;
5776 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5777 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005778 break;
5779
5780 case ImplicitConversionSequence::BadConversion:
5781 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005782 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005783 break;
5784
5785 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005786 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005787 "Can only end up with a standard conversion sequence or failure");
5788 }
5789}
5790
Douglas Gregor05155d82009-08-21 23:19:43 +00005791/// \brief Adds a conversion function template specialization
5792/// candidate to the overload set, using template argument deduction
5793/// to deduce the template arguments of the conversion function
5794/// template from the type that we are converting to (C++
5795/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005796void
Douglas Gregor05155d82009-08-21 23:19:43 +00005797Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005798 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005799 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005800 Expr *From, QualType ToType,
5801 OverloadCandidateSet &CandidateSet) {
5802 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5803 "Only conversion function templates permitted here");
5804
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005805 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5806 return;
5807
Craig Toppere6706e42012-09-19 02:26:47 +00005808 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005809 CXXConversionDecl *Specialization = 0;
5810 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005811 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005812 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005813 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005814 Candidate.FoundDecl = FoundDecl;
5815 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5816 Candidate.Viable = false;
5817 Candidate.FailureKind = ovl_fail_bad_deduction;
5818 Candidate.IsSurrogate = false;
5819 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005820 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005822 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005823 return;
5824 }
Mike Stump11289f42009-09-09 15:08:12 +00005825
Douglas Gregor05155d82009-08-21 23:19:43 +00005826 // Add the conversion function template specialization produced by
5827 // template argument deduction as a candidate.
5828 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005829 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005830 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005831}
5832
Douglas Gregorab7897a2008-11-19 22:57:39 +00005833/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5834/// converts the given @c Object to a function pointer via the
5835/// conversion function @c Conversion, and then attempts to call it
5836/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5837/// the type of function that we'll eventually be calling.
5838void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005839 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005840 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005841 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005842 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005843 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005844 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005845 if (!CandidateSet.isNewCandidate(Conversion))
5846 return;
5847
Douglas Gregor27381f32009-11-23 12:27:39 +00005848 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005849 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005850
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005851 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005852 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005853 Candidate.Function = 0;
5854 Candidate.Surrogate = Conversion;
5855 Candidate.Viable = true;
5856 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005857 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005858 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005859
5860 // Determine the implicit conversion sequence for the implicit
5861 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005862 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005863 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005864 Object->Classify(Context),
5865 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005866 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005867 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005868 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005869 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005870 return;
5871 }
5872
5873 // The first conversion is actually a user-defined conversion whose
5874 // first conversion is ObjectInit's standard conversion (which is
5875 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005876 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005877 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005878 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005879 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005880 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005881 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005882 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005883 = Candidate.Conversions[0].UserDefined.Before;
5884 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5885
Mike Stump11289f42009-09-09 15:08:12 +00005886 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005887 unsigned NumArgsInProto = Proto->getNumArgs();
5888
5889 // (C++ 13.3.2p2): A candidate function having fewer than m
5890 // parameters is viable only if it has an ellipsis in its parameter
5891 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005892 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005893 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005894 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005895 return;
5896 }
5897
5898 // Function types don't have any default arguments, so just check if
5899 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005900 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005901 // Not enough arguments.
5902 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005903 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005904 return;
5905 }
5906
5907 // Determine the implicit conversion sequences for each of the
5908 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005909 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005910 if (ArgIdx < NumArgsInProto) {
5911 // (C++ 13.3.2p3): for F to be a viable function, there shall
5912 // exist for each argument an implicit conversion sequence
5913 // (13.3.3.1) that converts that argument to the corresponding
5914 // parameter of F.
5915 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005916 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005917 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005918 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005919 /*InOverloadResolution=*/false,
5920 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005921 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005922 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005923 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005924 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005925 break;
5926 }
5927 } else {
5928 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5929 // argument for which there is no corresponding parameter is
5930 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005931 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005932 }
5933 }
5934}
5935
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005936/// \brief Add overload candidates for overloaded operators that are
5937/// member functions.
5938///
5939/// Add the overloaded operator candidates that are member functions
5940/// for the operator Op that was used in an operator expression such
5941/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5942/// CandidateSet will store the added overload candidates. (C++
5943/// [over.match.oper]).
5944void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5945 SourceLocation OpLoc,
5946 Expr **Args, unsigned NumArgs,
5947 OverloadCandidateSet& CandidateSet,
5948 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005949 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5950
5951 // C++ [over.match.oper]p3:
5952 // For a unary operator @ with an operand of a type whose
5953 // cv-unqualified version is T1, and for a binary operator @ with
5954 // a left operand of a type whose cv-unqualified version is T1 and
5955 // a right operand of a type whose cv-unqualified version is T2,
5956 // three sets of candidate functions, designated member
5957 // candidates, non-member candidates and built-in candidates, are
5958 // constructed as follows:
5959 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005960
5961 // -- If T1 is a class type, the set of member candidates is the
5962 // result of the qualified lookup of T1::operator@
5963 // (13.3.1.1.1); otherwise, the set of member candidates is
5964 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005965 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005966 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005967 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005968 return;
Mike Stump11289f42009-09-09 15:08:12 +00005969
John McCall27b18f82009-11-17 02:14:36 +00005970 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5971 LookupQualifiedName(Operators, T1Rec->getDecl());
5972 Operators.suppressDiagnostics();
5973
Mike Stump11289f42009-09-09 15:08:12 +00005974 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005975 OperEnd = Operators.end();
5976 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005977 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005978 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005979 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005980 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005981 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005982 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005983}
5984
Douglas Gregora11693b2008-11-12 17:17:38 +00005985/// AddBuiltinCandidate - Add a candidate for a built-in
5986/// operator. ResultTy and ParamTys are the result and parameter types
5987/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005988/// arguments being passed to the candidate. IsAssignmentOperator
5989/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005990/// operator. NumContextualBoolArguments is the number of arguments
5991/// (at the beginning of the argument list) that will be contextually
5992/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005993void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005994 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005995 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005996 bool IsAssignmentOperator,
5997 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005998 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005999 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006000
Douglas Gregora11693b2008-11-12 17:17:38 +00006001 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006002 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00006003 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006004 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006005 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006006 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006007 Candidate.BuiltinTypes.ResultTy = ResultTy;
6008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6009 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6010
6011 // Determine the implicit conversion sequences for each of the
6012 // arguments.
6013 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006014 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00006015 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006016 // C++ [over.match.oper]p4:
6017 // For the built-in assignment operators, conversions of the
6018 // left operand are restricted as follows:
6019 // -- no temporaries are introduced to hold the left operand, and
6020 // -- no user-defined conversions are applied to the left
6021 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006022 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006023 //
6024 // We block these conversions by turning off user-defined
6025 // conversions, since that is the only way that initialization of
6026 // a reference to a non-class type can occur from something that
6027 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006028 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006029 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006030 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006031 Candidate.Conversions[ArgIdx]
6032 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006033 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006034 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006035 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006036 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006037 /*InOverloadResolution=*/false,
6038 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006039 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006040 }
John McCall0d1da222010-01-12 00:44:57 +00006041 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006042 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006043 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006044 break;
6045 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006046 }
6047}
6048
6049/// BuiltinCandidateTypeSet - A set of types that will be used for the
6050/// candidate operator functions for built-in operators (C++
6051/// [over.built]). The types are separated into pointer types and
6052/// enumeration types.
6053class BuiltinCandidateTypeSet {
6054 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006055 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006056
6057 /// PointerTypes - The set of pointer types that will be used in the
6058 /// built-in candidates.
6059 TypeSet PointerTypes;
6060
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006061 /// MemberPointerTypes - The set of member pointer types that will be
6062 /// used in the built-in candidates.
6063 TypeSet MemberPointerTypes;
6064
Douglas Gregora11693b2008-11-12 17:17:38 +00006065 /// EnumerationTypes - The set of enumeration types that will be
6066 /// used in the built-in candidates.
6067 TypeSet EnumerationTypes;
6068
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006070 /// candidates.
6071 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006072
6073 /// \brief A flag indicating non-record types are viable candidates
6074 bool HasNonRecordTypes;
6075
6076 /// \brief A flag indicating whether either arithmetic or enumeration types
6077 /// were present in the candidate set.
6078 bool HasArithmeticOrEnumeralTypes;
6079
Douglas Gregor80af3132011-05-21 23:15:46 +00006080 /// \brief A flag indicating whether the nullptr type was present in the
6081 /// candidate set.
6082 bool HasNullPtrType;
6083
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006084 /// Sema - The semantic analysis instance where we are building the
6085 /// candidate type set.
6086 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006087
Douglas Gregora11693b2008-11-12 17:17:38 +00006088 /// Context - The AST context in which we will build the type sets.
6089 ASTContext &Context;
6090
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006091 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6092 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006093 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006094
6095public:
6096 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006097 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006098
Mike Stump11289f42009-09-09 15:08:12 +00006099 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006100 : HasNonRecordTypes(false),
6101 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006102 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006103 SemaRef(SemaRef),
6104 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006105
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006106 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006107 SourceLocation Loc,
6108 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006109 bool AllowExplicitConversions,
6110 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006111
6112 /// pointer_begin - First pointer type found;
6113 iterator pointer_begin() { return PointerTypes.begin(); }
6114
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006115 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006116 iterator pointer_end() { return PointerTypes.end(); }
6117
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006118 /// member_pointer_begin - First member pointer type found;
6119 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6120
6121 /// member_pointer_end - Past the last member pointer type found;
6122 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6123
Douglas Gregora11693b2008-11-12 17:17:38 +00006124 /// enumeration_begin - First enumeration type found;
6125 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6126
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006127 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006128 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006130 iterator vector_begin() { return VectorTypes.begin(); }
6131 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006132
6133 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6134 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006135 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006136};
6137
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006138/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006139/// the set of pointer types along with any more-qualified variants of
6140/// that type. For example, if @p Ty is "int const *", this routine
6141/// will add "int const *", "int const volatile *", "int const
6142/// restrict *", and "int const volatile restrict *" to the set of
6143/// pointer types. Returns true if the add of @p Ty itself succeeded,
6144/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006145///
6146/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006147bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006148BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6149 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006150
Douglas Gregora11693b2008-11-12 17:17:38 +00006151 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006152 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006153 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006155 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006156 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006157 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006158 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006159 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6160 PointeeTy = PTy->getPointeeType();
6161 buildObjCPtr = true;
6162 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006163 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006164 }
6165
Sebastian Redl4990a632009-11-18 20:39:26 +00006166 // Don't add qualified variants of arrays. For one, they're not allowed
6167 // (the qualifier would sink to the element type), and for another, the
6168 // only overload situation where it matters is subscript or pointer +- int,
6169 // and those shouldn't have qualifier variants anyway.
6170 if (PointeeTy->isArrayType())
6171 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006172
John McCall8ccfcb52009-09-24 19:53:00 +00006173 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006174 bool hasVolatile = VisibleQuals.hasVolatile();
6175 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006176
John McCall8ccfcb52009-09-24 19:53:00 +00006177 // Iterate through all strict supersets of BaseCVR.
6178 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6179 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006180 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006181 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006182
6183 // Skip over restrict if no restrict found anywhere in the types, or if
6184 // the type cannot be restrict-qualified.
6185 if ((CVR & Qualifiers::Restrict) &&
6186 (!hasRestrict ||
6187 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6188 continue;
6189
6190 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006191 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006192
6193 // Build qualified pointer type.
6194 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006195 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006196 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006197 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006198 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6199
6200 // Insert qualified pointer type.
6201 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006202 }
6203
6204 return true;
6205}
6206
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006207/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6208/// to the set of pointer types along with any more-qualified variants of
6209/// that type. For example, if @p Ty is "int const *", this routine
6210/// will add "int const *", "int const volatile *", "int const
6211/// restrict *", and "int const volatile restrict *" to the set of
6212/// pointer types. Returns true if the add of @p Ty itself succeeded,
6213/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006214///
6215/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006216bool
6217BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6218 QualType Ty) {
6219 // Insert this type.
6220 if (!MemberPointerTypes.insert(Ty))
6221 return false;
6222
John McCall8ccfcb52009-09-24 19:53:00 +00006223 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6224 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006225
John McCall8ccfcb52009-09-24 19:53:00 +00006226 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006227 // Don't add qualified variants of arrays. For one, they're not allowed
6228 // (the qualifier would sink to the element type), and for another, the
6229 // only overload situation where it matters is subscript or pointer +- int,
6230 // and those shouldn't have qualifier variants anyway.
6231 if (PointeeTy->isArrayType())
6232 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006233 const Type *ClassTy = PointerTy->getClass();
6234
6235 // Iterate through all strict supersets of the pointee type's CVR
6236 // qualifiers.
6237 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6238 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6239 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006240
John McCall8ccfcb52009-09-24 19:53:00 +00006241 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006242 MemberPointerTypes.insert(
6243 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006244 }
6245
6246 return true;
6247}
6248
Douglas Gregora11693b2008-11-12 17:17:38 +00006249/// AddTypesConvertedFrom - Add each of the types to which the type @p
6250/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006251/// primarily interested in pointer types and enumeration types. We also
6252/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006253/// AllowUserConversions is true if we should look at the conversion
6254/// functions of a class type, and AllowExplicitConversions if we
6255/// should also include the explicit conversion functions of a class
6256/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006257void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006258BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006259 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006260 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006261 bool AllowExplicitConversions,
6262 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006263 // Only deal with canonical types.
6264 Ty = Context.getCanonicalType(Ty);
6265
6266 // Look through reference types; they aren't part of the type of an
6267 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006268 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006269 Ty = RefTy->getPointeeType();
6270
John McCall33ddac02011-01-19 10:06:00 +00006271 // If we're dealing with an array type, decay to the pointer.
6272 if (Ty->isArrayType())
6273 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6274
6275 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006276 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006277
Chandler Carruth00a38332010-12-13 01:44:01 +00006278 // Flag if we ever add a non-record type.
6279 const RecordType *TyRec = Ty->getAs<RecordType>();
6280 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6281
Chandler Carruth00a38332010-12-13 01:44:01 +00006282 // Flag if we encounter an arithmetic type.
6283 HasArithmeticOrEnumeralTypes =
6284 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6285
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006286 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6287 PointerTypes.insert(Ty);
6288 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006289 // Insert our type, and its more-qualified variants, into the set
6290 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006291 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006292 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006293 } else if (Ty->isMemberPointerType()) {
6294 // Member pointers are far easier, since the pointee can't be converted.
6295 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6296 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006297 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006298 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006299 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006300 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006301 // We treat vector types as arithmetic types in many contexts as an
6302 // extension.
6303 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006304 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006305 } else if (Ty->isNullPtrType()) {
6306 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006307 } else if (AllowUserConversions && TyRec) {
6308 // No conversion functions in incomplete types.
6309 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6310 return;
Mike Stump11289f42009-09-09 15:08:12 +00006311
Chandler Carruth00a38332010-12-13 01:44:01 +00006312 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006313 std::pair<CXXRecordDecl::conversion_iterator,
6314 CXXRecordDecl::conversion_iterator>
6315 Conversions = ClassDecl->getVisibleConversionFunctions();
6316 for (CXXRecordDecl::conversion_iterator
6317 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006318 NamedDecl *D = I.getDecl();
6319 if (isa<UsingShadowDecl>(D))
6320 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006321
Chandler Carruth00a38332010-12-13 01:44:01 +00006322 // Skip conversion function templates; they don't tell us anything
6323 // about which builtin types we can convert to.
6324 if (isa<FunctionTemplateDecl>(D))
6325 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006326
Chandler Carruth00a38332010-12-13 01:44:01 +00006327 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6328 if (AllowExplicitConversions || !Conv->isExplicit()) {
6329 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6330 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006331 }
6332 }
6333 }
6334}
6335
Douglas Gregor84605ae2009-08-24 13:43:27 +00006336/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6337/// the volatile- and non-volatile-qualified assignment operators for the
6338/// given type to the candidate set.
6339static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6340 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006341 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006342 unsigned NumArgs,
6343 OverloadCandidateSet &CandidateSet) {
6344 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006345
Douglas Gregor84605ae2009-08-24 13:43:27 +00006346 // T& operator=(T&, T)
6347 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6348 ParamTypes[1] = T;
6349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6350 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006351
Douglas Gregor84605ae2009-08-24 13:43:27 +00006352 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6353 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006354 ParamTypes[0]
6355 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006356 ParamTypes[1] = T;
6357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006358 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006359 }
6360}
Mike Stump11289f42009-09-09 15:08:12 +00006361
Sebastian Redl1054fae2009-10-25 17:03:50 +00006362/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6363/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006364static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6365 Qualifiers VRQuals;
6366 const RecordType *TyRec;
6367 if (const MemberPointerType *RHSMPType =
6368 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006369 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006370 else
6371 TyRec = ArgExpr->getType()->getAs<RecordType>();
6372 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006373 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006374 VRQuals.addVolatile();
6375 VRQuals.addRestrict();
6376 return VRQuals;
6377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006380 if (!ClassDecl->hasDefinition())
6381 return VRQuals;
6382
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006383 std::pair<CXXRecordDecl::conversion_iterator,
6384 CXXRecordDecl::conversion_iterator>
6385 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006387 for (CXXRecordDecl::conversion_iterator
6388 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006389 NamedDecl *D = I.getDecl();
6390 if (isa<UsingShadowDecl>(D))
6391 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6392 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006393 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6394 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6395 CanTy = ResTypeRef->getPointeeType();
6396 // Need to go down the pointer/mempointer chain and add qualifiers
6397 // as see them.
6398 bool done = false;
6399 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006400 if (CanTy.isRestrictQualified())
6401 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006402 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6403 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006405 CanTy->getAs<MemberPointerType>())
6406 CanTy = ResTypeMPtr->getPointeeType();
6407 else
6408 done = true;
6409 if (CanTy.isVolatileQualified())
6410 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006411 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6412 return VRQuals;
6413 }
6414 }
6415 }
6416 return VRQuals;
6417}
John McCall52872982010-11-13 05:51:15 +00006418
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006419namespace {
John McCall52872982010-11-13 05:51:15 +00006420
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006421/// \brief Helper class to manage the addition of builtin operator overload
6422/// candidates. It provides shared state and utility methods used throughout
6423/// the process, as well as a helper method to add each group of builtin
6424/// operator overloads from the standard to a candidate set.
6425class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006426 // Common instance state available to all overload candidate addition methods.
6427 Sema &S;
6428 Expr **Args;
6429 unsigned NumArgs;
6430 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006431 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006432 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006433 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006434
Chandler Carruthc6586e52010-12-12 10:35:00 +00006435 // Define some constants used to index and iterate over the arithemetic types
6436 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006437 // The "promoted arithmetic types" are the arithmetic
6438 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006439 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006440 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006441 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006442 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006443 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006444 LastPromotedArithmeticType = 11;
6445 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006446
Chandler Carruthc6586e52010-12-12 10:35:00 +00006447 /// \brief Get the canonical type for a given arithmetic type index.
6448 CanQualType getArithmeticType(unsigned index) {
6449 assert(index < NumArithmeticTypes);
6450 static CanQualType ASTContext::* const
6451 ArithmeticTypes[NumArithmeticTypes] = {
6452 // Start of promoted types.
6453 &ASTContext::FloatTy,
6454 &ASTContext::DoubleTy,
6455 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006456
Chandler Carruthc6586e52010-12-12 10:35:00 +00006457 // Start of integral types.
6458 &ASTContext::IntTy,
6459 &ASTContext::LongTy,
6460 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006461 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006462 &ASTContext::UnsignedIntTy,
6463 &ASTContext::UnsignedLongTy,
6464 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006465 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006466 // End of promoted types.
6467
6468 &ASTContext::BoolTy,
6469 &ASTContext::CharTy,
6470 &ASTContext::WCharTy,
6471 &ASTContext::Char16Ty,
6472 &ASTContext::Char32Ty,
6473 &ASTContext::SignedCharTy,
6474 &ASTContext::ShortTy,
6475 &ASTContext::UnsignedCharTy,
6476 &ASTContext::UnsignedShortTy,
6477 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006478 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006479 };
6480 return S.Context.*ArithmeticTypes[index];
6481 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006482
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006483 /// \brief Gets the canonical type resulting from the usual arithemetic
6484 /// converions for the given arithmetic types.
6485 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6486 // Accelerator table for performing the usual arithmetic conversions.
6487 // The rules are basically:
6488 // - if either is floating-point, use the wider floating-point
6489 // - if same signedness, use the higher rank
6490 // - if same size, use unsigned of the higher rank
6491 // - use the larger type
6492 // These rules, together with the axiom that higher ranks are
6493 // never smaller, are sufficient to precompute all of these results
6494 // *except* when dealing with signed types of higher rank.
6495 // (we could precompute SLL x UI for all known platforms, but it's
6496 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006497 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006498 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006499 Dep=-1,
6500 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006501 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006502 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006503 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006504/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6505/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6506/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6507/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6508/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6509/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6510/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6511/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6512/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6513/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6514/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006515 };
6516
6517 assert(L < LastPromotedArithmeticType);
6518 assert(R < LastPromotedArithmeticType);
6519 int Idx = ConversionsTable[L][R];
6520
6521 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006522 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006523
6524 // Slow path: we need to compare widths.
6525 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006526 CanQualType LT = getArithmeticType(L),
6527 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006528 unsigned LW = S.Context.getIntWidth(LT),
6529 RW = S.Context.getIntWidth(RT);
6530
6531 // If they're different widths, use the signed type.
6532 if (LW > RW) return LT;
6533 else if (LW < RW) return RT;
6534
6535 // Otherwise, use the unsigned type of the signed type's rank.
6536 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6537 assert(L == SLL || R == SLL);
6538 return S.Context.UnsignedLongLongTy;
6539 }
6540
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006541 /// \brief Helper method to factor out the common pattern of adding overloads
6542 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006543 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006544 bool HasVolatile,
6545 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006546 QualType ParamTypes[2] = {
6547 S.Context.getLValueReferenceType(CandidateTy),
6548 S.Context.IntTy
6549 };
6550
6551 // Non-volatile version.
6552 if (NumArgs == 1)
6553 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6554 else
6555 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6556
6557 // Use a heuristic to reduce number of builtin candidates in the set:
6558 // add volatile version only if there are conversions to a volatile type.
6559 if (HasVolatile) {
6560 ParamTypes[0] =
6561 S.Context.getLValueReferenceType(
6562 S.Context.getVolatileType(CandidateTy));
6563 if (NumArgs == 1)
6564 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6565 else
6566 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6567 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006568
6569 // Add restrict version only if there are conversions to a restrict type
6570 // and our candidate type is a non-restrict-qualified pointer.
6571 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6572 !CandidateTy.isRestrictQualified()) {
6573 ParamTypes[0]
6574 = S.Context.getLValueReferenceType(
6575 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6576 if (NumArgs == 1)
6577 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6578 else
6579 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6580
6581 if (HasVolatile) {
6582 ParamTypes[0]
6583 = S.Context.getLValueReferenceType(
6584 S.Context.getCVRQualifiedType(CandidateTy,
6585 (Qualifiers::Volatile |
6586 Qualifiers::Restrict)));
6587 if (NumArgs == 1)
6588 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6589 CandidateSet);
6590 else
6591 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6592 }
6593 }
6594
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006595 }
6596
6597public:
6598 BuiltinOperatorOverloadBuilder(
6599 Sema &S, Expr **Args, unsigned NumArgs,
6600 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006601 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006602 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006603 OverloadCandidateSet &CandidateSet)
6604 : S(S), Args(Args), NumArgs(NumArgs),
6605 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006606 HasArithmeticOrEnumeralCandidateType(
6607 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006608 CandidateTypes(CandidateTypes),
6609 CandidateSet(CandidateSet) {
6610 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006611 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006612 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006613 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006614 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006615 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006616 assert(getArithmeticType(FirstPromotedArithmeticType)
6617 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006618 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006619 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006620 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006621 "Invalid last promoted arithmetic type");
6622 }
6623
6624 // C++ [over.built]p3:
6625 //
6626 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6627 // is either volatile or empty, there exist candidate operator
6628 // functions of the form
6629 //
6630 // VQ T& operator++(VQ T&);
6631 // T operator++(VQ T&, int);
6632 //
6633 // C++ [over.built]p4:
6634 //
6635 // For every pair (T, VQ), where T is an arithmetic type other
6636 // than bool, and VQ is either volatile or empty, there exist
6637 // candidate operator functions of the form
6638 //
6639 // VQ T& operator--(VQ T&);
6640 // T operator--(VQ T&, int);
6641 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006642 if (!HasArithmeticOrEnumeralCandidateType)
6643 return;
6644
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006645 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6646 Arith < NumArithmeticTypes; ++Arith) {
6647 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006648 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006649 VisibleTypeConversionsQuals.hasVolatile(),
6650 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006651 }
6652 }
6653
6654 // C++ [over.built]p5:
6655 //
6656 // For every pair (T, VQ), where T is a cv-qualified or
6657 // cv-unqualified object type, and VQ is either volatile or
6658 // empty, there exist candidate operator functions of the form
6659 //
6660 // T*VQ& operator++(T*VQ&);
6661 // T*VQ& operator--(T*VQ&);
6662 // T* operator++(T*VQ&, int);
6663 // T* operator--(T*VQ&, int);
6664 void addPlusPlusMinusMinusPointerOverloads() {
6665 for (BuiltinCandidateTypeSet::iterator
6666 Ptr = CandidateTypes[0].pointer_begin(),
6667 PtrEnd = CandidateTypes[0].pointer_end();
6668 Ptr != PtrEnd; ++Ptr) {
6669 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006670 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006671 continue;
6672
6673 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006674 (!(*Ptr).isVolatileQualified() &&
6675 VisibleTypeConversionsQuals.hasVolatile()),
6676 (!(*Ptr).isRestrictQualified() &&
6677 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006678 }
6679 }
6680
6681 // C++ [over.built]p6:
6682 // For every cv-qualified or cv-unqualified object type T, there
6683 // exist candidate operator functions of the form
6684 //
6685 // T& operator*(T*);
6686 //
6687 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006689 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006690 // T& operator*(T*);
6691 void addUnaryStarPointerOverloads() {
6692 for (BuiltinCandidateTypeSet::iterator
6693 Ptr = CandidateTypes[0].pointer_begin(),
6694 PtrEnd = CandidateTypes[0].pointer_end();
6695 Ptr != PtrEnd; ++Ptr) {
6696 QualType ParamTy = *Ptr;
6697 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006698 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6699 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
Douglas Gregor02824322011-01-26 19:30:28 +00006701 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6702 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006705 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6706 &ParamTy, Args, 1, CandidateSet);
6707 }
6708 }
6709
6710 // C++ [over.built]p9:
6711 // For every promoted arithmetic type T, there exist candidate
6712 // operator functions of the form
6713 //
6714 // T operator+(T);
6715 // T operator-(T);
6716 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006717 if (!HasArithmeticOrEnumeralCandidateType)
6718 return;
6719
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006720 for (unsigned Arith = FirstPromotedArithmeticType;
6721 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006722 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006723 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6724 }
6725
6726 // Extension: We also add these operators for vector types.
6727 for (BuiltinCandidateTypeSet::iterator
6728 Vec = CandidateTypes[0].vector_begin(),
6729 VecEnd = CandidateTypes[0].vector_end();
6730 Vec != VecEnd; ++Vec) {
6731 QualType VecTy = *Vec;
6732 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6733 }
6734 }
6735
6736 // C++ [over.built]p8:
6737 // For every type T, there exist candidate operator functions of
6738 // the form
6739 //
6740 // T* operator+(T*);
6741 void addUnaryPlusPointerOverloads() {
6742 for (BuiltinCandidateTypeSet::iterator
6743 Ptr = CandidateTypes[0].pointer_begin(),
6744 PtrEnd = CandidateTypes[0].pointer_end();
6745 Ptr != PtrEnd; ++Ptr) {
6746 QualType ParamTy = *Ptr;
6747 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6748 }
6749 }
6750
6751 // C++ [over.built]p10:
6752 // For every promoted integral type T, there exist candidate
6753 // operator functions of the form
6754 //
6755 // T operator~(T);
6756 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006757 if (!HasArithmeticOrEnumeralCandidateType)
6758 return;
6759
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006760 for (unsigned Int = FirstPromotedIntegralType;
6761 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006762 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006763 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6764 }
6765
6766 // Extension: We also add this operator for vector types.
6767 for (BuiltinCandidateTypeSet::iterator
6768 Vec = CandidateTypes[0].vector_begin(),
6769 VecEnd = CandidateTypes[0].vector_end();
6770 Vec != VecEnd; ++Vec) {
6771 QualType VecTy = *Vec;
6772 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6773 }
6774 }
6775
6776 // C++ [over.match.oper]p16:
6777 // For every pointer to member type T, there exist candidate operator
6778 // functions of the form
6779 //
6780 // bool operator==(T,T);
6781 // bool operator!=(T,T);
6782 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6783 /// Set of (canonical) types that we've already handled.
6784 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6785
6786 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6787 for (BuiltinCandidateTypeSet::iterator
6788 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6789 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6790 MemPtr != MemPtrEnd;
6791 ++MemPtr) {
6792 // Don't add the same builtin candidate twice.
6793 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6794 continue;
6795
6796 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6797 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6798 CandidateSet);
6799 }
6800 }
6801 }
6802
6803 // C++ [over.built]p15:
6804 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006805 // For every T, where T is an enumeration type, a pointer type, or
6806 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006807 //
6808 // bool operator<(T, T);
6809 // bool operator>(T, T);
6810 // bool operator<=(T, T);
6811 // bool operator>=(T, T);
6812 // bool operator==(T, T);
6813 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006814 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00006815 // C++ [over.match.oper]p3:
6816 // [...]the built-in candidates include all of the candidate operator
6817 // functions defined in 13.6 that, compared to the given operator, [...]
6818 // do not have the same parameter-type-list as any non-template non-member
6819 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006820 //
Eli Friedman14f082b2012-09-18 21:52:24 +00006821 // Note that in practice, this only affects enumeration types because there
6822 // aren't any built-in candidates of record type, and a user-defined operator
6823 // must have an operand of record or enumeration type. Also, the only other
6824 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006825 // cannot be overloaded for enumeration types, so this is the only place
6826 // where we must suppress candidates like this.
6827 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6828 UserDefinedBinaryOperators;
6829
6830 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6831 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6832 CandidateTypes[ArgIdx].enumeration_end()) {
6833 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6834 CEnd = CandidateSet.end();
6835 C != CEnd; ++C) {
6836 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6837 continue;
6838
Eli Friedman14f082b2012-09-18 21:52:24 +00006839 if (C->Function->isFunctionTemplateSpecialization())
6840 continue;
6841
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006842 QualType FirstParamType =
6843 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6844 QualType SecondParamType =
6845 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6846
6847 // Skip if either parameter isn't of enumeral type.
6848 if (!FirstParamType->isEnumeralType() ||
6849 !SecondParamType->isEnumeralType())
6850 continue;
6851
6852 // Add this operator to the set of known user-defined operators.
6853 UserDefinedBinaryOperators.insert(
6854 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6855 S.Context.getCanonicalType(SecondParamType)));
6856 }
6857 }
6858 }
6859
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006860 /// Set of (canonical) types that we've already handled.
6861 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6862
6863 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6864 for (BuiltinCandidateTypeSet::iterator
6865 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6866 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6867 Ptr != PtrEnd; ++Ptr) {
6868 // Don't add the same builtin candidate twice.
6869 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6870 continue;
6871
6872 QualType ParamTypes[2] = { *Ptr, *Ptr };
6873 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6874 CandidateSet);
6875 }
6876 for (BuiltinCandidateTypeSet::iterator
6877 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6878 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6879 Enum != EnumEnd; ++Enum) {
6880 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6881
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006882 // Don't add the same builtin candidate twice, or if a user defined
6883 // candidate exists.
6884 if (!AddedTypes.insert(CanonType) ||
6885 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6886 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006887 continue;
6888
6889 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006890 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6891 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006892 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006893
6894 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6895 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6896 if (AddedTypes.insert(NullPtrTy) &&
6897 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6898 NullPtrTy))) {
6899 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6900 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6901 CandidateSet);
6902 }
6903 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006904 }
6905 }
6906
6907 // C++ [over.built]p13:
6908 //
6909 // For every cv-qualified or cv-unqualified object type T
6910 // there exist candidate operator functions of the form
6911 //
6912 // T* operator+(T*, ptrdiff_t);
6913 // T& operator[](T*, ptrdiff_t); [BELOW]
6914 // T* operator-(T*, ptrdiff_t);
6915 // T* operator+(ptrdiff_t, T*);
6916 // T& operator[](ptrdiff_t, T*); [BELOW]
6917 //
6918 // C++ [over.built]p14:
6919 //
6920 // For every T, where T is a pointer to object type, there
6921 // exist candidate operator functions of the form
6922 //
6923 // ptrdiff_t operator-(T, T);
6924 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6925 /// Set of (canonical) types that we've already handled.
6926 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6927
6928 for (int Arg = 0; Arg < 2; ++Arg) {
6929 QualType AsymetricParamTypes[2] = {
6930 S.Context.getPointerDiffType(),
6931 S.Context.getPointerDiffType(),
6932 };
6933 for (BuiltinCandidateTypeSet::iterator
6934 Ptr = CandidateTypes[Arg].pointer_begin(),
6935 PtrEnd = CandidateTypes[Arg].pointer_end();
6936 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006937 QualType PointeeTy = (*Ptr)->getPointeeType();
6938 if (!PointeeTy->isObjectType())
6939 continue;
6940
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006941 AsymetricParamTypes[Arg] = *Ptr;
6942 if (Arg == 0 || Op == OO_Plus) {
6943 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6944 // T* operator+(ptrdiff_t, T*);
6945 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6946 CandidateSet);
6947 }
6948 if (Op == OO_Minus) {
6949 // ptrdiff_t operator-(T, T);
6950 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6951 continue;
6952
6953 QualType ParamTypes[2] = { *Ptr, *Ptr };
6954 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6955 Args, 2, CandidateSet);
6956 }
6957 }
6958 }
6959 }
6960
6961 // C++ [over.built]p12:
6962 //
6963 // For every pair of promoted arithmetic types L and R, there
6964 // exist candidate operator functions of the form
6965 //
6966 // LR operator*(L, R);
6967 // LR operator/(L, R);
6968 // LR operator+(L, R);
6969 // LR operator-(L, R);
6970 // bool operator<(L, R);
6971 // bool operator>(L, R);
6972 // bool operator<=(L, R);
6973 // bool operator>=(L, R);
6974 // bool operator==(L, R);
6975 // bool operator!=(L, R);
6976 //
6977 // where LR is the result of the usual arithmetic conversions
6978 // between types L and R.
6979 //
6980 // C++ [over.built]p24:
6981 //
6982 // For every pair of promoted arithmetic types L and R, there exist
6983 // candidate operator functions of the form
6984 //
6985 // LR operator?(bool, L, R);
6986 //
6987 // where LR is the result of the usual arithmetic conversions
6988 // between types L and R.
6989 // Our candidates ignore the first parameter.
6990 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006991 if (!HasArithmeticOrEnumeralCandidateType)
6992 return;
6993
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006994 for (unsigned Left = FirstPromotedArithmeticType;
6995 Left < LastPromotedArithmeticType; ++Left) {
6996 for (unsigned Right = FirstPromotedArithmeticType;
6997 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006998 QualType LandR[2] = { getArithmeticType(Left),
6999 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007000 QualType Result =
7001 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007002 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007003 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7004 }
7005 }
7006
7007 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7008 // conditional operator for vector types.
7009 for (BuiltinCandidateTypeSet::iterator
7010 Vec1 = CandidateTypes[0].vector_begin(),
7011 Vec1End = CandidateTypes[0].vector_end();
7012 Vec1 != Vec1End; ++Vec1) {
7013 for (BuiltinCandidateTypeSet::iterator
7014 Vec2 = CandidateTypes[1].vector_begin(),
7015 Vec2End = CandidateTypes[1].vector_end();
7016 Vec2 != Vec2End; ++Vec2) {
7017 QualType LandR[2] = { *Vec1, *Vec2 };
7018 QualType Result = S.Context.BoolTy;
7019 if (!isComparison) {
7020 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7021 Result = *Vec1;
7022 else
7023 Result = *Vec2;
7024 }
7025
7026 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7027 }
7028 }
7029 }
7030
7031 // C++ [over.built]p17:
7032 //
7033 // For every pair of promoted integral types L and R, there
7034 // exist candidate operator functions of the form
7035 //
7036 // LR operator%(L, R);
7037 // LR operator&(L, R);
7038 // LR operator^(L, R);
7039 // LR operator|(L, R);
7040 // L operator<<(L, R);
7041 // L operator>>(L, R);
7042 //
7043 // where LR is the result of the usual arithmetic conversions
7044 // between types L and R.
7045 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007046 if (!HasArithmeticOrEnumeralCandidateType)
7047 return;
7048
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007049 for (unsigned Left = FirstPromotedIntegralType;
7050 Left < LastPromotedIntegralType; ++Left) {
7051 for (unsigned Right = FirstPromotedIntegralType;
7052 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007053 QualType LandR[2] = { getArithmeticType(Left),
7054 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007055 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7056 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007057 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007058 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7059 }
7060 }
7061 }
7062
7063 // C++ [over.built]p20:
7064 //
7065 // For every pair (T, VQ), where T is an enumeration or
7066 // pointer to member type and VQ is either volatile or
7067 // empty, there exist candidate operator functions of the form
7068 //
7069 // VQ T& operator=(VQ T&, T);
7070 void addAssignmentMemberPointerOrEnumeralOverloads() {
7071 /// Set of (canonical) types that we've already handled.
7072 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7073
7074 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7075 for (BuiltinCandidateTypeSet::iterator
7076 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7077 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7078 Enum != EnumEnd; ++Enum) {
7079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7080 continue;
7081
7082 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7083 CandidateSet);
7084 }
7085
7086 for (BuiltinCandidateTypeSet::iterator
7087 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7088 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7089 MemPtr != MemPtrEnd; ++MemPtr) {
7090 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7091 continue;
7092
7093 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7094 CandidateSet);
7095 }
7096 }
7097 }
7098
7099 // C++ [over.built]p19:
7100 //
7101 // For every pair (T, VQ), where T is any type and VQ is either
7102 // volatile or empty, there exist candidate operator functions
7103 // of the form
7104 //
7105 // T*VQ& operator=(T*VQ&, T*);
7106 //
7107 // C++ [over.built]p21:
7108 //
7109 // For every pair (T, VQ), where T is a cv-qualified or
7110 // cv-unqualified object type and VQ is either volatile or
7111 // empty, there exist candidate operator functions of the form
7112 //
7113 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7114 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7115 void addAssignmentPointerOverloads(bool isEqualOp) {
7116 /// Set of (canonical) types that we've already handled.
7117 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7118
7119 for (BuiltinCandidateTypeSet::iterator
7120 Ptr = CandidateTypes[0].pointer_begin(),
7121 PtrEnd = CandidateTypes[0].pointer_end();
7122 Ptr != PtrEnd; ++Ptr) {
7123 // If this is operator=, keep track of the builtin candidates we added.
7124 if (isEqualOp)
7125 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007126 else if (!(*Ptr)->getPointeeType()->isObjectType())
7127 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007128
7129 // non-volatile version
7130 QualType ParamTypes[2] = {
7131 S.Context.getLValueReferenceType(*Ptr),
7132 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7133 };
7134 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7135 /*IsAssigmentOperator=*/ isEqualOp);
7136
Douglas Gregor5bee2582012-06-04 00:15:09 +00007137 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7138 VisibleTypeConversionsQuals.hasVolatile();
7139 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007140 // volatile version
7141 ParamTypes[0] =
7142 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7143 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7144 /*IsAssigmentOperator=*/isEqualOp);
7145 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007146
7147 if (!(*Ptr).isRestrictQualified() &&
7148 VisibleTypeConversionsQuals.hasRestrict()) {
7149 // restrict version
7150 ParamTypes[0]
7151 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7152 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7153 /*IsAssigmentOperator=*/isEqualOp);
7154
7155 if (NeedVolatile) {
7156 // volatile restrict version
7157 ParamTypes[0]
7158 = S.Context.getLValueReferenceType(
7159 S.Context.getCVRQualifiedType(*Ptr,
7160 (Qualifiers::Volatile |
7161 Qualifiers::Restrict)));
7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7163 CandidateSet,
7164 /*IsAssigmentOperator=*/isEqualOp);
7165 }
7166 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007167 }
7168
7169 if (isEqualOp) {
7170 for (BuiltinCandidateTypeSet::iterator
7171 Ptr = CandidateTypes[1].pointer_begin(),
7172 PtrEnd = CandidateTypes[1].pointer_end();
7173 Ptr != PtrEnd; ++Ptr) {
7174 // Make sure we don't add the same candidate twice.
7175 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7176 continue;
7177
Chandler Carruth8e543b32010-12-12 08:17:55 +00007178 QualType ParamTypes[2] = {
7179 S.Context.getLValueReferenceType(*Ptr),
7180 *Ptr,
7181 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007182
7183 // non-volatile version
7184 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7185 /*IsAssigmentOperator=*/true);
7186
Douglas Gregor5bee2582012-06-04 00:15:09 +00007187 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7188 VisibleTypeConversionsQuals.hasVolatile();
7189 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007190 // volatile version
7191 ParamTypes[0] =
7192 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7194 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007196
7197 if (!(*Ptr).isRestrictQualified() &&
7198 VisibleTypeConversionsQuals.hasRestrict()) {
7199 // restrict version
7200 ParamTypes[0]
7201 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7203 CandidateSet, /*IsAssigmentOperator=*/true);
7204
7205 if (NeedVolatile) {
7206 // volatile restrict version
7207 ParamTypes[0]
7208 = S.Context.getLValueReferenceType(
7209 S.Context.getCVRQualifiedType(*Ptr,
7210 (Qualifiers::Volatile |
7211 Qualifiers::Restrict)));
7212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7213 CandidateSet, /*IsAssigmentOperator=*/true);
7214
7215 }
7216 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007217 }
7218 }
7219 }
7220
7221 // C++ [over.built]p18:
7222 //
7223 // For every triple (L, VQ, R), where L is an arithmetic type,
7224 // VQ is either volatile or empty, and R is a promoted
7225 // arithmetic type, there exist candidate operator functions of
7226 // the form
7227 //
7228 // VQ L& operator=(VQ L&, R);
7229 // VQ L& operator*=(VQ L&, R);
7230 // VQ L& operator/=(VQ L&, R);
7231 // VQ L& operator+=(VQ L&, R);
7232 // VQ L& operator-=(VQ L&, R);
7233 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007234 if (!HasArithmeticOrEnumeralCandidateType)
7235 return;
7236
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7238 for (unsigned Right = FirstPromotedArithmeticType;
7239 Right < LastPromotedArithmeticType; ++Right) {
7240 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007241 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007242
7243 // Add this built-in operator as a candidate (VQ is empty).
7244 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007245 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007246 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7247 /*IsAssigmentOperator=*/isEqualOp);
7248
7249 // Add this built-in operator as a candidate (VQ is 'volatile').
7250 if (VisibleTypeConversionsQuals.hasVolatile()) {
7251 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007252 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007253 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007254 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7255 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007256 /*IsAssigmentOperator=*/isEqualOp);
7257 }
7258 }
7259 }
7260
7261 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7262 for (BuiltinCandidateTypeSet::iterator
7263 Vec1 = CandidateTypes[0].vector_begin(),
7264 Vec1End = CandidateTypes[0].vector_end();
7265 Vec1 != Vec1End; ++Vec1) {
7266 for (BuiltinCandidateTypeSet::iterator
7267 Vec2 = CandidateTypes[1].vector_begin(),
7268 Vec2End = CandidateTypes[1].vector_end();
7269 Vec2 != Vec2End; ++Vec2) {
7270 QualType ParamTypes[2];
7271 ParamTypes[1] = *Vec2;
7272 // Add this built-in operator as a candidate (VQ is empty).
7273 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7275 /*IsAssigmentOperator=*/isEqualOp);
7276
7277 // Add this built-in operator as a candidate (VQ is 'volatile').
7278 if (VisibleTypeConversionsQuals.hasVolatile()) {
7279 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7280 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007281 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7282 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 /*IsAssigmentOperator=*/isEqualOp);
7284 }
7285 }
7286 }
7287 }
7288
7289 // C++ [over.built]p22:
7290 //
7291 // For every triple (L, VQ, R), where L is an integral type, VQ
7292 // is either volatile or empty, and R is a promoted integral
7293 // type, there exist candidate operator functions of the form
7294 //
7295 // VQ L& operator%=(VQ L&, R);
7296 // VQ L& operator<<=(VQ L&, R);
7297 // VQ L& operator>>=(VQ L&, R);
7298 // VQ L& operator&=(VQ L&, R);
7299 // VQ L& operator^=(VQ L&, R);
7300 // VQ L& operator|=(VQ L&, R);
7301 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007302 if (!HasArithmeticOrEnumeralCandidateType)
7303 return;
7304
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007305 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7306 for (unsigned Right = FirstPromotedIntegralType;
7307 Right < LastPromotedIntegralType; ++Right) {
7308 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007309 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007310
7311 // Add this built-in operator as a candidate (VQ is empty).
7312 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007313 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7315 if (VisibleTypeConversionsQuals.hasVolatile()) {
7316 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007317 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007318 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7319 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7321 CandidateSet);
7322 }
7323 }
7324 }
7325 }
7326
7327 // C++ [over.operator]p23:
7328 //
7329 // There also exist candidate operator functions of the form
7330 //
7331 // bool operator!(bool);
7332 // bool operator&&(bool, bool);
7333 // bool operator||(bool, bool);
7334 void addExclaimOverload() {
7335 QualType ParamTy = S.Context.BoolTy;
7336 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7337 /*IsAssignmentOperator=*/false,
7338 /*NumContextualBoolArguments=*/1);
7339 }
7340 void addAmpAmpOrPipePipeOverload() {
7341 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7342 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7343 /*IsAssignmentOperator=*/false,
7344 /*NumContextualBoolArguments=*/2);
7345 }
7346
7347 // C++ [over.built]p13:
7348 //
7349 // For every cv-qualified or cv-unqualified object type T there
7350 // exist candidate operator functions of the form
7351 //
7352 // T* operator+(T*, ptrdiff_t); [ABOVE]
7353 // T& operator[](T*, ptrdiff_t);
7354 // T* operator-(T*, ptrdiff_t); [ABOVE]
7355 // T* operator+(ptrdiff_t, T*); [ABOVE]
7356 // T& operator[](ptrdiff_t, T*);
7357 void addSubscriptOverloads() {
7358 for (BuiltinCandidateTypeSet::iterator
7359 Ptr = CandidateTypes[0].pointer_begin(),
7360 PtrEnd = CandidateTypes[0].pointer_end();
7361 Ptr != PtrEnd; ++Ptr) {
7362 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7363 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007364 if (!PointeeType->isObjectType())
7365 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007366
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007367 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7368
7369 // T& operator[](T*, ptrdiff_t)
7370 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7371 }
7372
7373 for (BuiltinCandidateTypeSet::iterator
7374 Ptr = CandidateTypes[1].pointer_begin(),
7375 PtrEnd = CandidateTypes[1].pointer_end();
7376 Ptr != PtrEnd; ++Ptr) {
7377 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7378 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007379 if (!PointeeType->isObjectType())
7380 continue;
7381
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007382 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7383
7384 // T& operator[](ptrdiff_t, T*)
7385 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7386 }
7387 }
7388
7389 // C++ [over.built]p11:
7390 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7391 // C1 is the same type as C2 or is a derived class of C2, T is an object
7392 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7393 // there exist candidate operator functions of the form
7394 //
7395 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7396 //
7397 // where CV12 is the union of CV1 and CV2.
7398 void addArrowStarOverloads() {
7399 for (BuiltinCandidateTypeSet::iterator
7400 Ptr = CandidateTypes[0].pointer_begin(),
7401 PtrEnd = CandidateTypes[0].pointer_end();
7402 Ptr != PtrEnd; ++Ptr) {
7403 QualType C1Ty = (*Ptr);
7404 QualType C1;
7405 QualifierCollector Q1;
7406 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7407 if (!isa<RecordType>(C1))
7408 continue;
7409 // heuristic to reduce number of builtin candidates in the set.
7410 // Add volatile/restrict version only if there are conversions to a
7411 // volatile/restrict type.
7412 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7413 continue;
7414 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7415 continue;
7416 for (BuiltinCandidateTypeSet::iterator
7417 MemPtr = CandidateTypes[1].member_pointer_begin(),
7418 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7419 MemPtr != MemPtrEnd; ++MemPtr) {
7420 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7421 QualType C2 = QualType(mptr->getClass(), 0);
7422 C2 = C2.getUnqualifiedType();
7423 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7424 break;
7425 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7426 // build CV12 T&
7427 QualType T = mptr->getPointeeType();
7428 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7429 T.isVolatileQualified())
7430 continue;
7431 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7432 T.isRestrictQualified())
7433 continue;
7434 T = Q1.apply(S.Context, T);
7435 QualType ResultTy = S.Context.getLValueReferenceType(T);
7436 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7437 }
7438 }
7439 }
7440
7441 // Note that we don't consider the first argument, since it has been
7442 // contextually converted to bool long ago. The candidates below are
7443 // therefore added as binary.
7444 //
7445 // C++ [over.built]p25:
7446 // For every type T, where T is a pointer, pointer-to-member, or scoped
7447 // enumeration type, there exist candidate operator functions of the form
7448 //
7449 // T operator?(bool, T, T);
7450 //
7451 void addConditionalOperatorOverloads() {
7452 /// Set of (canonical) types that we've already handled.
7453 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7454
7455 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7456 for (BuiltinCandidateTypeSet::iterator
7457 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7458 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7459 Ptr != PtrEnd; ++Ptr) {
7460 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7461 continue;
7462
7463 QualType ParamTypes[2] = { *Ptr, *Ptr };
7464 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7465 }
7466
7467 for (BuiltinCandidateTypeSet::iterator
7468 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7469 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7470 MemPtr != MemPtrEnd; ++MemPtr) {
7471 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7472 continue;
7473
7474 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7475 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7476 }
7477
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007478 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007479 for (BuiltinCandidateTypeSet::iterator
7480 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7481 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7482 Enum != EnumEnd; ++Enum) {
7483 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7484 continue;
7485
7486 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7487 continue;
7488
7489 QualType ParamTypes[2] = { *Enum, *Enum };
7490 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7491 }
7492 }
7493 }
7494 }
7495};
7496
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007497} // end anonymous namespace
7498
7499/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7500/// operator overloads to the candidate set (C++ [over.built]), based
7501/// on the operator @p Op and the arguments given. For example, if the
7502/// operator is a binary '+', this routine might add "int
7503/// operator+(int, int)" to cover integer addition.
7504void
7505Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7506 SourceLocation OpLoc,
7507 Expr **Args, unsigned NumArgs,
7508 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007509 // Find all of the types that the arguments can convert to, but only
7510 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007511 // that make use of these types. Also record whether we encounter non-record
7512 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007513 Qualifiers VisibleTypeConversionsQuals;
7514 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007515 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7516 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007517
7518 bool HasNonRecordCandidateType = false;
7519 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007520 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007521 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7522 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7523 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7524 OpLoc,
7525 true,
7526 (Op == OO_Exclaim ||
7527 Op == OO_AmpAmp ||
7528 Op == OO_PipePipe),
7529 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007530 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7531 CandidateTypes[ArgIdx].hasNonRecordTypes();
7532 HasArithmeticOrEnumeralCandidateType =
7533 HasArithmeticOrEnumeralCandidateType ||
7534 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007535 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007536
Chandler Carruth00a38332010-12-13 01:44:01 +00007537 // Exit early when no non-record types have been added to the candidate set
7538 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007539 //
7540 // We can't exit early for !, ||, or &&, since there we have always have
7541 // 'bool' overloads.
7542 if (!HasNonRecordCandidateType &&
7543 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007544 return;
7545
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007546 // Setup an object to manage the common state for building overloads.
7547 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7548 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007549 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007550 CandidateTypes, CandidateSet);
7551
7552 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007553 switch (Op) {
7554 case OO_None:
7555 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007556 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007557
Chandler Carruth5184de02010-12-12 08:51:33 +00007558 case OO_New:
7559 case OO_Delete:
7560 case OO_Array_New:
7561 case OO_Array_Delete:
7562 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007563 llvm_unreachable(
7564 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007565
7566 case OO_Comma:
7567 case OO_Arrow:
7568 // C++ [over.match.oper]p3:
7569 // -- For the operator ',', the unary operator '&', or the
7570 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007571 break;
7572
7573 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007574 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007575 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007576 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007577
7578 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007579 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007581 } else {
7582 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7583 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7584 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007585 break;
7586
Chandler Carruth5184de02010-12-12 08:51:33 +00007587 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007588 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007589 OpBuilder.addUnaryStarPointerOverloads();
7590 else
7591 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7592 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007593
Chandler Carruth5184de02010-12-12 08:51:33 +00007594 case OO_Slash:
7595 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007596 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007597
7598 case OO_PlusPlus:
7599 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007600 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7601 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007602 break;
7603
Douglas Gregor84605ae2009-08-24 13:43:27 +00007604 case OO_EqualEqual:
7605 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007606 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007607 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007608
Douglas Gregora11693b2008-11-12 17:17:38 +00007609 case OO_Less:
7610 case OO_Greater:
7611 case OO_LessEqual:
7612 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007613 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007614 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7615 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007616
Douglas Gregora11693b2008-11-12 17:17:38 +00007617 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007618 case OO_Caret:
7619 case OO_Pipe:
7620 case OO_LessLess:
7621 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007622 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007623 break;
7624
Chandler Carruth5184de02010-12-12 08:51:33 +00007625 case OO_Amp: // '&' is either unary or binary
7626 if (NumArgs == 1)
7627 // C++ [over.match.oper]p3:
7628 // -- For the operator ',', the unary operator '&', or the
7629 // operator '->', the built-in candidates set is empty.
7630 break;
7631
7632 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7633 break;
7634
7635 case OO_Tilde:
7636 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7637 break;
7638
Douglas Gregora11693b2008-11-12 17:17:38 +00007639 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007640 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007641 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007642
7643 case OO_PlusEqual:
7644 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007645 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007646 // Fall through.
7647
7648 case OO_StarEqual:
7649 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007651 break;
7652
7653 case OO_PercentEqual:
7654 case OO_LessLessEqual:
7655 case OO_GreaterGreaterEqual:
7656 case OO_AmpEqual:
7657 case OO_CaretEqual:
7658 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007660 break;
7661
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 case OO_Exclaim:
7663 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007664 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007665
Douglas Gregora11693b2008-11-12 17:17:38 +00007666 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 case OO_PipePipe:
7668 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007669 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007670
7671 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007672 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007673 break;
7674
7675 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007676 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007677 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007678
7679 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007680 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007681 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7682 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007683 }
7684}
7685
Douglas Gregore254f902009-02-04 00:32:51 +00007686/// \brief Add function candidates found via argument-dependent lookup
7687/// to the set of overloading candidates.
7688///
7689/// This routine performs argument-dependent name lookup based on the
7690/// given function name (which may also be an operator name) and adds
7691/// all of the overload candidates found by ADL to the overload
7692/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007693void
Douglas Gregore254f902009-02-04 00:32:51 +00007694Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007695 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007696 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007697 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007698 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00007699 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00007700 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007701
John McCall91f61fc2010-01-26 06:04:06 +00007702 // FIXME: This approach for uniquing ADL results (and removing
7703 // redundant candidates from the set) relies on pointer-equality,
7704 // which means we need to key off the canonical decl. However,
7705 // always going back to the canonical decl might not get us the
7706 // right set of default arguments. What default arguments are
7707 // we supposed to consider on ADL candidates, anyway?
7708
Douglas Gregorcabea402009-09-22 15:41:20 +00007709 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00007710 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00007711
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007712 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007713 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7714 CandEnd = CandidateSet.end();
7715 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007716 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007717 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007718 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007719 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007720 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007721
7722 // For each of the ADL candidates we found, add it to the overload
7723 // set.
John McCall8fe68082010-01-26 07:16:45 +00007724 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007725 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007727 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007728 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007729
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007730 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7731 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007732 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007733 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007734 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007735 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007736 }
Douglas Gregore254f902009-02-04 00:32:51 +00007737}
7738
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007739/// isBetterOverloadCandidate - Determines whether the first overload
7740/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007741bool
John McCall5c32be02010-08-24 20:38:10 +00007742isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007743 const OverloadCandidate &Cand1,
7744 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007745 SourceLocation Loc,
7746 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007747 // Define viable functions to be better candidates than non-viable
7748 // functions.
7749 if (!Cand2.Viable)
7750 return Cand1.Viable;
7751 else if (!Cand1.Viable)
7752 return false;
7753
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007754 // C++ [over.match.best]p1:
7755 //
7756 // -- if F is a static member function, ICS1(F) is defined such
7757 // that ICS1(F) is neither better nor worse than ICS1(G) for
7758 // any function G, and, symmetrically, ICS1(G) is neither
7759 // better nor worse than ICS1(F).
7760 unsigned StartArg = 0;
7761 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7762 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007763
Douglas Gregord3cb3562009-07-07 23:38:56 +00007764 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007765 // A viable function F1 is defined to be a better function than another
7766 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007767 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007768 unsigned NumArgs = Cand1.NumConversions;
7769 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007770 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007771 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007772 switch (CompareImplicitConversionSequences(S,
7773 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007774 Cand2.Conversions[ArgIdx])) {
7775 case ImplicitConversionSequence::Better:
7776 // Cand1 has a better conversion sequence.
7777 HasBetterConversion = true;
7778 break;
7779
7780 case ImplicitConversionSequence::Worse:
7781 // Cand1 can't be better than Cand2.
7782 return false;
7783
7784 case ImplicitConversionSequence::Indistinguishable:
7785 // Do nothing.
7786 break;
7787 }
7788 }
7789
Mike Stump11289f42009-09-09 15:08:12 +00007790 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007791 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007792 if (HasBetterConversion)
7793 return true;
7794
Mike Stump11289f42009-09-09 15:08:12 +00007795 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007796 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007797 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007798 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7799 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007800
7801 // -- F1 and F2 are function template specializations, and the function
7802 // template for F1 is more specialized than the template for F2
7803 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007804 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007805 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007806 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007807 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007808 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7809 Cand2.Function->getPrimaryTemplate(),
7810 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007811 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007812 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007813 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007814 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007816
Douglas Gregora1f013e2008-11-07 22:36:19 +00007817 // -- the context is an initialization by user-defined conversion
7818 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7819 // from the return type of F1 to the destination type (i.e.,
7820 // the type of the entity being initialized) is a better
7821 // conversion sequence than the standard conversion sequence
7822 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007823 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007824 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007825 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007826 // First check whether we prefer one of the conversion functions over the
7827 // other. This only distinguishes the results in non-standard, extension
7828 // cases such as the conversion from a lambda closure type to a function
7829 // pointer or block.
7830 ImplicitConversionSequence::CompareKind FuncResult
7831 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7832 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7833 return FuncResult;
7834
John McCall5c32be02010-08-24 20:38:10 +00007835 switch (CompareStandardConversionSequences(S,
7836 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007837 Cand2.FinalConversion)) {
7838 case ImplicitConversionSequence::Better:
7839 // Cand1 has a better conversion sequence.
7840 return true;
7841
7842 case ImplicitConversionSequence::Worse:
7843 // Cand1 can't be better than Cand2.
7844 return false;
7845
7846 case ImplicitConversionSequence::Indistinguishable:
7847 // Do nothing
7848 break;
7849 }
7850 }
7851
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007852 return false;
7853}
7854
Mike Stump11289f42009-09-09 15:08:12 +00007855/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007856/// within an overload candidate set.
7857///
James Dennettffad8b72012-06-22 08:10:18 +00007858/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007859/// which overload resolution occurs.
7860///
James Dennettffad8b72012-06-22 08:10:18 +00007861/// \param Best If overload resolution was successful or found a deleted
7862/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007863///
7864/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007865OverloadingResult
7866OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007867 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007868 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007869 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007870 Best = end();
7871 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7872 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007874 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007875 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007876 }
7877
7878 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007879 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007880 return OR_No_Viable_Function;
7881
7882 // Make sure that this function is better than every other viable
7883 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007884 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007885 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007886 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007887 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007888 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007889 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007890 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007891 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007892 }
Mike Stump11289f42009-09-09 15:08:12 +00007893
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007894 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007895 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007896 (Best->Function->isDeleted() ||
7897 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007898 return OR_Deleted;
7899
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007900 return OR_Success;
7901}
7902
John McCall53262c92010-01-12 02:15:36 +00007903namespace {
7904
7905enum OverloadCandidateKind {
7906 oc_function,
7907 oc_method,
7908 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007909 oc_function_template,
7910 oc_method_template,
7911 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007912 oc_implicit_default_constructor,
7913 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007914 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007915 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007916 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007917 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007918};
7919
John McCalle1ac8d12010-01-13 00:25:19 +00007920OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7921 FunctionDecl *Fn,
7922 std::string &Description) {
7923 bool isTemplate = false;
7924
7925 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7926 isTemplate = true;
7927 Description = S.getTemplateArgumentBindingsText(
7928 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7929 }
John McCallfd0b2f82010-01-06 09:43:14 +00007930
7931 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007932 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007933 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007934
Sebastian Redl08905022011-02-05 19:23:19 +00007935 if (Ctor->getInheritedConstructor())
7936 return oc_implicit_inherited_constructor;
7937
Alexis Hunt119c10e2011-05-25 23:16:36 +00007938 if (Ctor->isDefaultConstructor())
7939 return oc_implicit_default_constructor;
7940
7941 if (Ctor->isMoveConstructor())
7942 return oc_implicit_move_constructor;
7943
7944 assert(Ctor->isCopyConstructor() &&
7945 "unexpected sort of implicit constructor");
7946 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007947 }
7948
7949 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7950 // This actually gets spelled 'candidate function' for now, but
7951 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007952 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007953 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007954
Alexis Hunt119c10e2011-05-25 23:16:36 +00007955 if (Meth->isMoveAssignmentOperator())
7956 return oc_implicit_move_assignment;
7957
Douglas Gregor12695102012-02-10 08:36:38 +00007958 if (Meth->isCopyAssignmentOperator())
7959 return oc_implicit_copy_assignment;
7960
7961 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7962 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007963 }
7964
John McCalle1ac8d12010-01-13 00:25:19 +00007965 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007966}
7967
Sebastian Redl08905022011-02-05 19:23:19 +00007968void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7969 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7970 if (!Ctor) return;
7971
7972 Ctor = Ctor->getInheritedConstructor();
7973 if (!Ctor) return;
7974
7975 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7976}
7977
John McCall53262c92010-01-12 02:15:36 +00007978} // end anonymous namespace
7979
7980// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007981void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007982 std::string FnDesc;
7983 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007984 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7985 << (unsigned) K << FnDesc;
7986 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7987 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007988 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007989}
7990
Douglas Gregorb491ed32011-02-19 21:32:49 +00007991//Notes the location of all overload candidates designated through
7992// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007993void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007994 assert(OverloadedExpr->getType() == Context.OverloadTy);
7995
7996 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7997 OverloadExpr *OvlExpr = Ovl.Expression;
7998
7999 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8000 IEnd = OvlExpr->decls_end();
8001 I != IEnd; ++I) {
8002 if (FunctionTemplateDecl *FunTmpl =
8003 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008004 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008005 } else if (FunctionDecl *Fun
8006 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008007 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008008 }
8009 }
8010}
8011
John McCall0d1da222010-01-12 00:44:57 +00008012/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8013/// "lead" diagnostic; it will be given two arguments, the source and
8014/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008015void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8016 Sema &S,
8017 SourceLocation CaretLoc,
8018 const PartialDiagnostic &PDiag) const {
8019 S.Diag(CaretLoc, PDiag)
8020 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008021 // FIXME: The note limiting machinery is borrowed from
8022 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8023 // refactoring here.
8024 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8025 unsigned CandsShown = 0;
8026 AmbiguousConversionSequence::const_iterator I, E;
8027 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8028 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8029 break;
8030 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008031 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008032 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008033 if (I != E)
8034 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008035}
8036
John McCall0d1da222010-01-12 00:44:57 +00008037namespace {
8038
John McCall6a61b522010-01-13 09:16:55 +00008039void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8040 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8041 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008042 assert(Cand->Function && "for now, candidate must be a function");
8043 FunctionDecl *Fn = Cand->Function;
8044
8045 // There's a conversion slot for the object argument if this is a
8046 // non-constructor method. Note that 'I' corresponds the
8047 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008048 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008049 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008050 if (I == 0)
8051 isObjectArgument = true;
8052 else
8053 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008054 }
8055
John McCalle1ac8d12010-01-13 00:25:19 +00008056 std::string FnDesc;
8057 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8058
John McCall6a61b522010-01-13 09:16:55 +00008059 Expr *FromExpr = Conv.Bad.FromExpr;
8060 QualType FromTy = Conv.Bad.getFromType();
8061 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008062
John McCallfb7ad0f2010-02-02 02:42:52 +00008063 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008064 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008065 Expr *E = FromExpr->IgnoreParens();
8066 if (isa<UnaryOperator>(E))
8067 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008068 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008069
8070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8071 << (unsigned) FnKind << FnDesc
8072 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8073 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008074 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008075 return;
8076 }
8077
John McCall6d174642010-01-23 08:10:49 +00008078 // Do some hand-waving analysis to see if the non-viability is due
8079 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008080 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8081 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8082 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8083 CToTy = RT->getPointeeType();
8084 else {
8085 // TODO: detect and diagnose the full richness of const mismatches.
8086 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8087 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8088 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8089 }
8090
8091 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8092 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008093 Qualifiers FromQs = CFromTy.getQualifiers();
8094 Qualifiers ToQs = CToTy.getQualifiers();
8095
8096 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8098 << (unsigned) FnKind << FnDesc
8099 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8100 << FromTy
8101 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8102 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008103 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008104 return;
8105 }
8106
John McCall31168b02011-06-15 23:02:42 +00008107 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008109 << (unsigned) FnKind << FnDesc
8110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8111 << FromTy
8112 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8113 << (unsigned) isObjectArgument << I+1;
8114 MaybeEmitInheritedConstructorNote(S, Fn);
8115 return;
8116 }
8117
Douglas Gregoraec25842011-04-26 23:16:46 +00008118 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8120 << (unsigned) FnKind << FnDesc
8121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8122 << FromTy
8123 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8124 << (unsigned) isObjectArgument << I+1;
8125 MaybeEmitInheritedConstructorNote(S, Fn);
8126 return;
8127 }
8128
John McCall47000992010-01-14 03:28:57 +00008129 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8130 assert(CVR && "unexpected qualifiers mismatch");
8131
8132 if (isObjectArgument) {
8133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8134 << (unsigned) FnKind << FnDesc
8135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8136 << FromTy << (CVR - 1);
8137 } else {
8138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8139 << (unsigned) FnKind << FnDesc
8140 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8141 << FromTy << (CVR - 1) << I+1;
8142 }
Sebastian Redl08905022011-02-05 19:23:19 +00008143 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008144 return;
8145 }
8146
Sebastian Redla72462c2011-09-24 17:48:32 +00008147 // Special diagnostic for failure to convert an initializer list, since
8148 // telling the user that it has type void is not useful.
8149 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8151 << (unsigned) FnKind << FnDesc
8152 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8153 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8154 MaybeEmitInheritedConstructorNote(S, Fn);
8155 return;
8156 }
8157
John McCall6d174642010-01-23 08:10:49 +00008158 // Diagnose references or pointers to incomplete types differently,
8159 // since it's far from impossible that the incompleteness triggered
8160 // the failure.
8161 QualType TempFromTy = FromTy.getNonReferenceType();
8162 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8163 TempFromTy = PTy->getPointeeType();
8164 if (TempFromTy->isIncompleteType()) {
8165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8166 << (unsigned) FnKind << FnDesc
8167 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8168 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008169 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008170 return;
8171 }
8172
Douglas Gregor56f2e342010-06-30 23:01:39 +00008173 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008174 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008175 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8176 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8177 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8178 FromPtrTy->getPointeeType()) &&
8179 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8180 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008182 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008183 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008184 }
8185 } else if (const ObjCObjectPointerType *FromPtrTy
8186 = FromTy->getAs<ObjCObjectPointerType>()) {
8187 if (const ObjCObjectPointerType *ToPtrTy
8188 = ToTy->getAs<ObjCObjectPointerType>())
8189 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8190 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8191 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8192 FromPtrTy->getPointeeType()) &&
8193 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008194 BaseToDerivedConversion = 2;
8195 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008196 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8197 !FromTy->isIncompleteType() &&
8198 !ToRefTy->getPointeeType()->isIncompleteType() &&
8199 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8200 BaseToDerivedConversion = 3;
8201 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8202 ToTy.getNonReferenceType().getCanonicalType() ==
8203 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008204 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8205 << (unsigned) FnKind << FnDesc
8206 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8207 << (unsigned) isObjectArgument << I + 1;
8208 MaybeEmitInheritedConstructorNote(S, Fn);
8209 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008210 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008212
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008213 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008214 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008215 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008216 << (unsigned) FnKind << FnDesc
8217 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008218 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008219 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008220 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008221 return;
8222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008223
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008224 if (isa<ObjCObjectPointerType>(CFromTy) &&
8225 isa<PointerType>(CToTy)) {
8226 Qualifiers FromQs = CFromTy.getQualifiers();
8227 Qualifiers ToQs = CToTy.getQualifiers();
8228 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8230 << (unsigned) FnKind << FnDesc
8231 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8232 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8233 MaybeEmitInheritedConstructorNote(S, Fn);
8234 return;
8235 }
8236 }
8237
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008238 // Emit the generic diagnostic and, optionally, add the hints to it.
8239 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8240 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008241 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008242 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8243 << (unsigned) (Cand->Fix.Kind);
8244
8245 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008246 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8247 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008248 FDiag << *HI;
8249 S.Diag(Fn->getLocation(), FDiag);
8250
Sebastian Redl08905022011-02-05 19:23:19 +00008251 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008252}
8253
8254void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8255 unsigned NumFormalArgs) {
8256 // TODO: treat calls to a missing default constructor as a special case
8257
8258 FunctionDecl *Fn = Cand->Function;
8259 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8260
8261 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008262
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008263 // With invalid overloaded operators, it's possible that we think we
8264 // have an arity mismatch when it fact it looks like we have the
8265 // right number of arguments, because only overloaded operators have
8266 // the weird behavior of overloading member and non-member functions.
8267 // Just don't report anything.
8268 if (Fn->isInvalidDecl() &&
8269 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8270 return;
8271
John McCall6a61b522010-01-13 09:16:55 +00008272 // at least / at most / exactly
8273 unsigned mode, modeCount;
8274 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008275 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8276 (Cand->FailureKind == ovl_fail_bad_deduction &&
8277 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008278 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008279 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008280 mode = 0; // "at least"
8281 else
8282 mode = 2; // "exactly"
8283 modeCount = MinParams;
8284 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008285 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8286 (Cand->FailureKind == ovl_fail_bad_deduction &&
8287 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008288 if (MinParams != FnTy->getNumArgs())
8289 mode = 1; // "at most"
8290 else
8291 mode = 2; // "exactly"
8292 modeCount = FnTy->getNumArgs();
8293 }
8294
8295 std::string Description;
8296 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8297
Richard Smith10ff50d2012-05-11 05:16:41 +00008298 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8300 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8301 << Fn->getParamDecl(0) << NumFormalArgs;
8302 else
8303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8304 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8305 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008306 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008307}
8308
John McCall8b9ed552010-02-01 18:53:26 +00008309/// Diagnose a failed template-argument deduction.
8310void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008311 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008312 FunctionDecl *Fn = Cand->Function; // pattern
8313
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008314 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008315 NamedDecl *ParamD;
8316 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8317 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8318 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008319 switch (Cand->DeductionFailure.Result) {
8320 case Sema::TDK_Success:
8321 llvm_unreachable("TDK_success while diagnosing bad deduction");
8322
8323 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008324 assert(ParamD && "no parameter found for incomplete deduction result");
8325 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8326 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008327 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008328 return;
8329 }
8330
John McCall42d7d192010-08-05 09:05:08 +00008331 case Sema::TDK_Underqualified: {
8332 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8333 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8334
8335 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8336
8337 // Param will have been canonicalized, but it should just be a
8338 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008339 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008340 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008341 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008342 assert(S.Context.hasSameType(Param, NonCanonParam));
8343
8344 // Arg has also been canonicalized, but there's nothing we can do
8345 // about that. It also doesn't matter as much, because it won't
8346 // have any template parameters in it (because deduction isn't
8347 // done on dependent types).
8348 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8349
8350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8351 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008352 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008353 return;
8354 }
8355
8356 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008357 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008358 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008359 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008360 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008361 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008362 which = 1;
8363 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008364 which = 2;
8365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008366
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008367 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008369 << *Cand->DeductionFailure.getFirstArg()
8370 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008371 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008372 return;
8373 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008374
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008375 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008376 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008377 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008378 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008379 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8380 << ParamD->getDeclName();
8381 else {
8382 int index = 0;
8383 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8384 index = TTP->getIndex();
8385 else if (NonTypeTemplateParmDecl *NTTP
8386 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8387 index = NTTP->getIndex();
8388 else
8389 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008390 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008391 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8392 << (index + 1);
8393 }
Sebastian Redl08905022011-02-05 19:23:19 +00008394 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008395 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008396
Douglas Gregor02eb4832010-05-08 18:13:28 +00008397 case Sema::TDK_TooManyArguments:
8398 case Sema::TDK_TooFewArguments:
8399 DiagnoseArityMismatch(S, Cand, NumArgs);
8400 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008401
8402 case Sema::TDK_InstantiationDepth:
8403 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008404 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008405 return;
8406
8407 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008408 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008409 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008410 if (TemplateArgumentList *Args =
8411 Cand->DeductionFailure.getTemplateArgumentList()) {
8412 TemplateArgString = " ";
8413 TemplateArgString += S.getTemplateArgumentBindingsText(
8414 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8415 }
8416
Richard Smith6f8d2c62012-05-09 05:17:00 +00008417 // If this candidate was disabled by enable_if, say so.
8418 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8419 if (PDiag && PDiag->second.getDiagID() ==
8420 diag::err_typename_nested_not_found_enable_if) {
8421 // FIXME: Use the source range of the condition, and the fully-qualified
8422 // name of the enable_if template. These are both present in PDiag.
8423 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8424 << "'enable_if'" << TemplateArgString;
8425 return;
8426 }
8427
Richard Smith9ca64612012-05-07 09:03:25 +00008428 // Format the SFINAE diagnostic into the argument string.
8429 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8430 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008431 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008432 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008433 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008434 SFINAEArgString = ": ";
8435 R = SourceRange(PDiag->first, PDiag->first);
8436 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8437 }
8438
Douglas Gregord09efd42010-05-08 20:07:26 +00008439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008440 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008441 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008442 return;
8443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008444
John McCall8b9ed552010-02-01 18:53:26 +00008445 // TODO: diagnose these individually, then kill off
8446 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008447 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008448 case Sema::TDK_FailedOverloadResolution:
8449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008450 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008451 return;
8452 }
8453}
8454
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008455/// CUDA: diagnose an invalid call across targets.
8456void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8457 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8458 FunctionDecl *Callee = Cand->Function;
8459
8460 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8461 CalleeTarget = S.IdentifyCUDATarget(Callee);
8462
8463 std::string FnDesc;
8464 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8465
8466 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8467 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8468}
8469
John McCall8b9ed552010-02-01 18:53:26 +00008470/// Generates a 'note' diagnostic for an overload candidate. We've
8471/// already generated a primary error at the call site.
8472///
8473/// It really does need to be a single diagnostic with its caret
8474/// pointed at the candidate declaration. Yes, this creates some
8475/// major challenges of technical writing. Yes, this makes pointing
8476/// out problems with specific arguments quite awkward. It's still
8477/// better than generating twenty screens of text for every failed
8478/// overload.
8479///
8480/// It would be great to be able to express per-candidate problems
8481/// more richly for those diagnostic clients that cared, but we'd
8482/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008483void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008484 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008485 FunctionDecl *Fn = Cand->Function;
8486
John McCall12f97bc2010-01-08 04:41:39 +00008487 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008488 if (Cand->Viable && (Fn->isDeleted() ||
8489 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008490 std::string FnDesc;
8491 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008492
8493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008494 << FnKind << FnDesc
8495 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008496 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008497 return;
John McCall12f97bc2010-01-08 04:41:39 +00008498 }
8499
John McCalle1ac8d12010-01-13 00:25:19 +00008500 // We don't really have anything else to say about viable candidates.
8501 if (Cand->Viable) {
8502 S.NoteOverloadCandidate(Fn);
8503 return;
8504 }
John McCall0d1da222010-01-12 00:44:57 +00008505
John McCall6a61b522010-01-13 09:16:55 +00008506 switch (Cand->FailureKind) {
8507 case ovl_fail_too_many_arguments:
8508 case ovl_fail_too_few_arguments:
8509 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008510
John McCall6a61b522010-01-13 09:16:55 +00008511 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008512 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008513
John McCallfe796dd2010-01-23 05:17:32 +00008514 case ovl_fail_trivial_conversion:
8515 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008516 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008517 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008518
John McCall65eb8792010-02-25 01:37:24 +00008519 case ovl_fail_bad_conversion: {
8520 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008521 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008522 if (Cand->Conversions[I].isBad())
8523 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008524
John McCall6a61b522010-01-13 09:16:55 +00008525 // FIXME: this currently happens when we're called from SemaInit
8526 // when user-conversion overload fails. Figure out how to handle
8527 // those conditions and diagnose them well.
8528 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008529 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008530
8531 case ovl_fail_bad_target:
8532 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008533 }
John McCalld3224162010-01-08 00:58:21 +00008534}
8535
8536void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8537 // Desugar the type of the surrogate down to a function type,
8538 // retaining as many typedefs as possible while still showing
8539 // the function type (and, therefore, its parameter types).
8540 QualType FnType = Cand->Surrogate->getConversionType();
8541 bool isLValueReference = false;
8542 bool isRValueReference = false;
8543 bool isPointer = false;
8544 if (const LValueReferenceType *FnTypeRef =
8545 FnType->getAs<LValueReferenceType>()) {
8546 FnType = FnTypeRef->getPointeeType();
8547 isLValueReference = true;
8548 } else if (const RValueReferenceType *FnTypeRef =
8549 FnType->getAs<RValueReferenceType>()) {
8550 FnType = FnTypeRef->getPointeeType();
8551 isRValueReference = true;
8552 }
8553 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8554 FnType = FnTypePtr->getPointeeType();
8555 isPointer = true;
8556 }
8557 // Desugar down to a function type.
8558 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8559 // Reconstruct the pointer/reference as appropriate.
8560 if (isPointer) FnType = S.Context.getPointerType(FnType);
8561 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8562 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8563
8564 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8565 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008566 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008567}
8568
8569void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00008570 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00008571 SourceLocation OpLoc,
8572 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008573 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008574 std::string TypeStr("operator");
8575 TypeStr += Opc;
8576 TypeStr += "(";
8577 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008578 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008579 TypeStr += ")";
8580 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8581 } else {
8582 TypeStr += ", ";
8583 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8584 TypeStr += ")";
8585 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8586 }
8587}
8588
8589void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8590 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008591 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008592 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8593 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008594 if (ICS.isBad()) break; // all meaningless after first invalid
8595 if (!ICS.isAmbiguous()) continue;
8596
John McCall5c32be02010-08-24 20:38:10 +00008597 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008598 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008599 }
8600}
8601
John McCall3712d9e2010-01-15 23:32:50 +00008602SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8603 if (Cand->Function)
8604 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008605 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008606 return Cand->Surrogate->getLocation();
8607 return SourceLocation();
8608}
8609
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008610static unsigned
8611RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008612 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008613 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008614 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008615
Douglas Gregorc5c01a62012-09-13 21:01:57 +00008616 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008617 case Sema::TDK_Incomplete:
8618 return 1;
8619
8620 case Sema::TDK_Underqualified:
8621 case Sema::TDK_Inconsistent:
8622 return 2;
8623
8624 case Sema::TDK_SubstitutionFailure:
8625 case Sema::TDK_NonDeducedMismatch:
8626 return 3;
8627
8628 case Sema::TDK_InstantiationDepth:
8629 case Sema::TDK_FailedOverloadResolution:
8630 return 4;
8631
8632 case Sema::TDK_InvalidExplicitArguments:
8633 return 5;
8634
8635 case Sema::TDK_TooManyArguments:
8636 case Sema::TDK_TooFewArguments:
8637 return 6;
8638 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008639 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008640}
8641
John McCallad2587a2010-01-12 00:48:53 +00008642struct CompareOverloadCandidatesForDisplay {
8643 Sema &S;
8644 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008645
8646 bool operator()(const OverloadCandidate *L,
8647 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008648 // Fast-path this check.
8649 if (L == R) return false;
8650
John McCall12f97bc2010-01-08 04:41:39 +00008651 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008652 if (L->Viable) {
8653 if (!R->Viable) return true;
8654
8655 // TODO: introduce a tri-valued comparison for overload
8656 // candidates. Would be more worthwhile if we had a sort
8657 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008658 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8659 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008660 } else if (R->Viable)
8661 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008662
John McCall3712d9e2010-01-15 23:32:50 +00008663 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008664
John McCall3712d9e2010-01-15 23:32:50 +00008665 // Criteria by which we can sort non-viable candidates:
8666 if (!L->Viable) {
8667 // 1. Arity mismatches come after other candidates.
8668 if (L->FailureKind == ovl_fail_too_many_arguments ||
8669 L->FailureKind == ovl_fail_too_few_arguments)
8670 return false;
8671 if (R->FailureKind == ovl_fail_too_many_arguments ||
8672 R->FailureKind == ovl_fail_too_few_arguments)
8673 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008674
John McCallfe796dd2010-01-23 05:17:32 +00008675 // 2. Bad conversions come first and are ordered by the number
8676 // of bad conversions and quality of good conversions.
8677 if (L->FailureKind == ovl_fail_bad_conversion) {
8678 if (R->FailureKind != ovl_fail_bad_conversion)
8679 return true;
8680
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008681 // The conversion that can be fixed with a smaller number of changes,
8682 // comes first.
8683 unsigned numLFixes = L->Fix.NumConversionsFixed;
8684 unsigned numRFixes = R->Fix.NumConversionsFixed;
8685 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8686 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008687 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008688 if (numLFixes < numRFixes)
8689 return true;
8690 else
8691 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008692 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008693
John McCallfe796dd2010-01-23 05:17:32 +00008694 // If there's any ordering between the defined conversions...
8695 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008696 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008697
8698 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008699 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008700 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008701 switch (CompareImplicitConversionSequences(S,
8702 L->Conversions[I],
8703 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008704 case ImplicitConversionSequence::Better:
8705 leftBetter++;
8706 break;
8707
8708 case ImplicitConversionSequence::Worse:
8709 leftBetter--;
8710 break;
8711
8712 case ImplicitConversionSequence::Indistinguishable:
8713 break;
8714 }
8715 }
8716 if (leftBetter > 0) return true;
8717 if (leftBetter < 0) return false;
8718
8719 } else if (R->FailureKind == ovl_fail_bad_conversion)
8720 return false;
8721
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008722 if (L->FailureKind == ovl_fail_bad_deduction) {
8723 if (R->FailureKind != ovl_fail_bad_deduction)
8724 return true;
8725
8726 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8727 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008728 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008729 } else if (R->FailureKind == ovl_fail_bad_deduction)
8730 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008731
John McCall3712d9e2010-01-15 23:32:50 +00008732 // TODO: others?
8733 }
8734
8735 // Sort everything else by location.
8736 SourceLocation LLoc = GetLocationForCandidate(L);
8737 SourceLocation RLoc = GetLocationForCandidate(R);
8738
8739 // Put candidates without locations (e.g. builtins) at the end.
8740 if (LLoc.isInvalid()) return false;
8741 if (RLoc.isInvalid()) return true;
8742
8743 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008744 }
8745};
8746
John McCallfe796dd2010-01-23 05:17:32 +00008747/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008748/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008749void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008750 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008751 assert(!Cand->Viable);
8752
8753 // Don't do anything on failures other than bad conversion.
8754 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8755
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008756 // We only want the FixIts if all the arguments can be corrected.
8757 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008758 // Use a implicit copy initialization to check conversion fixes.
8759 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008760
John McCallfe796dd2010-01-23 05:17:32 +00008761 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008762 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008763 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008764 while (true) {
8765 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8766 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008767 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008768 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008769 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008770 }
John McCallfe796dd2010-01-23 05:17:32 +00008771 }
8772
8773 if (ConvIdx == ConvCount)
8774 return;
8775
John McCall65eb8792010-02-25 01:37:24 +00008776 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8777 "remaining conversion is initialized?");
8778
Douglas Gregoradc7a702010-04-16 17:45:54 +00008779 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008780 // operation somehow.
8781 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008782
8783 const FunctionProtoType* Proto;
8784 unsigned ArgIdx = ConvIdx;
8785
8786 if (Cand->IsSurrogate) {
8787 QualType ConvType
8788 = Cand->Surrogate->getConversionType().getNonReferenceType();
8789 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8790 ConvType = ConvPtrType->getPointeeType();
8791 Proto = ConvType->getAs<FunctionProtoType>();
8792 ArgIdx--;
8793 } else if (Cand->Function) {
8794 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8795 if (isa<CXXMethodDecl>(Cand->Function) &&
8796 !isa<CXXConstructorDecl>(Cand->Function))
8797 ArgIdx--;
8798 } else {
8799 // Builtin binary operator with a bad first conversion.
8800 assert(ConvCount <= 3);
8801 for (; ConvIdx != ConvCount; ++ConvIdx)
8802 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008803 = TryCopyInitialization(S, Args[ConvIdx],
8804 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008805 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008806 /*InOverloadResolution*/ true,
8807 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008808 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008809 return;
8810 }
8811
8812 // Fill in the rest of the conversions.
8813 unsigned NumArgsInProto = Proto->getNumArgs();
8814 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008815 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008816 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008817 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008818 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008819 /*InOverloadResolution=*/true,
8820 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008821 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008822 // Store the FixIt in the candidate if it exists.
8823 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008824 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008825 }
John McCallfe796dd2010-01-23 05:17:32 +00008826 else
8827 Cand->Conversions[ConvIdx].setEllipsis();
8828 }
8829}
8830
John McCalld3224162010-01-08 00:58:21 +00008831} // end anonymous namespace
8832
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008833/// PrintOverloadCandidates - When overload resolution fails, prints
8834/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008835/// set.
John McCall5c32be02010-08-24 20:38:10 +00008836void OverloadCandidateSet::NoteCandidates(Sema &S,
8837 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008838 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00008839 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00008840 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008841 // Sort the candidates by viability and position. Sorting directly would
8842 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008843 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008844 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8845 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008846 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008847 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008848 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008849 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008850 if (Cand->Function || Cand->IsSurrogate)
8851 Cands.push_back(Cand);
8852 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8853 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008854 }
8855 }
8856
John McCallad2587a2010-01-12 00:48:53 +00008857 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008858 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008859
John McCall0d1da222010-01-12 00:44:57 +00008860 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008861
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008862 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00008863 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008864 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008865 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8866 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008867
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008868 // Set an arbitrary limit on the number of candidate functions we'll spam
8869 // the user with. FIXME: This limit should depend on details of the
8870 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00008871 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008872 break;
8873 }
8874 ++CandsShown;
8875
John McCalld3224162010-01-08 00:58:21 +00008876 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008877 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008878 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008879 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008880 else {
8881 assert(Cand->Viable &&
8882 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008883 // Generally we only see ambiguities including viable builtin
8884 // operators if overload resolution got screwed up by an
8885 // ambiguous user-defined conversion.
8886 //
8887 // FIXME: It's quite possible for different conversions to see
8888 // different ambiguities, though.
8889 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008890 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008891 ReportedAmbiguousConversions = true;
8892 }
John McCalld3224162010-01-08 00:58:21 +00008893
John McCall0d1da222010-01-12 00:44:57 +00008894 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008895 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008896 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008897 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008898
8899 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008900 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008901}
8902
Douglas Gregorb491ed32011-02-19 21:32:49 +00008903// [PossiblyAFunctionType] --> [Return]
8904// NonFunctionType --> NonFunctionType
8905// R (A) --> R(A)
8906// R (*)(A) --> R (A)
8907// R (&)(A) --> R (A)
8908// R (S::*)(A) --> R (A)
8909QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8910 QualType Ret = PossiblyAFunctionType;
8911 if (const PointerType *ToTypePtr =
8912 PossiblyAFunctionType->getAs<PointerType>())
8913 Ret = ToTypePtr->getPointeeType();
8914 else if (const ReferenceType *ToTypeRef =
8915 PossiblyAFunctionType->getAs<ReferenceType>())
8916 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008917 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008918 PossiblyAFunctionType->getAs<MemberPointerType>())
8919 Ret = MemTypePtr->getPointeeType();
8920 Ret =
8921 Context.getCanonicalType(Ret).getUnqualifiedType();
8922 return Ret;
8923}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008924
Douglas Gregorb491ed32011-02-19 21:32:49 +00008925// A helper class to help with address of function resolution
8926// - allows us to avoid passing around all those ugly parameters
8927class AddressOfFunctionResolver
8928{
8929 Sema& S;
8930 Expr* SourceExpr;
8931 const QualType& TargetType;
8932 QualType TargetFunctionType; // Extracted function type from target type
8933
8934 bool Complain;
8935 //DeclAccessPair& ResultFunctionAccessPair;
8936 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008937
Douglas Gregorb491ed32011-02-19 21:32:49 +00008938 bool TargetTypeIsNonStaticMemberFunction;
8939 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008940
Douglas Gregorb491ed32011-02-19 21:32:49 +00008941 OverloadExpr::FindResult OvlExprInfo;
8942 OverloadExpr *OvlExpr;
8943 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008944 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008945
Douglas Gregorb491ed32011-02-19 21:32:49 +00008946public:
8947 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8948 const QualType& TargetType, bool Complain)
8949 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8950 Complain(Complain), Context(S.getASTContext()),
8951 TargetTypeIsNonStaticMemberFunction(
8952 !!TargetType->getAs<MemberPointerType>()),
8953 FoundNonTemplateFunction(false),
8954 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8955 OvlExpr(OvlExprInfo.Expression)
8956 {
8957 ExtractUnqualifiedFunctionTypeFromTargetType();
8958
8959 if (!TargetFunctionType->isFunctionType()) {
8960 if (OvlExpr->hasExplicitTemplateArgs()) {
8961 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008962 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008963 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008964
8965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8966 if (!Method->isStatic()) {
8967 // If the target type is a non-function type and the function
8968 // found is a non-static member function, pretend as if that was
8969 // the target, it's the only possible type to end up with.
8970 TargetTypeIsNonStaticMemberFunction = true;
8971
8972 // And skip adding the function if its not in the proper form.
8973 // We'll diagnose this due to an empty set of functions.
8974 if (!OvlExprInfo.HasFormOfMemberPointer)
8975 return;
8976 }
8977 }
8978
Douglas Gregorb491ed32011-02-19 21:32:49 +00008979 Matches.push_back(std::make_pair(dap,Fn));
8980 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008981 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008982 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008983 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008984
8985 if (OvlExpr->hasExplicitTemplateArgs())
8986 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008987
Douglas Gregorb491ed32011-02-19 21:32:49 +00008988 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8989 // C++ [over.over]p4:
8990 // If more than one function is selected, [...]
8991 if (Matches.size() > 1) {
8992 if (FoundNonTemplateFunction)
8993 EliminateAllTemplateMatches();
8994 else
8995 EliminateAllExceptMostSpecializedTemplate();
8996 }
8997 }
8998 }
8999
9000private:
9001 bool isTargetTypeAFunction() const {
9002 return TargetFunctionType->isFunctionType();
9003 }
9004
9005 // [ToType] [Return]
9006
9007 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9008 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9009 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9010 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9011 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9012 }
9013
9014 // return true if any matching specializations were found
9015 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9016 const DeclAccessPair& CurAccessFunPair) {
9017 if (CXXMethodDecl *Method
9018 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9019 // Skip non-static function templates when converting to pointer, and
9020 // static when converting to member pointer.
9021 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9022 return false;
9023 }
9024 else if (TargetTypeIsNonStaticMemberFunction)
9025 return false;
9026
9027 // C++ [over.over]p2:
9028 // If the name is a function template, template argument deduction is
9029 // done (14.8.2.2), and if the argument deduction succeeds, the
9030 // resulting template argument list is used to generate a single
9031 // function template specialization, which is added to the set of
9032 // overloaded functions considered.
9033 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009034 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009035 if (Sema::TemplateDeductionResult Result
9036 = S.DeduceTemplateArguments(FunctionTemplate,
9037 &OvlExplicitTemplateArgs,
9038 TargetFunctionType, Specialization,
9039 Info)) {
9040 // FIXME: make a note of the failed deduction for diagnostics.
9041 (void)Result;
9042 return false;
9043 }
9044
9045 // Template argument deduction ensures that we have an exact match.
9046 // This function template specicalization works.
9047 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9048 assert(TargetFunctionType
9049 == Context.getCanonicalType(Specialization->getType()));
9050 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9051 return true;
9052 }
9053
9054 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9055 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009056 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009057 // Skip non-static functions when converting to pointer, and static
9058 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009059 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9060 return false;
9061 }
9062 else if (TargetTypeIsNonStaticMemberFunction)
9063 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009064
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009065 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009066 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009067 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9068 if (S.CheckCUDATarget(Caller, FunDecl))
9069 return false;
9070
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009071 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009072 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9073 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009074 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9075 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009076 Matches.push_back(std::make_pair(CurAccessFunPair,
9077 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009078 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009079 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009080 }
Mike Stump11289f42009-09-09 15:08:12 +00009081 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009082
9083 return false;
9084 }
9085
9086 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9087 bool Ret = false;
9088
9089 // If the overload expression doesn't have the form of a pointer to
9090 // member, don't try to convert it to a pointer-to-member type.
9091 if (IsInvalidFormOfPointerToMemberFunction())
9092 return false;
9093
9094 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9095 E = OvlExpr->decls_end();
9096 I != E; ++I) {
9097 // Look through any using declarations to find the underlying function.
9098 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9099
9100 // C++ [over.over]p3:
9101 // Non-member functions and static member functions match
9102 // targets of type "pointer-to-function" or "reference-to-function."
9103 // Nonstatic member functions match targets of
9104 // type "pointer-to-member-function."
9105 // Note that according to DR 247, the containing class does not matter.
9106 if (FunctionTemplateDecl *FunctionTemplate
9107 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9108 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9109 Ret = true;
9110 }
9111 // If we have explicit template arguments supplied, skip non-templates.
9112 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9113 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9114 Ret = true;
9115 }
9116 assert(Ret || Matches.empty());
9117 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009118 }
9119
Douglas Gregorb491ed32011-02-19 21:32:49 +00009120 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009121 // [...] and any given function template specialization F1 is
9122 // eliminated if the set contains a second function template
9123 // specialization whose function template is more specialized
9124 // than the function template of F1 according to the partial
9125 // ordering rules of 14.5.5.2.
9126
9127 // The algorithm specified above is quadratic. We instead use a
9128 // two-pass algorithm (similar to the one used to identify the
9129 // best viable function in an overload set) that identifies the
9130 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009131
9132 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9133 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9134 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009135
John McCall58cc69d2010-01-27 01:50:18 +00009136 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009137 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9138 TPOC_Other, 0, SourceExpr->getLocStart(),
9139 S.PDiag(),
9140 S.PDiag(diag::err_addr_ovl_ambiguous)
9141 << Matches[0].second->getDeclName(),
9142 S.PDiag(diag::note_ovl_candidate)
9143 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009144 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009145
Douglas Gregorb491ed32011-02-19 21:32:49 +00009146 if (Result != MatchesCopy.end()) {
9147 // Make it the first and only element
9148 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9149 Matches[0].second = cast<FunctionDecl>(*Result);
9150 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009151 }
9152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009153
Douglas Gregorb491ed32011-02-19 21:32:49 +00009154 void EliminateAllTemplateMatches() {
9155 // [...] any function template specializations in the set are
9156 // eliminated if the set also contains a non-template function, [...]
9157 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9158 if (Matches[I].second->getPrimaryTemplate() == 0)
9159 ++I;
9160 else {
9161 Matches[I] = Matches[--N];
9162 Matches.set_size(N);
9163 }
9164 }
9165 }
9166
9167public:
9168 void ComplainNoMatchesFound() const {
9169 assert(Matches.empty());
9170 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9171 << OvlExpr->getName() << TargetFunctionType
9172 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009173 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009174 }
9175
9176 bool IsInvalidFormOfPointerToMemberFunction() const {
9177 return TargetTypeIsNonStaticMemberFunction &&
9178 !OvlExprInfo.HasFormOfMemberPointer;
9179 }
9180
9181 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9182 // TODO: Should we condition this on whether any functions might
9183 // have matched, or is it more appropriate to do that in callers?
9184 // TODO: a fixit wouldn't hurt.
9185 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9186 << TargetType << OvlExpr->getSourceRange();
9187 }
9188
9189 void ComplainOfInvalidConversion() const {
9190 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9191 << OvlExpr->getName() << TargetType;
9192 }
9193
9194 void ComplainMultipleMatchesFound() const {
9195 assert(Matches.size() > 1);
9196 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9197 << OvlExpr->getName()
9198 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009199 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009200 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009201
9202 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9203
Douglas Gregorb491ed32011-02-19 21:32:49 +00009204 int getNumMatches() const { return Matches.size(); }
9205
9206 FunctionDecl* getMatchingFunctionDecl() const {
9207 if (Matches.size() != 1) return 0;
9208 return Matches[0].second;
9209 }
9210
9211 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9212 if (Matches.size() != 1) return 0;
9213 return &Matches[0].first;
9214 }
9215};
9216
9217/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9218/// an overloaded function (C++ [over.over]), where @p From is an
9219/// expression with overloaded function type and @p ToType is the type
9220/// we're trying to resolve to. For example:
9221///
9222/// @code
9223/// int f(double);
9224/// int f(int);
9225///
9226/// int (*pfd)(double) = f; // selects f(double)
9227/// @endcode
9228///
9229/// This routine returns the resulting FunctionDecl if it could be
9230/// resolved, and NULL otherwise. When @p Complain is true, this
9231/// routine will emit diagnostics if there is an error.
9232FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009233Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9234 QualType TargetType,
9235 bool Complain,
9236 DeclAccessPair &FoundResult,
9237 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009238 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009239
9240 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9241 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009242 int NumMatches = Resolver.getNumMatches();
9243 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009244 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009245 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9246 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9247 else
9248 Resolver.ComplainNoMatchesFound();
9249 }
9250 else if (NumMatches > 1 && Complain)
9251 Resolver.ComplainMultipleMatchesFound();
9252 else if (NumMatches == 1) {
9253 Fn = Resolver.getMatchingFunctionDecl();
9254 assert(Fn);
9255 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009256 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009257 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009258 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009259
9260 if (pHadMultipleCandidates)
9261 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009262 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009263}
9264
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009265/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009266/// resolve that overloaded function expression down to a single function.
9267///
9268/// This routine can only resolve template-ids that refer to a single function
9269/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009270/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009271/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009272FunctionDecl *
9273Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9274 bool Complain,
9275 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009276 // C++ [over.over]p1:
9277 // [...] [Note: any redundant set of parentheses surrounding the
9278 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009279 // C++ [over.over]p1:
9280 // [...] The overloaded function name can be preceded by the &
9281 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009282
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009283 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009284 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009285 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009286
9287 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009288 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009289
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009290 // Look through all of the overloaded functions, searching for one
9291 // whose type matches exactly.
9292 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009293 for (UnresolvedSetIterator I = ovl->decls_begin(),
9294 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009295 // C++0x [temp.arg.explicit]p3:
9296 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009297 // where deduction is not done, if a template argument list is
9298 // specified and it, along with any default template arguments,
9299 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009300 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009301 FunctionTemplateDecl *FunctionTemplate
9302 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009303
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009304 // C++ [over.over]p2:
9305 // If the name is a function template, template argument deduction is
9306 // done (14.8.2.2), and if the argument deduction succeeds, the
9307 // resulting template argument list is used to generate a single
9308 // function template specialization, which is added to the set of
9309 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009310 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009311 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009312 if (TemplateDeductionResult Result
9313 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9314 Specialization, Info)) {
9315 // FIXME: make a note of the failed deduction for diagnostics.
9316 (void)Result;
9317 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009318 }
9319
John McCall0009fcc2011-04-26 20:42:42 +00009320 assert(Specialization && "no specialization and no error?");
9321
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009322 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009323 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009324 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009325 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9326 << ovl->getName();
9327 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009328 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009329 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009330 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009331
John McCall0009fcc2011-04-26 20:42:42 +00009332 Matched = Specialization;
9333 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009335
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009336 return Matched;
9337}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009338
Douglas Gregor1beec452011-03-12 01:48:56 +00009339
9340
9341
John McCall50a2c2c2011-10-11 23:14:30 +00009342// Resolve and fix an overloaded expression that can be resolved
9343// because it identifies a single function template specialization.
9344//
Douglas Gregor1beec452011-03-12 01:48:56 +00009345// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009346//
9347// Return true if it was logically possible to so resolve the
9348// expression, regardless of whether or not it succeeded. Always
9349// returns true if 'complain' is set.
9350bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9351 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9352 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009353 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009354 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009355 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009356
John McCall50a2c2c2011-10-11 23:14:30 +00009357 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009358
John McCall0009fcc2011-04-26 20:42:42 +00009359 DeclAccessPair found;
9360 ExprResult SingleFunctionExpression;
9361 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9362 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009363 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009364 SrcExpr = ExprError();
9365 return true;
9366 }
John McCall0009fcc2011-04-26 20:42:42 +00009367
9368 // It is only correct to resolve to an instance method if we're
9369 // resolving a form that's permitted to be a pointer to member.
9370 // Otherwise we'll end up making a bound member expression, which
9371 // is illegal in all the contexts we resolve like this.
9372 if (!ovl.HasFormOfMemberPointer &&
9373 isa<CXXMethodDecl>(fn) &&
9374 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009375 if (!complain) return false;
9376
9377 Diag(ovl.Expression->getExprLoc(),
9378 diag::err_bound_member_function)
9379 << 0 << ovl.Expression->getSourceRange();
9380
9381 // TODO: I believe we only end up here if there's a mix of
9382 // static and non-static candidates (otherwise the expression
9383 // would have 'bound member' type, not 'overload' type).
9384 // Ideally we would note which candidate was chosen and why
9385 // the static candidates were rejected.
9386 SrcExpr = ExprError();
9387 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009388 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009389
Sylvestre Ledrua5202662012-07-31 06:56:50 +00009390 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +00009391 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009392 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009393
9394 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009395 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009396 SingleFunctionExpression =
9397 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009398 if (SingleFunctionExpression.isInvalid()) {
9399 SrcExpr = ExprError();
9400 return true;
9401 }
9402 }
John McCall0009fcc2011-04-26 20:42:42 +00009403 }
9404
9405 if (!SingleFunctionExpression.isUsable()) {
9406 if (complain) {
9407 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9408 << ovl.Expression->getName()
9409 << DestTypeForComplaining
9410 << OpRangeForComplaining
9411 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009412 NoteAllOverloadCandidates(SrcExpr.get());
9413
9414 SrcExpr = ExprError();
9415 return true;
9416 }
9417
9418 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009419 }
9420
John McCall50a2c2c2011-10-11 23:14:30 +00009421 SrcExpr = SingleFunctionExpression;
9422 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009423}
9424
Douglas Gregorcabea402009-09-22 15:41:20 +00009425/// \brief Add a single candidate to the overload set.
9426static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009427 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009428 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009429 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009430 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009431 bool PartialOverloading,
9432 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009433 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009434 if (isa<UsingShadowDecl>(Callee))
9435 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9436
Douglas Gregorcabea402009-09-22 15:41:20 +00009437 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009438 if (ExplicitTemplateArgs) {
9439 assert(!KnownValid && "Explicit template arguments?");
9440 return;
9441 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009442 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9443 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009444 return;
John McCalld14a8642009-11-21 08:51:07 +00009445 }
9446
9447 if (FunctionTemplateDecl *FuncTemplate
9448 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009449 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009450 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009451 return;
9452 }
9453
Richard Smith95ce4f62011-06-26 22:19:54 +00009454 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009456
Douglas Gregorcabea402009-09-22 15:41:20 +00009457/// \brief Add the overload candidates named by callee and/or found by argument
9458/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009459void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009460 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009461 OverloadCandidateSet &CandidateSet,
9462 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009463
9464#ifndef NDEBUG
9465 // Verify that ArgumentDependentLookup is consistent with the rules
9466 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009467 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009468 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9469 // and let Y be the lookup set produced by argument dependent
9470 // lookup (defined as follows). If X contains
9471 //
9472 // -- a declaration of a class member, or
9473 //
9474 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009475 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009476 //
9477 // -- a declaration that is neither a function or a function
9478 // template
9479 //
9480 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009481
John McCall57500772009-12-16 12:17:52 +00009482 if (ULE->requiresADL()) {
9483 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9484 E = ULE->decls_end(); I != E; ++I) {
9485 assert(!(*I)->getDeclContext()->isRecord());
9486 assert(isa<UsingShadowDecl>(*I) ||
9487 !(*I)->getDeclContext()->isFunctionOrMethod());
9488 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009489 }
9490 }
9491#endif
9492
John McCall57500772009-12-16 12:17:52 +00009493 // It would be nice to avoid this copy.
9494 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009495 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009496 if (ULE->hasExplicitTemplateArgs()) {
9497 ULE->copyTemplateArgumentsInto(TABuffer);
9498 ExplicitTemplateArgs = &TABuffer;
9499 }
9500
9501 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9502 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009503 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9504 CandidateSet, PartialOverloading,
9505 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009506
John McCall57500772009-12-16 12:17:52 +00009507 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009508 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009509 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009510 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +00009511 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009512}
John McCalld681c392009-12-16 08:11:27 +00009513
Richard Smith998a5912011-06-05 22:42:48 +00009514/// Attempt to recover from an ill-formed use of a non-dependent name in a
9515/// template, where the non-dependent name was declared after the template
9516/// was defined. This is common in code written for a compilers which do not
9517/// correctly implement two-stage name lookup.
9518///
9519/// Returns true if a viable candidate was found and a diagnostic was issued.
9520static bool
9521DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9522 const CXXScopeSpec &SS, LookupResult &R,
9523 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009524 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009525 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9526 return false;
9527
9528 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009529 if (DC->isTransparentContext())
9530 continue;
9531
Richard Smith998a5912011-06-05 22:42:48 +00009532 SemaRef.LookupQualifiedName(R, DC);
9533
9534 if (!R.empty()) {
9535 R.suppressDiagnostics();
9536
9537 if (isa<CXXRecordDecl>(DC)) {
9538 // Don't diagnose names we find in classes; we get much better
9539 // diagnostics for these from DiagnoseEmptyLookup.
9540 R.clear();
9541 return false;
9542 }
9543
9544 OverloadCandidateSet Candidates(FnLoc);
9545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9546 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009547 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009548 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009549
9550 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009551 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009552 // No viable functions. Don't bother the user with notes for functions
9553 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009554 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009555 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009556 }
Richard Smith998a5912011-06-05 22:42:48 +00009557
9558 // Find the namespaces where ADL would have looked, and suggest
9559 // declaring the function there instead.
9560 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9561 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00009562 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +00009563 AssociatedNamespaces,
9564 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +00009565 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckya21719d2012-11-13 00:08:34 +00009566 DeclContext *Std = SemaRef.getStdNamespace();
9567 for (Sema::AssociatedNamespaceSet::iterator
9568 it = AssociatedNamespaces.begin(),
9569 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith21bae432012-12-22 02:46:14 +00009570 // Never suggest declaring a function within namespace 'std'.
9571 if (Std && Std->Encloses(*it))
9572 continue;
9573
9574 // Never suggest declaring a function within a namespace with a reserved
9575 // name, like __gnu_cxx.
9576 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9577 if (NS &&
9578 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9579 continue;
9580
9581 SuggestedNamespaces.insert(*it);
Richard Smith998a5912011-06-05 22:42:48 +00009582 }
9583
9584 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9585 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009586 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009587 SemaRef.Diag(Best->Function->getLocation(),
9588 diag::note_not_found_by_two_phase_lookup)
9589 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009590 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009591 SemaRef.Diag(Best->Function->getLocation(),
9592 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009593 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009594 } else {
9595 // FIXME: It would be useful to list the associated namespaces here,
9596 // but the diagnostics infrastructure doesn't provide a way to produce
9597 // a localized representation of a list of items.
9598 SemaRef.Diag(Best->Function->getLocation(),
9599 diag::note_not_found_by_two_phase_lookup)
9600 << R.getLookupName() << 2;
9601 }
9602
9603 // Try to recover by calling this function.
9604 return true;
9605 }
9606
9607 R.clear();
9608 }
9609
9610 return false;
9611}
9612
9613/// Attempt to recover from ill-formed use of a non-dependent operator in a
9614/// template, where the non-dependent operator was declared after the template
9615/// was defined.
9616///
9617/// Returns true if a viable candidate was found and a diagnostic was issued.
9618static bool
9619DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9620 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009621 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009622 DeclarationName OpName =
9623 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9624 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9625 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009626 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009627}
9628
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009629namespace {
9630// Callback to limit the allowed keywords and to only accept typo corrections
9631// that are keywords or whose decls refer to functions (or template functions)
9632// that accept the given number of arguments.
9633class RecoveryCallCCC : public CorrectionCandidateCallback {
9634 public:
9635 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9636 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009637 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009638 WantRemainingKeywords = false;
9639 }
9640
9641 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9642 if (!candidate.getCorrectionDecl())
9643 return candidate.isKeyword();
9644
9645 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9646 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9647 FunctionDecl *FD = 0;
9648 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9649 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9650 FD = FTD->getTemplatedDecl();
9651 if (!HasExplicitTemplateArgs && !FD) {
9652 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9653 // If the Decl is neither a function nor a template function,
9654 // determine if it is a pointer or reference to a function. If so,
9655 // check against the number of arguments expected for the pointee.
9656 QualType ValType = cast<ValueDecl>(ND)->getType();
9657 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9658 ValType = ValType->getPointeeType();
9659 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9660 if (FPT->getNumArgs() == NumArgs)
9661 return true;
9662 }
9663 }
9664 if (FD && FD->getNumParams() >= NumArgs &&
9665 FD->getMinRequiredArguments() <= NumArgs)
9666 return true;
9667 }
9668 return false;
9669 }
9670
9671 private:
9672 unsigned NumArgs;
9673 bool HasExplicitTemplateArgs;
9674};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009675
9676// Callback that effectively disabled typo correction
9677class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9678 public:
9679 NoTypoCorrectionCCC() {
9680 WantTypeSpecifiers = false;
9681 WantExpressionKeywords = false;
9682 WantCXXNamedCasts = false;
9683 WantRemainingKeywords = false;
9684 }
9685
9686 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9687 return false;
9688 }
9689};
Richard Smith88d67f32012-09-25 04:46:05 +00009690
9691class BuildRecoveryCallExprRAII {
9692 Sema &SemaRef;
9693public:
9694 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9695 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9696 SemaRef.IsBuildingRecoveryCallExpr = true;
9697 }
9698
9699 ~BuildRecoveryCallExprRAII() {
9700 SemaRef.IsBuildingRecoveryCallExpr = false;
9701 }
9702};
9703
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009704}
9705
John McCalld681c392009-12-16 08:11:27 +00009706/// Attempts to recover from a call where no functions were found.
9707///
9708/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009709static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009710BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009711 UnresolvedLookupExpr *ULE,
9712 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009713 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009714 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009715 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +00009716 // Do not try to recover if it is already building a recovery call.
9717 // This stops infinite loops for template instantiations like
9718 //
9719 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9720 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9721 //
9722 if (SemaRef.IsBuildingRecoveryCallExpr)
9723 return ExprError();
9724 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +00009725
9726 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009727 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009728 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009729
John McCall57500772009-12-16 12:17:52 +00009730 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009731 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009732 if (ULE->hasExplicitTemplateArgs()) {
9733 ULE->copyTemplateArgumentsInto(TABuffer);
9734 ExplicitTemplateArgs = &TABuffer;
9735 }
9736
John McCalld681c392009-12-16 08:11:27 +00009737 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9738 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009739 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009740 NoTypoCorrectionCCC RejectAll;
9741 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9742 (CorrectionCandidateCallback*)&Validator :
9743 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009744 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009745 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009746 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009747 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009748 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009749 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009750
John McCall57500772009-12-16 12:17:52 +00009751 assert(!R.empty() && "lookup results empty despite recovery");
9752
9753 // Build an implicit member call if appropriate. Just drop the
9754 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009755 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009756 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009757 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9758 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009759 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009760 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009761 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009762 else
9763 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9764
9765 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009766 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009767
9768 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009769 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009770 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009771 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009772 MultiExprArg(Args.data(), Args.size()),
9773 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009774}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009775
Sam Panzer0f384432012-08-21 00:52:01 +00009776/// \brief Constructs and populates an OverloadedCandidateSet from
9777/// the given function.
9778/// \returns true when an the ExprResult output parameter has been set.
9779bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9780 UnresolvedLookupExpr *ULE,
9781 Expr **Args, unsigned NumArgs,
9782 SourceLocation RParenLoc,
9783 OverloadCandidateSet *CandidateSet,
9784 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +00009785#ifndef NDEBUG
9786 if (ULE->requiresADL()) {
9787 // To do ADL, we must have found an unqualified name.
9788 assert(!ULE->getQualifier() && "qualified name with ADL");
9789
9790 // We don't perform ADL for implicit declarations of builtins.
9791 // Verify that this was correctly set up.
9792 FunctionDecl *F;
9793 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9794 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9795 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009796 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009797
John McCall57500772009-12-16 12:17:52 +00009798 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009799 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +00009800 }
John McCall57500772009-12-16 12:17:52 +00009801#endif
9802
John McCall4124c492011-10-17 18:40:02 +00009803 UnbridgedCastsSet UnbridgedCasts;
Sam Panzer0f384432012-08-21 00:52:01 +00009804 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9805 *Result = ExprError();
9806 return true;
9807 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009808
John McCall57500772009-12-16 12:17:52 +00009809 // Add the functions denoted by the callee to the set of candidate
9810 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009811 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzer0f384432012-08-21 00:52:01 +00009812 *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009813
9814 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009815 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9816 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +00009817 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009818 // In Microsoft mode, if we are inside a template class member function then
9819 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009820 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009821 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009822 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009823 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00009824 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9825 llvm::makeArrayRef(Args, NumArgs),
9826 Context.DependentTy, VK_RValue,
9827 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009828 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +00009829 *Result = Owned(CE);
9830 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009831 }
Sam Panzer0f384432012-08-21 00:52:01 +00009832 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +00009833 }
John McCalld681c392009-12-16 08:11:27 +00009834
John McCall4124c492011-10-17 18:40:02 +00009835 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +00009836 return false;
9837}
John McCall4124c492011-10-17 18:40:02 +00009838
Sam Panzer0f384432012-08-21 00:52:01 +00009839/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9840/// the completed call expression. If overload resolution fails, emits
9841/// diagnostics and returns ExprError()
9842static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9843 UnresolvedLookupExpr *ULE,
9844 SourceLocation LParenLoc,
9845 Expr **Args, unsigned NumArgs,
9846 SourceLocation RParenLoc,
9847 Expr *ExecConfig,
9848 OverloadCandidateSet *CandidateSet,
9849 OverloadCandidateSet::iterator *Best,
9850 OverloadingResult OverloadResult,
9851 bool AllowTypoCorrection) {
9852 if (CandidateSet->empty())
9853 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9854 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9855 RParenLoc, /*EmptyLookup=*/true,
9856 AllowTypoCorrection);
9857
9858 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +00009859 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +00009860 FunctionDecl *FDecl = (*Best)->Function;
9861 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9862 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9863 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9864 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9865 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9866 RParenLoc, ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009867 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009868
Richard Smith998a5912011-06-05 22:42:48 +00009869 case OR_No_Viable_Function: {
9870 // Try to recover by looking for viable functions which the user might
9871 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +00009872 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009873 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9874 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009875 /*EmptyLookup=*/false,
9876 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009877 if (!Recovery.isInvalid())
9878 return Recovery;
9879
Sam Panzer0f384432012-08-21 00:52:01 +00009880 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009881 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009882 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009883 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9884 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009885 break;
Richard Smith998a5912011-06-05 22:42:48 +00009886 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009887
9888 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +00009889 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009890 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009891 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9892 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009893 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009894
Sam Panzer0f384432012-08-21 00:52:01 +00009895 case OR_Deleted: {
9896 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9897 << (*Best)->Function->isDeleted()
9898 << ULE->getName()
9899 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9900 << Fn->getSourceRange();
9901 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9902 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009903
Sam Panzer0f384432012-08-21 00:52:01 +00009904 // We emitted an error for the unvailable/deleted function call but keep
9905 // the call in the AST.
9906 FunctionDecl *FDecl = (*Best)->Function;
9907 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9908 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9909 RParenLoc, ExecConfig);
9910 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009911 }
9912
Douglas Gregorb412e172010-07-25 18:17:45 +00009913 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009914 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009915}
9916
Sam Panzer0f384432012-08-21 00:52:01 +00009917/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9918/// (which eventually refers to the declaration Func) and the call
9919/// arguments Args/NumArgs, attempt to resolve the function call down
9920/// to a specific function. If overload resolution succeeds, returns
9921/// the call expression produced by overload resolution.
9922/// Otherwise, emits diagnostics and returns ExprError.
9923ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9924 UnresolvedLookupExpr *ULE,
9925 SourceLocation LParenLoc,
9926 Expr **Args, unsigned NumArgs,
9927 SourceLocation RParenLoc,
9928 Expr *ExecConfig,
9929 bool AllowTypoCorrection) {
9930 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9931 ExprResult result;
9932
9933 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9934 &CandidateSet, &result))
9935 return result;
9936
9937 OverloadCandidateSet::iterator Best;
9938 OverloadingResult OverloadResult =
9939 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9940
9941 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9942 RParenLoc, ExecConfig, &CandidateSet,
9943 &Best, OverloadResult,
9944 AllowTypoCorrection);
9945}
9946
John McCall4c4c1df2010-01-26 03:27:55 +00009947static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009948 return Functions.size() > 1 ||
9949 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9950}
9951
Douglas Gregor084d8552009-03-13 23:49:33 +00009952/// \brief Create a unary operation that may resolve to an overloaded
9953/// operator.
9954///
9955/// \param OpLoc The location of the operator itself (e.g., '*').
9956///
9957/// \param OpcIn The UnaryOperator::Opcode that describes this
9958/// operator.
9959///
James Dennett18348b62012-06-22 08:52:37 +00009960/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009961/// considered by overload resolution. The caller needs to build this
9962/// set based on the context using, e.g.,
9963/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9964/// set should not contain any member functions; those will be added
9965/// by CreateOverloadedUnaryOp().
9966///
James Dennett91738ff2012-06-22 10:32:46 +00009967/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009968ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009969Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9970 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009971 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009972 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009973
9974 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9975 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9976 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009977 // TODO: provide better source location info.
9978 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009979
John McCall4124c492011-10-17 18:40:02 +00009980 if (checkPlaceholderForOverload(*this, Input))
9981 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009982
Douglas Gregor084d8552009-03-13 23:49:33 +00009983 Expr *Args[2] = { Input, 0 };
9984 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009985
Douglas Gregor084d8552009-03-13 23:49:33 +00009986 // For post-increment and post-decrement, add the implicit '0' as
9987 // the second argument, so that we know this is a post-increment or
9988 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009989 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009990 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009991 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9992 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009993 NumArgs = 2;
9994 }
9995
9996 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009997 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009998 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009999 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010000 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010001 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010002 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010003
John McCall58cc69d2010-01-27 01:50:18 +000010004 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010005 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010006 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010007 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010008 /*ADL*/ true, IsOverloaded(Fns),
10009 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +000010010 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010011 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor084d8552009-03-13 23:49:33 +000010012 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010013 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010014 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010015 }
10016
10017 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010018 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010019
10020 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010021 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10022 false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010023
10024 // Add operator candidates that are member functions.
10025 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10026
John McCall4c4c1df2010-01-26 03:27:55 +000010027 // Add candidates from ADL.
10028 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010029 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +000010030 /*ExplicitTemplateArgs*/ 0,
10031 CandidateSet);
10032
Douglas Gregor084d8552009-03-13 23:49:33 +000010033 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010034 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010035
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010036 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10037
Douglas Gregor084d8552009-03-13 23:49:33 +000010038 // Perform overload resolution.
10039 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010040 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010041 case OR_Success: {
10042 // We found a built-in operator or an overloaded operator.
10043 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010044
Douglas Gregor084d8552009-03-13 23:49:33 +000010045 if (FnDecl) {
10046 // We matched an overloaded operator. Build a call to that
10047 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010048
Eli Friedmanfa0df832012-02-02 03:46:19 +000010049 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010050
Douglas Gregor084d8552009-03-13 23:49:33 +000010051 // Convert the arguments.
10052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010053 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010054
John Wiegley01296292011-04-08 18:41:53 +000010055 ExprResult InputRes =
10056 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10057 Best->FoundDecl, Method);
10058 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010059 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010060 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010061 } else {
10062 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010063 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010064 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010065 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010066 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010067 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010068 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010069 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010070 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010071 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010072 }
10073
John McCall4fa0d5f2010-05-06 18:15:07 +000010074 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10075
John McCall7decc9e2010-11-18 06:31:45 +000010076 // Determine the result type.
10077 QualType ResultTy = FnDecl->getResultType();
10078 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10079 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +000010080
Douglas Gregor084d8552009-03-13 23:49:33 +000010081 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010082 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010083 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010084 if (FnExpr.isInvalid())
10085 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010086
Eli Friedman030eee42009-11-18 03:58:17 +000010087 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010088 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010089 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010090 llvm::makeArrayRef(Args, NumArgs),
Lang Hames5de91cc2012-10-02 04:45:10 +000010091 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010093 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010094 FnDecl))
10095 return ExprError();
10096
John McCallb268a282010-08-23 23:25:46 +000010097 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010098 } else {
10099 // We matched a built-in operator. Convert the arguments, then
10100 // break out so that we will build the appropriate built-in
10101 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010102 ExprResult InputRes =
10103 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10104 Best->Conversions[0], AA_Passing);
10105 if (InputRes.isInvalid())
10106 return ExprError();
10107 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010108 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010109 }
John Wiegley01296292011-04-08 18:41:53 +000010110 }
10111
10112 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010113 // This is an erroneous use of an operator which can be overloaded by
10114 // a non-member function. Check for non-member operators which were
10115 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010116 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10117 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010118 // FIXME: Recover by calling the found function.
10119 return ExprError();
10120
John Wiegley01296292011-04-08 18:41:53 +000010121 // No viable function; fall through to handling this as a
10122 // built-in operator, which will produce an error message for us.
10123 break;
10124
10125 case OR_Ambiguous:
10126 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10127 << UnaryOperator::getOpcodeStr(Opc)
10128 << Input->getType()
10129 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010130 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10131 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010132 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10133 return ExprError();
10134
10135 case OR_Deleted:
10136 Diag(OpLoc, diag::err_ovl_deleted_oper)
10137 << Best->Function->isDeleted()
10138 << UnaryOperator::getOpcodeStr(Opc)
10139 << getDeletedOrUnavailableSuffix(Best->Function)
10140 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010141 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10142 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010143 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010144 return ExprError();
10145 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010146
10147 // Either we found no viable overloaded operator or we matched a
10148 // built-in operator. In either case, fall through to trying to
10149 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010150 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010151}
10152
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010153/// \brief Create a binary operation that may resolve to an overloaded
10154/// operator.
10155///
10156/// \param OpLoc The location of the operator itself (e.g., '+').
10157///
10158/// \param OpcIn The BinaryOperator::Opcode that describes this
10159/// operator.
10160///
James Dennett18348b62012-06-22 08:52:37 +000010161/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010162/// considered by overload resolution. The caller needs to build this
10163/// set based on the context using, e.g.,
10164/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10165/// set should not contain any member functions; those will be added
10166/// by CreateOverloadedBinOp().
10167///
10168/// \param LHS Left-hand argument.
10169/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010170ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010171Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010172 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010173 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010174 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010175 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010176 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010177
10178 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10179 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10180 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10181
10182 // If either side is type-dependent, create an appropriate dependent
10183 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010184 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010185 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010186 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010187 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010188 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010189 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010190 Context.DependentTy,
10191 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010192 OpLoc,
10193 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010194
Douglas Gregor5287f092009-11-05 00:51:44 +000010195 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10196 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010197 VK_LValue,
10198 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010199 Context.DependentTy,
10200 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010201 OpLoc,
10202 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010203 }
John McCall4c4c1df2010-01-26 03:27:55 +000010204
10205 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010206 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010207 // TODO: provide better source location info in DNLoc component.
10208 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010209 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010210 = UnresolvedLookupExpr::Create(Context, NamingClass,
10211 NestedNameSpecifierLoc(), OpNameInfo,
10212 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010213 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010214 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10215 Context.DependentTy, VK_RValue,
10216 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010217 }
10218
John McCall4124c492011-10-17 18:40:02 +000010219 // Always do placeholder-like conversions on the RHS.
10220 if (checkPlaceholderForOverload(*this, Args[1]))
10221 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010222
John McCall526ab472011-10-25 17:37:35 +000010223 // Do placeholder-like conversion on the LHS; note that we should
10224 // not get here with a PseudoObject LHS.
10225 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010226 if (checkPlaceholderForOverload(*this, Args[0]))
10227 return ExprError();
10228
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010229 // If this is the assignment operator, we only perform overload resolution
10230 // if the left-hand side is a class or enumeration type. This is actually
10231 // a hack. The standard requires that we do overload resolution between the
10232 // various built-in candidates, but as DR507 points out, this can lead to
10233 // problems. So we do it this way, which pretty much follows what GCC does.
10234 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010235 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010236 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010237
John McCalle26a8722010-12-04 08:14:53 +000010238 // If this is the .* operator, which is not overloadable, just
10239 // create a built-in binary operator.
10240 if (Opc == BO_PtrMemD)
10241 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10242
Douglas Gregor084d8552009-03-13 23:49:33 +000010243 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010244 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010245
10246 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010247 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010248
10249 // Add operator candidates that are member functions.
10250 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10251
John McCall4c4c1df2010-01-26 03:27:55 +000010252 // Add candidates from ADL.
10253 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010254 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010255 /*ExplicitTemplateArgs*/ 0,
10256 CandidateSet);
10257
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010258 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010259 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010260
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010261 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10262
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010263 // Perform overload resolution.
10264 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010265 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010266 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010267 // We found a built-in operator or an overloaded operator.
10268 FunctionDecl *FnDecl = Best->Function;
10269
10270 if (FnDecl) {
10271 // We matched an overloaded operator. Build a call to that
10272 // operator.
10273
Eli Friedmanfa0df832012-02-02 03:46:19 +000010274 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010275
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010276 // Convert the arguments.
10277 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010278 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010279 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010280
Chandler Carruth8e543b32010-12-12 08:17:55 +000010281 ExprResult Arg1 =
10282 PerformCopyInitialization(
10283 InitializedEntity::InitializeParameter(Context,
10284 FnDecl->getParamDecl(0)),
10285 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010286 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010287 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010288
John Wiegley01296292011-04-08 18:41:53 +000010289 ExprResult Arg0 =
10290 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10291 Best->FoundDecl, Method);
10292 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010293 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010294 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010295 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010296 } else {
10297 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010298 ExprResult Arg0 = PerformCopyInitialization(
10299 InitializedEntity::InitializeParameter(Context,
10300 FnDecl->getParamDecl(0)),
10301 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010302 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010303 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010304
Chandler Carruth8e543b32010-12-12 08:17:55 +000010305 ExprResult Arg1 =
10306 PerformCopyInitialization(
10307 InitializedEntity::InitializeParameter(Context,
10308 FnDecl->getParamDecl(1)),
10309 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010310 if (Arg1.isInvalid())
10311 return ExprError();
10312 Args[0] = LHS = Arg0.takeAs<Expr>();
10313 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010314 }
10315
John McCall4fa0d5f2010-05-06 18:15:07 +000010316 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10317
John McCall7decc9e2010-11-18 06:31:45 +000010318 // Determine the result type.
10319 QualType ResultTy = FnDecl->getResultType();
10320 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10321 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010322
10323 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010324 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10325 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010326 if (FnExpr.isInvalid())
10327 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010328
John McCallb268a282010-08-23 23:25:46 +000010329 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010330 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010331 Args, ResultTy, VK, OpLoc,
10332 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010333
10334 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010335 FnDecl))
10336 return ExprError();
10337
John McCallb268a282010-08-23 23:25:46 +000010338 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010339 } else {
10340 // We matched a built-in operator. Convert the arguments, then
10341 // break out so that we will build the appropriate built-in
10342 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010343 ExprResult ArgsRes0 =
10344 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10345 Best->Conversions[0], AA_Passing);
10346 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010347 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010348 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010349
John Wiegley01296292011-04-08 18:41:53 +000010350 ExprResult ArgsRes1 =
10351 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10352 Best->Conversions[1], AA_Passing);
10353 if (ArgsRes1.isInvalid())
10354 return ExprError();
10355 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010356 break;
10357 }
10358 }
10359
Douglas Gregor66950a32009-09-30 21:46:01 +000010360 case OR_No_Viable_Function: {
10361 // C++ [over.match.oper]p9:
10362 // If the operator is the operator , [...] and there are no
10363 // viable functions, then the operator is assumed to be the
10364 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010365 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010366 break;
10367
Chandler Carruth8e543b32010-12-12 08:17:55 +000010368 // For class as left operand for assignment or compound assigment
10369 // operator do not fall through to handling in built-in, but report that
10370 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010371 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010372 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010373 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010374 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10375 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010376 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010377 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010378 // This is an erroneous use of an operator which can be overloaded by
10379 // a non-member function. Check for non-member operators which were
10380 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010381 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010382 // FIXME: Recover by calling the found function.
10383 return ExprError();
10384
Douglas Gregor66950a32009-09-30 21:46:01 +000010385 // No viable function; try to create a built-in operation, which will
10386 // produce an error. Then, show the non-viable candidates.
10387 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010389 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010390 "C++ binary operator overloading is missing candidates!");
10391 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010392 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010393 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010394 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000010395 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010396
10397 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010398 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010399 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010400 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010401 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010402 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010403 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010404 return ExprError();
10405
10406 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010407 if (isImplicitlyDeleted(Best->Function)) {
10408 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10409 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000010410 << Context.getRecordType(Method->getParent())
10411 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010412
Richard Smithde1a4872012-12-28 12:23:24 +000010413 // The user probably meant to call this special member. Just
10414 // explain why it's deleted.
10415 NoteDeletedFunction(Method);
10416 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000010417 } else {
10418 Diag(OpLoc, diag::err_ovl_deleted_oper)
10419 << Best->Function->isDeleted()
10420 << BinaryOperator::getOpcodeStr(Opc)
10421 << getDeletedOrUnavailableSuffix(Best->Function)
10422 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10423 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010425 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010426 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010427 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010428
Douglas Gregor66950a32009-09-30 21:46:01 +000010429 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010430 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010431}
10432
John McCalldadc5752010-08-24 06:29:42 +000010433ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010434Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10435 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010436 Expr *Base, Expr *Idx) {
10437 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010438 DeclarationName OpName =
10439 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10440
10441 // If either side is type-dependent, create an appropriate dependent
10442 // expression.
10443 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10444
John McCall58cc69d2010-01-27 01:50:18 +000010445 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010446 // CHECKME: no 'operator' keyword?
10447 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10448 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010449 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010450 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010451 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010452 /*ADL*/ true, /*Overloaded*/ false,
10453 UnresolvedSetIterator(),
10454 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010455 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010456
Sebastian Redladba46e2009-10-29 20:17:01 +000010457 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010458 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000010459 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010460 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010461 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000010462 }
10463
John McCall4124c492011-10-17 18:40:02 +000010464 // Handle placeholders on both operands.
10465 if (checkPlaceholderForOverload(*this, Args[0]))
10466 return ExprError();
10467 if (checkPlaceholderForOverload(*this, Args[1]))
10468 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010469
Sebastian Redladba46e2009-10-29 20:17:01 +000010470 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010471 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010472
10473 // Subscript can only be overloaded as a member function.
10474
10475 // Add operator candidates that are member functions.
10476 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10477
10478 // Add builtin operator candidates.
10479 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10480
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010481 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10482
Sebastian Redladba46e2009-10-29 20:17:01 +000010483 // Perform overload resolution.
10484 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010485 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010486 case OR_Success: {
10487 // We found a built-in operator or an overloaded operator.
10488 FunctionDecl *FnDecl = Best->Function;
10489
10490 if (FnDecl) {
10491 // We matched an overloaded operator. Build a call to that
10492 // operator.
10493
Eli Friedmanfa0df832012-02-02 03:46:19 +000010494 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010495
John McCalla0296f72010-03-19 07:35:19 +000010496 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010497 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010498
Sebastian Redladba46e2009-10-29 20:17:01 +000010499 // Convert the arguments.
10500 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010501 ExprResult Arg0 =
10502 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10503 Best->FoundDecl, Method);
10504 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010505 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010506 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010507
Anders Carlssona68e51e2010-01-29 18:37:50 +000010508 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010509 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010510 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010511 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010512 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010513 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010514 Owned(Args[1]));
10515 if (InputInit.isInvalid())
10516 return ExprError();
10517
10518 Args[1] = InputInit.takeAs<Expr>();
10519
Sebastian Redladba46e2009-10-29 20:17:01 +000010520 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010521 QualType ResultTy = FnDecl->getResultType();
10522 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10523 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010524
10525 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010526 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10527 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010528 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10529 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010530 OpLocInfo.getLoc(),
10531 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010532 if (FnExpr.isInvalid())
10533 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010534
John McCallb268a282010-08-23 23:25:46 +000010535 CXXOperatorCallExpr *TheCall =
10536 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010537 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000010538 ResultTy, VK, RLoc,
10539 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000010540
John McCallb268a282010-08-23 23:25:46 +000010541 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010542 FnDecl))
10543 return ExprError();
10544
John McCallb268a282010-08-23 23:25:46 +000010545 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010546 } else {
10547 // We matched a built-in operator. Convert the arguments, then
10548 // break out so that we will build the appropriate built-in
10549 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010550 ExprResult ArgsRes0 =
10551 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10552 Best->Conversions[0], AA_Passing);
10553 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010554 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010555 Args[0] = ArgsRes0.take();
10556
10557 ExprResult ArgsRes1 =
10558 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10559 Best->Conversions[1], AA_Passing);
10560 if (ArgsRes1.isInvalid())
10561 return ExprError();
10562 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010563
10564 break;
10565 }
10566 }
10567
10568 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010569 if (CandidateSet.empty())
10570 Diag(LLoc, diag::err_ovl_no_oper)
10571 << Args[0]->getType() << /*subscript*/ 0
10572 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10573 else
10574 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10575 << Args[0]->getType()
10576 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010577 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010578 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010579 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010580 }
10581
10582 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010583 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010584 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010585 << Args[0]->getType() << Args[1]->getType()
10586 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010587 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010588 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010589 return ExprError();
10590
10591 case OR_Deleted:
10592 Diag(LLoc, diag::err_ovl_deleted_oper)
10593 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010594 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010595 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010596 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010597 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010598 return ExprError();
10599 }
10600
10601 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010602 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010603}
10604
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010605/// BuildCallToMemberFunction - Build a call to a member
10606/// function. MemExpr is the expression that refers to the member
10607/// function (and includes the object parameter), Args/NumArgs are the
10608/// arguments to the function call (not including the object
10609/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010610/// expression refers to a non-static member function or an overloaded
10611/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010612ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010613Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10614 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010615 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010616 assert(MemExprE->getType() == Context.BoundMemberTy ||
10617 MemExprE->getType() == Context.OverloadTy);
10618
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010619 // Dig out the member expression. This holds both the object
10620 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010621 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010622
John McCall0009fcc2011-04-26 20:42:42 +000010623 // Determine whether this is a call to a pointer-to-member function.
10624 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10625 assert(op->getType() == Context.BoundMemberTy);
10626 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10627
10628 QualType fnType =
10629 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10630
10631 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10632 QualType resultType = proto->getCallResultType(Context);
10633 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10634
10635 // Check that the object type isn't more qualified than the
10636 // member function we're calling.
10637 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10638
10639 QualType objectType = op->getLHS()->getType();
10640 if (op->getOpcode() == BO_PtrMemI)
10641 objectType = objectType->castAs<PointerType>()->getPointeeType();
10642 Qualifiers objectQuals = objectType.getQualifiers();
10643
10644 Qualifiers difference = objectQuals - funcQuals;
10645 difference.removeObjCGCAttr();
10646 difference.removeAddressSpace();
10647 if (difference) {
10648 std::string qualsString = difference.getAsString();
10649 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10650 << fnType.getUnqualifiedType()
10651 << qualsString
10652 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10653 }
10654
10655 CXXMemberCallExpr *call
Benjamin Kramerc215e762012-08-24 11:54:20 +000010656 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10657 llvm::makeArrayRef(Args, NumArgs),
John McCall0009fcc2011-04-26 20:42:42 +000010658 resultType, valueKind, RParenLoc);
10659
10660 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010661 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010662 call, 0))
10663 return ExprError();
10664
10665 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10666 return ExprError();
10667
10668 return MaybeBindToTemporary(call);
10669 }
10670
John McCall4124c492011-10-17 18:40:02 +000010671 UnbridgedCastsSet UnbridgedCasts;
10672 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10673 return ExprError();
10674
John McCall10eae182009-11-30 22:42:35 +000010675 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010676 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010677 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010678 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010679 if (isa<MemberExpr>(NakedMemExpr)) {
10680 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010681 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010682 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010683 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010684 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010685 } else {
10686 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010687 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010688
John McCall6e9f8f62009-12-03 04:06:58 +000010689 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010690 Expr::Classification ObjectClassification
10691 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10692 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010693
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010694 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010695 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010696
John McCall2d74de92009-12-01 22:10:20 +000010697 // FIXME: avoid copy.
10698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10699 if (UnresExpr->hasExplicitTemplateArgs()) {
10700 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10701 TemplateArgs = &TemplateArgsBuffer;
10702 }
10703
John McCall10eae182009-11-30 22:42:35 +000010704 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10705 E = UnresExpr->decls_end(); I != E; ++I) {
10706
John McCall6e9f8f62009-12-03 04:06:58 +000010707 NamedDecl *Func = *I;
10708 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10709 if (isa<UsingShadowDecl>(Func))
10710 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10711
Douglas Gregor02824322011-01-26 19:30:28 +000010712
Francois Pichet64225792011-01-18 05:04:39 +000010713 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010714 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010715 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10716 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010717 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010718 // If explicit template arguments were provided, we can't call a
10719 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010720 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010721 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010722
John McCalla0296f72010-03-19 07:35:19 +000010723 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010724 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010725 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010726 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010727 } else {
John McCall10eae182009-11-30 22:42:35 +000010728 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010729 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010730 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010731 llvm::makeArrayRef(Args, NumArgs),
10732 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010733 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010734 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010735 }
Mike Stump11289f42009-09-09 15:08:12 +000010736
John McCall10eae182009-11-30 22:42:35 +000010737 DeclarationName DeclName = UnresExpr->getMemberName();
10738
John McCall4124c492011-10-17 18:40:02 +000010739 UnbridgedCasts.restore();
10740
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010741 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010742 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010743 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010744 case OR_Success:
10745 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010746 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010747 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010748 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010749 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010750 break;
10751
10752 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010753 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010754 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010755 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010756 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10757 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010758 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010759 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010760
10761 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010762 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010763 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010764 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10765 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010766 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010767 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010768
10769 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010770 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010771 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010772 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010773 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010774 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010775 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10776 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010777 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010778 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010779 }
10780
John McCall16df1e52010-03-30 21:47:33 +000010781 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010782
John McCall2d74de92009-12-01 22:10:20 +000010783 // If overload resolution picked a static member, build a
10784 // non-member call based on that function.
10785 if (Method->isStatic()) {
10786 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10787 Args, NumArgs, RParenLoc);
10788 }
10789
John McCall10eae182009-11-30 22:42:35 +000010790 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010791 }
10792
John McCall7decc9e2010-11-18 06:31:45 +000010793 QualType ResultType = Method->getResultType();
10794 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10795 ResultType = ResultType.getNonLValueExprType(Context);
10796
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010797 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010798 CXXMemberCallExpr *TheCall =
Benjamin Kramerc215e762012-08-24 11:54:20 +000010799 new (Context) CXXMemberCallExpr(Context, MemExprE,
10800 llvm::makeArrayRef(Args, NumArgs),
John McCall7decc9e2010-11-18 06:31:45 +000010801 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010802
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010803 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010804 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010805 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010806 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010807
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010808 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010809 // We only need to do this if there was actually an overload; otherwise
10810 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010811 if (!Method->isStatic()) {
10812 ExprResult ObjectArg =
10813 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10814 FoundDecl, Method);
10815 if (ObjectArg.isInvalid())
10816 return ExprError();
10817 MemExpr->setBase(ObjectArg.take());
10818 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010819
10820 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010821 const FunctionProtoType *Proto =
10822 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010823 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010824 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010825 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010826
Eli Friedmanff4b4072012-02-18 04:48:30 +000010827 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10828
Richard Smith55ce3522012-06-25 20:30:08 +000010829 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000010830 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010831
Anders Carlsson47061ee2011-05-06 14:25:31 +000010832 if ((isa<CXXConstructorDecl>(CurContext) ||
10833 isa<CXXDestructorDecl>(CurContext)) &&
10834 TheCall->getMethodDecl()->isPure()) {
10835 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10836
Chandler Carruth59259262011-06-27 08:31:58 +000010837 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010838 Diag(MemExpr->getLocStart(),
10839 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10840 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10841 << MD->getParent()->getDeclName();
10842
10843 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010844 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010845 }
John McCallb268a282010-08-23 23:25:46 +000010846 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010847}
10848
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010849/// BuildCallToObjectOfClassType - Build a call to an object of class
10850/// type (C++ [over.call.object]), which can end up invoking an
10851/// overloaded function call operator (@c operator()) or performing a
10852/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010853ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010854Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010855 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010856 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010857 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010858 if (checkPlaceholderForOverload(*this, Obj))
10859 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010860 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010861
10862 UnbridgedCastsSet UnbridgedCasts;
10863 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10864 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010865
John Wiegley01296292011-04-08 18:41:53 +000010866 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10867 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010868
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010869 // C++ [over.call.object]p1:
10870 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010871 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010872 // candidate functions includes at least the function call
10873 // operators of T. The function call operators of T are obtained by
10874 // ordinary lookup of the name operator() in the context of
10875 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010876 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010878
John Wiegley01296292011-04-08 18:41:53 +000010879 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010880 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010881 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010882
John McCall27b18f82009-11-17 02:14:36 +000010883 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10884 LookupQualifiedName(R, Record->getDecl());
10885 R.suppressDiagnostics();
10886
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010887 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010888 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010889 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10890 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010891 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010893
Douglas Gregorab7897a2008-11-19 22:57:39 +000010894 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010895 // In addition, for each (non-explicit in C++0x) conversion function
10896 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010897 //
10898 // operator conversion-type-id () cv-qualifier;
10899 //
10900 // where cv-qualifier is the same cv-qualification as, or a
10901 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010902 // denotes the type "pointer to function of (P1,...,Pn) returning
10903 // R", or the type "reference to pointer to function of
10904 // (P1,...,Pn) returning R", or the type "reference to function
10905 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010906 // is also considered as a candidate function. Similarly,
10907 // surrogate call functions are added to the set of candidate
10908 // functions for each conversion function declared in an
10909 // accessible base class provided the function is not hidden
10910 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010911 std::pair<CXXRecordDecl::conversion_iterator,
10912 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010913 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010914 for (CXXRecordDecl::conversion_iterator
10915 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010916 NamedDecl *D = *I;
10917 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10918 if (isa<UsingShadowDecl>(D))
10919 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010920
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010921 // Skip over templated conversion functions; they aren't
10922 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010923 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010924 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010925
John McCall6e9f8f62009-12-03 04:06:58 +000010926 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010927 if (!Conv->isExplicit()) {
10928 // Strip the reference type (if any) and then the pointer type (if
10929 // any) to get down to what might be a function type.
10930 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10931 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10932 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010933
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010934 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10935 {
10936 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010937 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10938 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010939 }
10940 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010941 }
Mike Stump11289f42009-09-09 15:08:12 +000010942
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010943 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10944
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010945 // Perform overload resolution.
10946 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010947 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010948 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010949 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010950 // Overload resolution succeeded; we'll build the appropriate call
10951 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010952 break;
10953
10954 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010955 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010956 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010957 << Object.get()->getType() << /*call*/ 1
10958 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010959 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010960 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010961 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010962 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10964 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010965 break;
10966
10967 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010968 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010969 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010970 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010971 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10972 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010973 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010974
10975 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010976 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010977 diag::err_ovl_deleted_object_call)
10978 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010979 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010980 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010981 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010982 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10983 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010984 break;
Mike Stump11289f42009-09-09 15:08:12 +000010985 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010986
Douglas Gregorb412e172010-07-25 18:17:45 +000010987 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010988 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010989
John McCall4124c492011-10-17 18:40:02 +000010990 UnbridgedCasts.restore();
10991
Douglas Gregorab7897a2008-11-19 22:57:39 +000010992 if (Best->Function == 0) {
10993 // Since there is no function declaration, this is one of the
10994 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010995 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010996 = cast<CXXConversionDecl>(
10997 Best->Conversions[0].UserDefined.ConversionFunction);
10998
John Wiegley01296292011-04-08 18:41:53 +000010999 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011000 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000011001
Douglas Gregorab7897a2008-11-19 22:57:39 +000011002 // We selected one of the surrogate functions that converts the
11003 // object parameter to a function pointer. Perform the conversion
11004 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011005
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011006 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011007 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011008 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11009 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011010 if (Call.isInvalid())
11011 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011012 // Record usage of conversion in an implicit cast.
11013 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11014 CK_UserDefinedConversion,
11015 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011016
Douglas Gregor668443e2011-01-20 00:18:04 +000011017 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000011018 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011019 }
11020
Eli Friedmanfa0df832012-02-02 03:46:19 +000011021 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011022 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011023 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000011024
Douglas Gregorab7897a2008-11-19 22:57:39 +000011025 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11026 // that calls this method, using Object for the implicit object
11027 // parameter and passing along the remaining arguments.
11028 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011029
11030 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011031 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011032 return ExprError();
11033
Chandler Carruth8e543b32010-12-12 08:17:55 +000011034 const FunctionProtoType *Proto =
11035 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011036
11037 unsigned NumArgsInProto = Proto->getNumArgs();
11038 unsigned NumArgsToCheck = NumArgs;
11039
11040 // Build the full argument list for the method call (the
11041 // implicit object parameter is placed at the beginning of the
11042 // list).
11043 Expr **MethodArgs;
11044 if (NumArgs < NumArgsInProto) {
11045 NumArgsToCheck = NumArgsInProto;
11046 MethodArgs = new Expr*[NumArgsInProto + 1];
11047 } else {
11048 MethodArgs = new Expr*[NumArgs + 1];
11049 }
John Wiegley01296292011-04-08 18:41:53 +000011050 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011051 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11052 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000011053
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011054 DeclarationNameInfo OpLocInfo(
11055 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11056 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011057 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011058 HadMultipleCandidates,
11059 OpLocInfo.getLoc(),
11060 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011061 if (NewFn.isInvalid())
11062 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011063
11064 // Once we've built TheCall, all of the expressions are properly
11065 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011066 QualType ResultTy = Method->getResultType();
11067 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11068 ResultTy = ResultTy.getNonLValueExprType(Context);
11069
John McCallb268a282010-08-23 23:25:46 +000011070 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011071 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011072 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hames5de91cc2012-10-02 04:45:10 +000011073 ResultTy, VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011074 delete [] MethodArgs;
11075
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011076 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011077 Method))
11078 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011079
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011080 // We may have default arguments. If so, we need to allocate more
11081 // slots in the call for them.
11082 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011083 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011084 else if (NumArgs > NumArgsInProto)
11085 NumArgsToCheck = NumArgsInProto;
11086
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011087 bool IsError = false;
11088
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011089 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011090 ExprResult ObjRes =
11091 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11092 Best->FoundDecl, Method);
11093 if (ObjRes.isInvalid())
11094 IsError = true;
11095 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011096 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011097 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011098
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011099 // Check the argument types.
11100 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011101 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011102 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011103 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011104
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011105 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011106
John McCalldadc5752010-08-24 06:29:42 +000011107 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011108 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011109 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011110 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011111 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011112
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011113 IsError |= InputInit.isInvalid();
11114 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011115 } else {
John McCalldadc5752010-08-24 06:29:42 +000011116 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011117 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11118 if (DefArg.isInvalid()) {
11119 IsError = true;
11120 break;
11121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011122
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011123 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011124 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011125
11126 TheCall->setArg(i + 1, Arg);
11127 }
11128
11129 // If this is a variadic call, handle args passed through "...".
11130 if (Proto->isVariadic()) {
11131 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman9bca21e2012-07-20 20:40:35 +000011132 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011133 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11134 IsError |= Arg.isInvalid();
11135 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011136 }
11137 }
11138
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011139 if (IsError) return true;
11140
Eli Friedmanff4b4072012-02-18 04:48:30 +000011141 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11142
Richard Smith55ce3522012-06-25 20:30:08 +000011143 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011144 return true;
11145
John McCalle172be52010-08-24 06:09:16 +000011146 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011147}
11148
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011149/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011150/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011151/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011152ExprResult
John McCallb268a282010-08-23 23:25:46 +000011153Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011154 assert(Base->getType()->isRecordType() &&
11155 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011156
John McCall4124c492011-10-17 18:40:02 +000011157 if (checkPlaceholderForOverload(*this, Base))
11158 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011159
John McCallbc077cf2010-02-08 23:07:23 +000011160 SourceLocation Loc = Base->getExprLoc();
11161
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011162 // C++ [over.ref]p1:
11163 //
11164 // [...] An expression x->m is interpreted as (x.operator->())->m
11165 // for a class object x of type T if T::operator->() exists and if
11166 // the operator is selected as the best match function by the
11167 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011168 DeclarationName OpName =
11169 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011170 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011171 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011172
John McCallbc077cf2010-02-08 23:07:23 +000011173 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011174 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011175 return ExprError();
11176
John McCall27b18f82009-11-17 02:14:36 +000011177 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11178 LookupQualifiedName(R, BaseRecord->getDecl());
11179 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011180
11181 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011182 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011183 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11184 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011185 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011186
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011187 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11188
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011189 // Perform overload resolution.
11190 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011191 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011192 case OR_Success:
11193 // Overload resolution succeeded; we'll build the call below.
11194 break;
11195
11196 case OR_No_Viable_Function:
11197 if (CandidateSet.empty())
11198 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011199 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011200 else
11201 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011202 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011204 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011205
11206 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011207 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11208 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011209 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011210 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011211
11212 case OR_Deleted:
11213 Diag(OpLoc, diag::err_ovl_deleted_oper)
11214 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011215 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011216 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011217 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011219 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011220 }
11221
Eli Friedmanfa0df832012-02-02 03:46:19 +000011222 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011223 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011224 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011225
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011226 // Convert the object parameter.
11227 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011228 ExprResult BaseResult =
11229 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11230 Best->FoundDecl, Method);
11231 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011232 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011233 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011234
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011235 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011236 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011237 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011238 if (FnExpr.isInvalid())
11239 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011240
John McCall7decc9e2010-11-18 06:31:45 +000011241 QualType ResultTy = Method->getResultType();
11242 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11243 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011244 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011245 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011246 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011247
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011248 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011249 Method))
11250 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011251
11252 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011253}
11254
Richard Smithbcc22fc2012-03-09 08:00:36 +000011255/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11256/// a literal operator described by the provided lookup results.
11257ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11258 DeclarationNameInfo &SuffixInfo,
11259 ArrayRef<Expr*> Args,
11260 SourceLocation LitEndLoc,
11261 TemplateArgumentListInfo *TemplateArgs) {
11262 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011263
Richard Smithbcc22fc2012-03-09 08:00:36 +000011264 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11265 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11266 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011267
Richard Smithbcc22fc2012-03-09 08:00:36 +000011268 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11269
Richard Smithbcc22fc2012-03-09 08:00:36 +000011270 // Perform overload resolution. This will usually be trivial, but might need
11271 // to perform substitutions for a literal operator template.
11272 OverloadCandidateSet::iterator Best;
11273 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11274 case OR_Success:
11275 case OR_Deleted:
11276 break;
11277
11278 case OR_No_Viable_Function:
11279 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11280 << R.getLookupName();
11281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11282 return ExprError();
11283
11284 case OR_Ambiguous:
11285 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11286 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11287 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011288 }
11289
Richard Smithbcc22fc2012-03-09 08:00:36 +000011290 FunctionDecl *FD = Best->Function;
11291 MarkFunctionReferenced(UDSuffixLoc, FD);
11292 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011293
Richard Smithbcc22fc2012-03-09 08:00:36 +000011294 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11295 SuffixInfo.getLoc(),
11296 SuffixInfo.getInfo());
11297 if (Fn.isInvalid())
11298 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011299
11300 // Check the argument types. This should almost always be a no-op, except
11301 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011302 Expr *ConvArgs[2];
11303 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11304 ExprResult InputInit = PerformCopyInitialization(
11305 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11306 SourceLocation(), Args[ArgIdx]);
11307 if (InputInit.isInvalid())
11308 return true;
11309 ConvArgs[ArgIdx] = InputInit.take();
11310 }
11311
Richard Smithc67fdd42012-03-07 08:35:16 +000011312 QualType ResultTy = FD->getResultType();
11313 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11314 ResultTy = ResultTy.getNonLValueExprType(Context);
11315
Richard Smithc67fdd42012-03-07 08:35:16 +000011316 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011317 new (Context) UserDefinedLiteral(Context, Fn.take(),
11318 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011319 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11320
11321 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11322 return ExprError();
11323
Richard Smith55ce3522012-06-25 20:30:08 +000011324 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011325 return ExprError();
11326
11327 return MaybeBindToTemporary(UDL);
11328}
11329
Sam Panzer0f384432012-08-21 00:52:01 +000011330/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11331/// given LookupResult is non-empty, it is assumed to describe a member which
11332/// will be invoked. Otherwise, the function will be found via argument
11333/// dependent lookup.
11334/// CallExpr is set to a valid expression and FRS_Success returned on success,
11335/// otherwise CallExpr is set to ExprError() and some non-success value
11336/// is returned.
11337Sema::ForRangeStatus
11338Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11339 SourceLocation RangeLoc, VarDecl *Decl,
11340 BeginEndFunction BEF,
11341 const DeclarationNameInfo &NameInfo,
11342 LookupResult &MemberLookup,
11343 OverloadCandidateSet *CandidateSet,
11344 Expr *Range, ExprResult *CallExpr) {
11345 CandidateSet->clear();
11346 if (!MemberLookup.empty()) {
11347 ExprResult MemberRef =
11348 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11349 /*IsPtr=*/false, CXXScopeSpec(),
11350 /*TemplateKWLoc=*/SourceLocation(),
11351 /*FirstQualifierInScope=*/0,
11352 MemberLookup,
11353 /*TemplateArgs=*/0);
11354 if (MemberRef.isInvalid()) {
11355 *CallExpr = ExprError();
11356 Diag(Range->getLocStart(), diag::note_in_for_range)
11357 << RangeLoc << BEF << Range->getType();
11358 return FRS_DiagnosticIssued;
11359 }
11360 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11361 if (CallExpr->isInvalid()) {
11362 *CallExpr = ExprError();
11363 Diag(Range->getLocStart(), diag::note_in_for_range)
11364 << RangeLoc << BEF << Range->getType();
11365 return FRS_DiagnosticIssued;
11366 }
11367 } else {
11368 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011369 UnresolvedLookupExpr *Fn =
11370 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11371 NestedNameSpecifierLoc(), NameInfo,
11372 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011373 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011374
11375 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11376 CandidateSet, CallExpr);
11377 if (CandidateSet->empty() || CandidateSetError) {
11378 *CallExpr = ExprError();
11379 return FRS_NoViableFunction;
11380 }
11381 OverloadCandidateSet::iterator Best;
11382 OverloadingResult OverloadResult =
11383 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11384
11385 if (OverloadResult == OR_No_Viable_Function) {
11386 *CallExpr = ExprError();
11387 return FRS_NoViableFunction;
11388 }
11389 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11390 Loc, 0, CandidateSet, &Best,
11391 OverloadResult,
11392 /*AllowTypoCorrection=*/false);
11393 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11394 *CallExpr = ExprError();
11395 Diag(Range->getLocStart(), diag::note_in_for_range)
11396 << RangeLoc << BEF << Range->getType();
11397 return FRS_DiagnosticIssued;
11398 }
11399 }
11400 return FRS_Success;
11401}
11402
11403
Douglas Gregorcd695e52008-11-10 20:40:00 +000011404/// FixOverloadedFunctionReference - E is an expression that refers to
11405/// a C++ overloaded function (possibly with some parentheses and
11406/// perhaps a '&' around it). We have resolved the overloaded function
11407/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011408/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011409Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011410 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011411 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011412 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11413 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011414 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011415 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011416
Douglas Gregor51c538b2009-11-20 19:42:02 +000011417 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011418 }
11419
Douglas Gregor51c538b2009-11-20 19:42:02 +000011420 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011421 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11422 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011423 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011424 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011425 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011426 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011427 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011428 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011429
11430 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011431 ICE->getCastKind(),
11432 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011433 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011434 }
11435
Douglas Gregor51c538b2009-11-20 19:42:02 +000011436 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011437 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011438 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11440 if (Method->isStatic()) {
11441 // Do nothing: static member functions aren't any different
11442 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011443 } else {
John McCalle66edc12009-11-24 19:00:30 +000011444 // Fix the sub expression, which really has to be an
11445 // UnresolvedLookupExpr holding an overloaded member function
11446 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011447 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11448 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011449 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011450 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011451
John McCalld14a8642009-11-21 08:51:07 +000011452 assert(isa<DeclRefExpr>(SubExpr)
11453 && "fixed to something other than a decl ref");
11454 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11455 && "fixed to a member ref with no nested name qualifier");
11456
11457 // We have taken the address of a pointer to member
11458 // function. Perform the computation here so that we get the
11459 // appropriate pointer to member type.
11460 QualType ClassType
11461 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11462 QualType MemPtrType
11463 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11464
John McCall7decc9e2010-11-18 06:31:45 +000011465 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11466 VK_RValue, OK_Ordinary,
11467 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011468 }
11469 }
John McCall16df1e52010-03-30 21:47:33 +000011470 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11471 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011472 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011473 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011474
John McCalle3027922010-08-25 11:45:40 +000011475 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011476 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011477 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011478 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011479 }
John McCalld14a8642009-11-21 08:51:07 +000011480
11481 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011482 // FIXME: avoid copy.
11483 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011484 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011485 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11486 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011487 }
11488
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011489 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11490 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011491 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011492 Fn,
John McCall113bee02012-03-10 09:33:50 +000011493 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011494 ULE->getNameLoc(),
11495 Fn->getType(),
11496 VK_LValue,
11497 Found.getDecl(),
11498 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011499 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011500 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11501 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011502 }
11503
John McCall10eae182009-11-30 22:42:35 +000011504 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011505 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011506 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11507 if (MemExpr->hasExplicitTemplateArgs()) {
11508 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11509 TemplateArgs = &TemplateArgsBuffer;
11510 }
John McCall6b51f282009-11-23 01:53:49 +000011511
John McCall2d74de92009-12-01 22:10:20 +000011512 Expr *Base;
11513
John McCall7decc9e2010-11-18 06:31:45 +000011514 // If we're filling in a static method where we used to have an
11515 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011516 if (MemExpr->isImplicitAccess()) {
11517 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011518 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11519 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011520 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011521 Fn,
John McCall113bee02012-03-10 09:33:50 +000011522 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011523 MemExpr->getMemberLoc(),
11524 Fn->getType(),
11525 VK_LValue,
11526 Found.getDecl(),
11527 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011528 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011529 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11530 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011531 } else {
11532 SourceLocation Loc = MemExpr->getMemberLoc();
11533 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011534 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011535 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011536 Base = new (Context) CXXThisExpr(Loc,
11537 MemExpr->getBaseType(),
11538 /*isImplicit=*/true);
11539 }
John McCall2d74de92009-12-01 22:10:20 +000011540 } else
John McCallc3007a22010-10-26 07:05:15 +000011541 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011542
John McCall4adb38c2011-04-27 00:36:17 +000011543 ExprValueKind valueKind;
11544 QualType type;
11545 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11546 valueKind = VK_LValue;
11547 type = Fn->getType();
11548 } else {
11549 valueKind = VK_RValue;
11550 type = Context.BoundMemberTy;
11551 }
11552
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011553 MemberExpr *ME = MemberExpr::Create(Context, Base,
11554 MemExpr->isArrow(),
11555 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011556 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011557 Fn,
11558 Found,
11559 MemExpr->getMemberNameInfo(),
11560 TemplateArgs,
11561 type, valueKind, OK_Ordinary);
11562 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000011563 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011564 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011566
John McCallc3007a22010-10-26 07:05:15 +000011567 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011568}
11569
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011570ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011571 DeclAccessPair Found,
11572 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011573 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011574}
11575
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011576} // end namespace clang