blob: 7afa39f3f3b0b099e06ca8312a1f8c43e5e3e6d5 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000044 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith66e05fe2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000291/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
292/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000293NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000294StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
295 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000296 APValue &ConstantValue,
297 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000298 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000299
300 // C++11 [dcl.init.list]p7:
301 // A narrowing conversion is an implicit conversion ...
302 QualType FromType = getToType(0);
303 QualType ToType = getToType(1);
304 switch (Second) {
305 // -- from a floating-point type to an integer type, or
306 //
307 // -- from an integer type or unscoped enumeration type to a floating-point
308 // type, except where the source is a constant expression and the actual
309 // value after conversion will fit into the target type and will produce
310 // the original value when converted back to the original type, or
311 case ICK_Floating_Integral:
312 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
313 return NK_Type_Narrowing;
314 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
315 llvm::APSInt IntConstantValue;
316 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
317 if (Initializer &&
318 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
319 // Convert the integer to the floating type.
320 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
321 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
322 llvm::APFloat::rmNearestTiesToEven);
323 // And back.
324 llvm::APSInt ConvertedValue = IntConstantValue;
325 bool ignored;
326 Result.convertToInteger(ConvertedValue,
327 llvm::APFloat::rmTowardZero, &ignored);
328 // If the resulting value is different, this was a narrowing conversion.
329 if (IntConstantValue != ConvertedValue) {
330 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000331 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000332 return NK_Constant_Narrowing;
333 }
334 } else {
335 // Variables are always narrowings.
336 return NK_Variable_Narrowing;
337 }
338 }
339 return NK_Not_Narrowing;
340
341 // -- from long double to double or float, or from double to float, except
342 // where the source is a constant expression and the actual value after
343 // conversion is within the range of values that can be represented (even
344 // if it cannot be represented exactly), or
345 case ICK_Floating_Conversion:
346 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
347 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
348 // FromType is larger than ToType.
349 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
350 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
351 // Constant!
352 assert(ConstantValue.isFloat());
353 llvm::APFloat FloatVal = ConstantValue.getFloat();
354 // Convert the source value into the target type.
355 bool ignored;
356 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
357 Ctx.getFloatTypeSemantics(ToType),
358 llvm::APFloat::rmNearestTiesToEven, &ignored);
359 // If there was no overflow, the source value is within the range of
360 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000361 if (ConvertStatus & llvm::APFloat::opOverflow) {
362 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000363 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000364 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 } else {
366 return NK_Variable_Narrowing;
367 }
368 }
369 return NK_Not_Narrowing;
370
371 // -- from an integer type or unscoped enumeration type to an integer type
372 // that cannot represent all the values of the original type, except where
373 // the source is a constant expression and the actual value after
374 // conversion will fit into the target type and will produce the original
375 // value when converted back to the original type.
376 case ICK_Boolean_Conversion: // Bools are integers too.
377 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
378 // Boolean conversions can be from pointers and pointers to members
379 // [conv.bool], and those aren't considered narrowing conversions.
380 return NK_Not_Narrowing;
381 } // Otherwise, fall through to the integral case.
382 case ICK_Integral_Conversion: {
383 assert(FromType->isIntegralOrUnscopedEnumerationType());
384 assert(ToType->isIntegralOrUnscopedEnumerationType());
385 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
386 const unsigned FromWidth = Ctx.getIntWidth(FromType);
387 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
388 const unsigned ToWidth = Ctx.getIntWidth(ToType);
389
390 if (FromWidth > ToWidth ||
391 (FromWidth == ToWidth && FromSigned != ToSigned)) {
392 // Not all values of FromType can be represented in ToType.
393 llvm::APSInt InitializerValue;
394 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
395 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
396 ConstantValue = APValue(InitializerValue);
397
398 // Add a bit to the InitializerValue so we don't have to worry about
399 // signed vs. unsigned comparisons.
400 InitializerValue = InitializerValue.extend(
401 InitializerValue.getBitWidth() + 1);
402 // Convert the initializer to and from the target width and signed-ness.
403 llvm::APSInt ConvertedValue = InitializerValue;
404 ConvertedValue = ConvertedValue.trunc(ToWidth);
405 ConvertedValue.setIsSigned(ToSigned);
406 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
407 ConvertedValue.setIsSigned(InitializerValue.isSigned());
408 // If the result is different, this was a narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000409 if (ConvertedValue != InitializerValue) {
410 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000411 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000412 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000413 } else {
414 // Variables are always narrowings.
415 return NK_Variable_Narrowing;
416 }
417 }
418 return NK_Not_Narrowing;
419 }
420
421 default:
422 // Other kinds of conversions are not narrowings.
423 return NK_Not_Narrowing;
424 }
425}
426
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427/// DebugPrint - Print this standard conversion sequence to standard
428/// error. Useful for debugging overloading issues.
429void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000430 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431 bool PrintedSomething = false;
432 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434 PrintedSomething = true;
435 }
436
437 if (Second != ICK_Identity) {
438 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000440 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000441 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442
443 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000445 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000447 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (Third != ICK_Identity) {
454 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 }
464}
465
466/// DebugPrint - Print this user-defined conversion sequence to standard
467/// error. Useful for debugging overloading issues.
468void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 if (Before.First || Before.Second || Before.Third) {
471 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000474 if (ConversionFunction)
475 OS << '\'' << *ConversionFunction << '\'';
476 else
477 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 After.DebugPrint();
481 }
482}
483
484/// DebugPrint - Print this implicit conversion sequence to standard
485/// error. Useful for debugging overloading issues.
486void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 switch (ConversionKind) {
489 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 Standard.DebugPrint();
492 break;
493 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000494 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 UserDefined.DebugPrint();
496 break;
497 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 break;
John McCall0d1da222010-01-12 00:44:57 +0000500 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000502 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000503 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000504 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 break;
506 }
507
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509}
510
John McCall0d1da222010-01-12 00:44:57 +0000511void AmbiguousConversionSequence::construct() {
512 new (&conversions()) ConversionSet();
513}
514
515void AmbiguousConversionSequence::destruct() {
516 conversions().~ConversionSet();
517}
518
519void
520AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
521 FromTypePtr = O.FromTypePtr;
522 ToTypePtr = O.ToTypePtr;
523 new (&conversions()) ConversionSet(O.conversions());
524}
525
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526namespace {
527 // Structure used by OverloadCandidate::DeductionFailureInfo to store
528 // template parameter and template argument information.
529 struct DFIParamWithArguments {
530 TemplateParameter Param;
531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536/// \brief Convert from Sema's representation of template deduction information
537/// to the form used in overload-candidate information.
538OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000539static MakeDeductionFailureInfo(ASTContext &Context,
540 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000541 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 OverloadCandidate::DeductionFailureInfo Result;
543 Result.Result = static_cast<unsigned>(TDK);
544 Result.Data = 0;
545 switch (TDK) {
546 case Sema::TDK_Success:
547 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000548 case Sema::TDK_TooManyArguments:
549 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000553 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 Result.Data = Info.Param.getOpaqueValue();
555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000558 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Saved->Param = Info.Param;
562 Saved->FirstArg = Info.FirstArg;
563 Saved->SecondArg = Info.SecondArg;
564 Result.Data = Saved;
565 break;
566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000569 Result.Data = Info.take();
570 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 return Result;
578}
John McCall0d1da222010-01-12 00:44:57 +0000579
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580void OverloadCandidate::DeductionFailureInfo::Destroy() {
581 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
582 case Sema::TDK_Success:
583 case Sema::TDK_InstantiationDepth:
584 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000585 case Sema::TDK_TooManyArguments:
586 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000591 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000592 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000593 Data = 0;
594 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000595
596 case Sema::TDK_SubstitutionFailure:
597 // FIXME: Destroy the template arugment list?
598 Data = 0;
599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor461761d2010-05-08 18:20:53 +0000601 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_FailedOverloadResolution:
604 break;
605 }
606}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
608TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
610 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
611 case Sema::TDK_Success:
612 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000613 case Sema::TDK_TooManyArguments:
614 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000615 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000618 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000619 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621
622 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000623 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_FailedOverloadResolution:
629 break;
630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 return TemplateParameter();
633}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregord09efd42010-05-08 20:07:26 +0000635TemplateArgumentList *
636OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
637 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
638 case Sema::TDK_Success:
639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_TooManyArguments:
641 case Sema::TDK_TooFewArguments:
642 case Sema::TDK_Incomplete:
643 case Sema::TDK_InvalidExplicitArguments:
644 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 return 0;
647
648 case Sema::TDK_SubstitutionFailure:
649 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregord09efd42010-05-08 20:07:26 +0000651 // Unhandled
652 case Sema::TDK_NonDeducedMismatch:
653 case Sema::TDK_FailedOverloadResolution:
654 break;
655 }
656
657 return 0;
658}
659
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
661 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662 case Sema::TDK_Success:
663 case Sema::TDK_InstantiationDepth:
664 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000665 case Sema::TDK_TooManyArguments:
666 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000667 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 return 0;
670
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000671 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000672 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674
Douglas Gregor461761d2010-05-08 18:20:53 +0000675 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000676 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 case Sema::TDK_FailedOverloadResolution:
678 break;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683
684const TemplateArgument *
685OverloadCandidate::DeductionFailureInfo::getSecondArg() {
686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
687 case Sema::TDK_Success:
688 case Sema::TDK_InstantiationDepth:
689 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000690 case Sema::TDK_TooManyArguments:
691 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000692 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000693 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 return 0;
695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
699
Douglas Gregor461761d2010-05-08 18:20:53 +0000700 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 case Sema::TDK_FailedOverloadResolution:
703 break;
704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 return 0;
707}
708
709void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000710 for (iterator i = begin(), e = end(); i != e; ++i)
711 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
712 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000713 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000714 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 Functions.clear();
716}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717
John McCall4124c492011-10-17 18:40:02 +0000718namespace {
719 class UnbridgedCastsSet {
720 struct Entry {
721 Expr **Addr;
722 Expr *Saved;
723 };
724 SmallVector<Entry, 2> Entries;
725
726 public:
727 void save(Sema &S, Expr *&E) {
728 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
729 Entry entry = { &E, E };
730 Entries.push_back(entry);
731 E = S.stripARCUnbridgedCast(E);
732 }
733
734 void restore() {
735 for (SmallVectorImpl<Entry>::iterator
736 i = Entries.begin(), e = Entries.end(); i != e; ++i)
737 *i->Addr = i->Saved;
738 }
739 };
740}
741
742/// checkPlaceholderForOverload - Do any interesting placeholder-like
743/// preprocessing on the given expression.
744///
745/// \param unbridgedCasts a collection to which to add unbridged casts;
746/// without this, they will be immediately diagnosed as errors
747///
748/// Return true on unrecoverable error.
749static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
750 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000751 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
752 // We can't handle overloaded expressions here because overload
753 // resolution might reasonably tweak them.
754 if (placeholder->getKind() == BuiltinType::Overload) return false;
755
756 // If the context potentially accepts unbridged ARC casts, strip
757 // the unbridged cast and add it to the collection for later restoration.
758 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
759 unbridgedCasts) {
760 unbridgedCasts->save(S, E);
761 return false;
762 }
763
764 // Go ahead and check everything else.
765 ExprResult result = S.CheckPlaceholderExpr(E);
766 if (result.isInvalid())
767 return true;
768
769 E = result.take();
770 return false;
771 }
772
773 // Nothing to do.
774 return false;
775}
776
777/// checkArgPlaceholdersForOverload - Check a set of call operands for
778/// placeholders.
779static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
780 unsigned numArgs,
781 UnbridgedCastsSet &unbridged) {
782 for (unsigned i = 0; i != numArgs; ++i)
783 if (checkPlaceholderForOverload(S, args[i], &unbridged))
784 return true;
785
786 return false;
787}
788
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000790// overload of the declarations in Old. This routine returns false if
791// New and Old cannot be overloaded, e.g., if New has the same
792// signature as some function in Old (C++ 1.3.10) or if the Old
793// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000794// it does return false, MatchedDecl will point to the decl that New
795// cannot be overloaded with. This decl may be a UsingShadowDecl on
796// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797//
798// Example: Given the following input:
799//
800// void f(int, float); // #1
801// void f(int, int); // #2
802// int f(int, int); // #3
803//
804// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000805// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000806//
John McCall3d988d92009-12-02 08:47:38 +0000807// When we process #2, Old contains only the FunctionDecl for #1. By
808// comparing the parameter types, we see that #1 and #2 are overloaded
809// (since they have different signatures), so this routine returns
810// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811//
John McCall3d988d92009-12-02 08:47:38 +0000812// When we process #3, Old is an overload set containing #1 and #2. We
813// compare the signatures of #3 to #1 (they're overloaded, so we do
814// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
815// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816// signature), IsOverload returns false and MatchedDecl will be set to
817// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000818//
819// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
820// into a class by a using declaration. The rules for whether to hide
821// shadow declarations ignore some properties which otherwise figure
822// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000823Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000824Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
825 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000826 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000827 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000828 NamedDecl *OldD = *I;
829
830 bool OldIsUsingDecl = false;
831 if (isa<UsingShadowDecl>(OldD)) {
832 OldIsUsingDecl = true;
833
834 // We can always introduce two using declarations into the same
835 // context, even if they have identical signatures.
836 if (NewIsUsingDecl) continue;
837
838 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
839 }
840
841 // If either declaration was introduced by a using declaration,
842 // we'll need to use slightly different rules for matching.
843 // Essentially, these rules are the normal rules, except that
844 // function templates hide function templates with different
845 // return types or template parameter lists.
846 bool UseMemberUsingDeclRules =
847 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
848
John McCall3d988d92009-12-02 08:47:38 +0000849 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000850 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
851 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
852 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
853 continue;
854 }
855
John McCalldaa3d6b2009-12-09 03:35:25 +0000856 Match = *I;
857 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858 }
John McCall3d988d92009-12-02 08:47:38 +0000859 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000860 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
861 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
862 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
863 continue;
864 }
865
John McCalldaa3d6b2009-12-09 03:35:25 +0000866 Match = *I;
867 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000868 }
John McCalla8987a2942010-11-10 03:01:53 +0000869 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000870 // We can overload with these, which can show up when doing
871 // redeclaration checks for UsingDecls.
872 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000873 } else if (isa<TagDecl>(OldD)) {
874 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000875 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
876 // Optimistically assume that an unresolved using decl will
877 // overload; if it doesn't, we'll have to diagnose during
878 // template instantiation.
879 } else {
John McCall1f82f242009-11-18 22:49:29 +0000880 // (C++ 13p1):
881 // Only function declarations can be overloaded; object and type
882 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000883 Match = *I;
884 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000885 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886 }
John McCall1f82f242009-11-18 22:49:29 +0000887
John McCalldaa3d6b2009-12-09 03:35:25 +0000888 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000889}
890
John McCalle9cccd82010-06-16 08:42:20 +0000891bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
892 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000893 // If both of the functions are extern "C", then they are not
894 // overloads.
895 if (Old->isExternC() && New->isExternC())
896 return false;
897
John McCall1f82f242009-11-18 22:49:29 +0000898 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
899 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
900
901 // C++ [temp.fct]p2:
902 // A function template can be overloaded with other function templates
903 // and with normal (non-template) functions.
904 if ((OldTemplate == 0) != (NewTemplate == 0))
905 return true;
906
907 // Is the function New an overload of the function Old?
908 QualType OldQType = Context.getCanonicalType(Old->getType());
909 QualType NewQType = Context.getCanonicalType(New->getType());
910
911 // Compare the signatures (C++ 1.3.10) of the two functions to
912 // determine whether they are overloads. If we find any mismatch
913 // in the signature, they are overloads.
914
915 // If either of these functions is a K&R-style function (no
916 // prototype), then we consider them to have matching signatures.
917 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
918 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
919 return false;
920
John McCall424cec92011-01-19 06:33:43 +0000921 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
922 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000923
924 // The signature of a function includes the types of its
925 // parameters (C++ 1.3.10), which includes the presence or absence
926 // of the ellipsis; see C++ DR 357).
927 if (OldQType != NewQType &&
928 (OldType->getNumArgs() != NewType->getNumArgs() ||
929 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000930 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000931 return true;
932
933 // C++ [temp.over.link]p4:
934 // The signature of a function template consists of its function
935 // signature, its return type and its template parameter list. The names
936 // of the template parameters are significant only for establishing the
937 // relationship between the template parameters and the rest of the
938 // signature.
939 //
940 // We check the return type and template parameter lists for function
941 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000942 //
943 // However, we don't consider either of these when deciding whether
944 // a member introduced by a shadow declaration is hidden.
945 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000946 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
947 OldTemplate->getTemplateParameters(),
948 false, TPL_TemplateMatch) ||
949 OldType->getResultType() != NewType->getResultType()))
950 return true;
951
952 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000953 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000954 //
955 // As part of this, also check whether one of the member functions
956 // is static, in which case they are not overloads (C++
957 // 13.1p2). While not part of the definition of the signature,
958 // this check is important to determine whether these functions
959 // can be overloaded.
960 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
961 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
962 if (OldMethod && NewMethod &&
963 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000964 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000965 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
966 if (!UseUsingDeclRules &&
967 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
968 (OldMethod->getRefQualifier() == RQ_None ||
969 NewMethod->getRefQualifier() == RQ_None)) {
970 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971 // - Member function declarations with the same name and the same
972 // parameter-type-list as well as member function template
973 // declarations with the same name, the same parameter-type-list, and
974 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000975 // them, but not all, have a ref-qualifier (8.3.5).
976 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
977 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
978 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980
John McCall1f82f242009-11-18 22:49:29 +0000981 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
John McCall1f82f242009-11-18 22:49:29 +0000984 // The signatures match; this is not an overload.
985 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986}
987
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000988/// \brief Checks availability of the function depending on the current
989/// function context. Inside an unavailable function, unavailability is ignored.
990///
991/// \returns true if \arg FD is unavailable and current context is inside
992/// an available function, false otherwise.
993bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
994 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
995}
996
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000997/// \brief Tries a user-defined conversion from From to ToType.
998///
999/// Produces an implicit conversion sequence for when a standard conversion
1000/// is not an option. See TryImplicitConversion for more information.
1001static ImplicitConversionSequence
1002TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1003 bool SuppressUserConversions,
1004 bool AllowExplicit,
1005 bool InOverloadResolution,
1006 bool CStyle,
1007 bool AllowObjCWritebackConversion) {
1008 ImplicitConversionSequence ICS;
1009
1010 if (SuppressUserConversions) {
1011 // We're not in the case above, so there is no conversion that
1012 // we can perform.
1013 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1014 return ICS;
1015 }
1016
1017 // Attempt user-defined conversion.
1018 OverloadCandidateSet Conversions(From->getExprLoc());
1019 OverloadingResult UserDefResult
1020 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1021 AllowExplicit);
1022
1023 if (UserDefResult == OR_Success) {
1024 ICS.setUserDefined();
1025 // C++ [over.ics.user]p4:
1026 // A conversion of an expression of class type to the same class
1027 // type is given Exact Match rank, and a conversion of an
1028 // expression of class type to a base class of that type is
1029 // given Conversion rank, in spite of the fact that a copy
1030 // constructor (i.e., a user-defined conversion function) is
1031 // called for those cases.
1032 if (CXXConstructorDecl *Constructor
1033 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1034 QualType FromCanon
1035 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1036 QualType ToCanon
1037 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1038 if (Constructor->isCopyConstructor() &&
1039 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1040 // Turn this into a "standard" conversion sequence, so that it
1041 // gets ranked with standard conversion sequences.
1042 ICS.setStandard();
1043 ICS.Standard.setAsIdentityConversion();
1044 ICS.Standard.setFromType(From->getType());
1045 ICS.Standard.setAllToTypes(ToType);
1046 ICS.Standard.CopyConstructor = Constructor;
1047 if (ToCanon != FromCanon)
1048 ICS.Standard.Second = ICK_Derived_To_Base;
1049 }
1050 }
1051
1052 // C++ [over.best.ics]p4:
1053 // However, when considering the argument of a user-defined
1054 // conversion function that is a candidate by 13.3.1.3 when
1055 // invoked for the copying of the temporary in the second step
1056 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1057 // 13.3.1.6 in all cases, only standard conversion sequences and
1058 // ellipsis conversion sequences are allowed.
1059 if (SuppressUserConversions && ICS.isUserDefined()) {
1060 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1061 }
1062 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1063 ICS.setAmbiguous();
1064 ICS.Ambiguous.setFromType(From->getType());
1065 ICS.Ambiguous.setToType(ToType);
1066 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1067 Cand != Conversions.end(); ++Cand)
1068 if (Cand->Viable)
1069 ICS.Ambiguous.addConversion(Cand->Function);
1070 } else {
1071 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1072 }
1073
1074 return ICS;
1075}
1076
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001077/// TryImplicitConversion - Attempt to perform an implicit conversion
1078/// from the given expression (Expr) to the given type (ToType). This
1079/// function returns an implicit conversion sequence that can be used
1080/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001081///
1082/// void f(float f);
1083/// void g(int i) { f(i); }
1084///
1085/// this routine would produce an implicit conversion sequence to
1086/// describe the initialization of f from i, which will be a standard
1087/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1088/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1089//
1090/// Note that this routine only determines how the conversion can be
1091/// performed; it does not actually perform the conversion. As such,
1092/// it will not produce any diagnostics if no conversion is available,
1093/// but will instead return an implicit conversion sequence of kind
1094/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001095///
1096/// If @p SuppressUserConversions, then user-defined conversions are
1097/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001098/// If @p AllowExplicit, then explicit user-defined conversions are
1099/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001100///
1101/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1102/// writeback conversion, which allows __autoreleasing id* parameters to
1103/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001104static ImplicitConversionSequence
1105TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1106 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001108 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001109 bool CStyle,
1110 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001112 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001113 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001114 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001115 return ICS;
1116 }
1117
David Blaikiebbafb8a2012-03-11 07:00:24 +00001118 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001120 return ICS;
1121 }
1122
Douglas Gregor836a7e82010-08-11 02:15:33 +00001123 // C++ [over.ics.user]p4:
1124 // A conversion of an expression of class type to the same class
1125 // type is given Exact Match rank, and a conversion of an
1126 // expression of class type to a base class of that type is
1127 // given Conversion rank, in spite of the fact that a copy/move
1128 // constructor (i.e., a user-defined conversion function) is
1129 // called for those cases.
1130 QualType FromType = From->getType();
1131 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001132 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1133 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001134 ICS.setStandard();
1135 ICS.Standard.setAsIdentityConversion();
1136 ICS.Standard.setFromType(FromType);
1137 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregor5ab11652010-04-17 22:01:05 +00001139 // We don't actually check at this point whether there is a valid
1140 // copy/move constructor, since overloading just assumes that it
1141 // exists. When we actually perform initialization, we'll find the
1142 // appropriate constructor to copy the returned object, if needed.
1143 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
Douglas Gregor5ab11652010-04-17 22:01:05 +00001145 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001146 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001147 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148
Douglas Gregor836a7e82010-08-11 02:15:33 +00001149 return ICS;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001152 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1153 AllowExplicit, InOverloadResolution, CStyle,
1154 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155}
1156
John McCall31168b02011-06-15 23:02:42 +00001157ImplicitConversionSequence
1158Sema::TryImplicitConversion(Expr *From, QualType ToType,
1159 bool SuppressUserConversions,
1160 bool AllowExplicit,
1161 bool InOverloadResolution,
1162 bool CStyle,
1163 bool AllowObjCWritebackConversion) {
1164 return clang::TryImplicitConversion(*this, From, ToType,
1165 SuppressUserConversions, AllowExplicit,
1166 InOverloadResolution, CStyle,
1167 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001168}
1169
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001170/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001171/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001172/// converted expression. Flavor is the kind of conversion we're
1173/// performing, used in the error message. If @p AllowExplicit,
1174/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001175ExprResult
1176Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001177 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001178 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001179 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001180}
1181
John Wiegley01296292011-04-08 18:41:53 +00001182ExprResult
1183Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001184 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001185 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001186 if (checkPlaceholderForOverload(*this, From))
1187 return ExprError();
1188
John McCall31168b02011-06-15 23:02:42 +00001189 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1190 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001192 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001193
John McCall5c32be02010-08-24 20:38:10 +00001194 ICS = clang::TryImplicitConversion(*this, From, ToType,
1195 /*SuppressUserConversions=*/false,
1196 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001197 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001198 /*CStyle=*/false,
1199 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001200 return PerformImplicitConversion(From, ToType, ICS, Action);
1201}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202
1203/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001204/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001205bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1206 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001207 if (Context.hasSameUnqualifiedType(FromType, ToType))
1208 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209
John McCall991eb4b2010-12-21 00:44:39 +00001210 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1211 // where F adds one of the following at most once:
1212 // - a pointer
1213 // - a member pointer
1214 // - a block pointer
1215 CanQualType CanTo = Context.getCanonicalType(ToType);
1216 CanQualType CanFrom = Context.getCanonicalType(FromType);
1217 Type::TypeClass TyClass = CanTo->getTypeClass();
1218 if (TyClass != CanFrom->getTypeClass()) return false;
1219 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1220 if (TyClass == Type::Pointer) {
1221 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1223 } else if (TyClass == Type::BlockPointer) {
1224 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1225 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1226 } else if (TyClass == Type::MemberPointer) {
1227 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1228 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1229 } else {
1230 return false;
1231 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001232
John McCall991eb4b2010-12-21 00:44:39 +00001233 TyClass = CanTo->getTypeClass();
1234 if (TyClass != CanFrom->getTypeClass()) return false;
1235 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1236 return false;
1237 }
1238
1239 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1240 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1241 if (!EInfo.getNoReturn()) return false;
1242
1243 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1244 assert(QualType(FromFn, 0).isCanonical());
1245 if (QualType(FromFn, 0) != CanTo) return false;
1246
1247 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001248 return true;
1249}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
Douglas Gregor46188682010-05-18 22:42:18 +00001251/// \brief Determine whether the conversion from FromType to ToType is a valid
1252/// vector conversion.
1253///
1254/// \param ICK Will be set to the vector conversion kind, if this is a vector
1255/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001256static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1257 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001258 // We need at least one of these types to be a vector type to have a vector
1259 // conversion.
1260 if (!ToType->isVectorType() && !FromType->isVectorType())
1261 return false;
1262
1263 // Identical types require no conversions.
1264 if (Context.hasSameUnqualifiedType(FromType, ToType))
1265 return false;
1266
1267 // There are no conversions between extended vector types, only identity.
1268 if (ToType->isExtVectorType()) {
1269 // There are no conversions between extended vector types other than the
1270 // identity conversion.
1271 if (FromType->isExtVectorType())
1272 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Douglas Gregor46188682010-05-18 22:42:18 +00001274 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001275 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001276 ICK = ICK_Vector_Splat;
1277 return true;
1278 }
1279 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001280
1281 // We can perform the conversion between vector types in the following cases:
1282 // 1)vector types are equivalent AltiVec and GCC vector types
1283 // 2)lax vector conversions are permitted and the vector types are of the
1284 // same size
1285 if (ToType->isVectorType() && FromType->isVectorType()) {
1286 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001287 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001288 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001289 ICK = ICK_Vector_Conversion;
1290 return true;
1291 }
Douglas Gregor46188682010-05-18 22:42:18 +00001292 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001293
Douglas Gregor46188682010-05-18 22:42:18 +00001294 return false;
1295}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001297/// IsStandardConversion - Determines whether there is a standard
1298/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1299/// expression From to the type ToType. Standard conversion sequences
1300/// only consider non-class types; for conversions that involve class
1301/// types, use TryImplicitConversion. If a conversion exists, SCS will
1302/// contain the standard conversion sequence required to perform this
1303/// conversion and this routine will return true. Otherwise, this
1304/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001305static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1306 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001307 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001308 bool CStyle,
1309 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001310 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001313 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001314 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001315 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001316 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001317 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001319 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001320 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001321 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001322 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001323 return false;
1324
Mike Stump11289f42009-09-09 15:08:12 +00001325 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001326 }
1327
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001328 // The first conversion can be an lvalue-to-rvalue conversion,
1329 // array-to-pointer conversion, or function-to-pointer conversion
1330 // (C++ 4p1).
1331
John McCall5c32be02010-08-24 20:38:10 +00001332 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001333 DeclAccessPair AccessPair;
1334 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001336 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001337 // We were able to resolve the address of the overloaded function,
1338 // so we can convert to the type of that function.
1339 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001340
1341 // we can sometimes resolve &foo<int> regardless of ToType, so check
1342 // if the type matches (identity) or we are converting to bool
1343 if (!S.Context.hasSameUnqualifiedType(
1344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1345 QualType resultTy;
1346 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001347 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001348 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1349 // otherwise, only a boolean conversion is standard
1350 if (!ToType->isBooleanType())
1351 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Chandler Carruthffce2452011-03-29 08:08:18 +00001354 // Check if the "from" expression is taking the address of an overloaded
1355 // function and recompute the FromType accordingly. Take advantage of the
1356 // fact that non-static member functions *must* have such an address-of
1357 // expression.
1358 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1359 if (Method && !Method->isStatic()) {
1360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1361 "Non-unary operator on non-static member address");
1362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1363 == UO_AddrOf &&
1364 "Non-address-of operator on non-static member address");
1365 const Type *ClassType
1366 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1367 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001368 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1369 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1370 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001371 "Non-address-of operator for overloaded function expression");
1372 FromType = S.Context.getPointerType(FromType);
1373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor980fb162010-04-29 18:24:40 +00001375 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001376 assert(S.Context.hasSameType(
1377 FromType,
1378 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001379 } else {
1380 return false;
1381 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001382 }
John McCall154a2fd2011-08-30 00:57:29 +00001383 // Lvalue-to-rvalue conversion (C++11 4.1):
1384 // A glvalue (3.10) of a non-function, non-array type T can
1385 // be converted to a prvalue.
1386 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001387 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001388 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001389 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001390 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001391
1392 // If T is a non-class type, the type of the rvalue is the
1393 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001394 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1395 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001396 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001397 } else if (FromType->isArrayType()) {
1398 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001399 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
1401 // An lvalue or rvalue of type "array of N T" or "array of unknown
1402 // bound of T" can be converted to an rvalue of type "pointer to
1403 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001404 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405
John McCall5c32be02010-08-24 20:38:10 +00001406 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001408 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409
1410 // For the purpose of ranking in overload resolution
1411 // (13.3.3.1.1), this conversion is considered an
1412 // array-to-pointer conversion followed by a qualification
1413 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001414 SCS.Second = ICK_Identity;
1415 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001416 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001417 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001418 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001419 }
John McCall086a4642010-11-24 05:12:34 +00001420 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001421 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001422 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423
1424 // An lvalue of function type T can be converted to an rvalue of
1425 // type "pointer to T." The result is a pointer to the
1426 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001427 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001428 } else {
1429 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001430 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001431 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001432 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433
1434 // The second conversion can be an integral promotion, floating
1435 // point promotion, integral conversion, floating point conversion,
1436 // floating-integral conversion, pointer conversion,
1437 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001438 // For overloading in C, this can also be a "compatible-type"
1439 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001440 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001441 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001442 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 // The unqualified versions of the types are the same: there's no
1444 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001445 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001446 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001447 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001448 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001450 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001451 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001454 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001455 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001456 SCS.Second = ICK_Complex_Promotion;
1457 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001458 } else if (ToType->isBooleanType() &&
1459 (FromType->isArithmeticType() ||
1460 FromType->isAnyPointerType() ||
1461 FromType->isBlockPointerType() ||
1462 FromType->isMemberPointerType() ||
1463 FromType->isNullPtrType())) {
1464 // Boolean conversions (C++ 4.12).
1465 SCS.Second = ICK_Boolean_Conversion;
1466 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001467 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001468 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001469 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001472 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001473 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001474 SCS.Second = ICK_Complex_Conversion;
1475 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001476 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1477 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001478 // Complex-real conversions (C99 6.3.1.7)
1479 SCS.Second = ICK_Complex_Real;
1480 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001481 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001482 // Floating point conversions (C++ 4.8).
1483 SCS.Second = ICK_Floating_Conversion;
1484 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001486 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001487 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001488 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001489 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001490 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001492 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001493 SCS.Second = ICK_Block_Pointer_Conversion;
1494 } else if (AllowObjCWritebackConversion &&
1495 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1496 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001497 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1498 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001499 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001501 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001502 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001504 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001505 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001506 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001507 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001508 SCS.Second = SecondICK;
1509 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001510 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001511 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001512 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001513 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001514 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001515 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001516 // Treat a conversion that strips "noreturn" as an identity conversion.
1517 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001518 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1519 InOverloadResolution,
1520 SCS, CStyle)) {
1521 SCS.Second = ICK_TransparentUnionConversion;
1522 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 } else {
1524 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001527 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001529 QualType CanonFrom;
1530 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001532 bool ObjCLifetimeConversion;
1533 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1534 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001536 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001538 CanonFrom = S.Context.getCanonicalType(FromType);
1539 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001540 } else {
1541 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Third = ICK_Identity;
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 // [...] Any difference in top-level cv-qualification is
1546 // subsumed by the initialization itself and does not constitute
1547 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001548 CanonFrom = S.Context.getCanonicalType(FromType);
1549 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001551 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001552 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001553 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1554 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001555 FromType = ToType;
1556 CanonFrom = CanonTo;
1557 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001559 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
1561 // If we have not converted the argument type to the parameter type,
1562 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001563 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001568
1569static bool
1570IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1571 QualType &ToType,
1572 bool InOverloadResolution,
1573 StandardConversionSequence &SCS,
1574 bool CStyle) {
1575
1576 const RecordType *UT = ToType->getAsUnionType();
1577 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1578 return false;
1579 // The field to initialize within the transparent union.
1580 RecordDecl *UD = UT->getDecl();
1581 // It's compatible if the expression matches any of the fields.
1582 for (RecordDecl::field_iterator it = UD->field_begin(),
1583 itend = UD->field_end();
1584 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001585 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1586 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001587 ToType = it->getType();
1588 return true;
1589 }
1590 }
1591 return false;
1592}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593
1594/// IsIntegralPromotion - Determines whether the conversion from the
1595/// expression From (whose potentially-adjusted type is FromType) to
1596/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1597/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001598bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001599 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001600 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001601 if (!To) {
1602 return false;
1603 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604
1605 // An rvalue of type char, signed char, unsigned char, short int, or
1606 // unsigned short int can be converted to an rvalue of type int if
1607 // int can represent all the values of the source type; otherwise,
1608 // the source rvalue can be converted to an rvalue of type unsigned
1609 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001610 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1611 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 if (// We can promote any signed, promotable integer type to an int
1613 (FromType->isSignedIntegerType() ||
1614 // We can promote any unsigned integer type whose size is
1615 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001616 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001617 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001619 }
1620
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001621 return To->getKind() == BuiltinType::UInt;
1622 }
1623
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624 // C++0x [conv.prom]p3:
1625 // A prvalue of an unscoped enumeration type whose underlying type is not
1626 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1627 // following types that can represent all the values of the enumeration
1628 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1629 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001630 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001632 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633 // with lowest integer conversion rank (4.13) greater than the rank of long
1634 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001635 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001636 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1637 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1638 // provided for a scoped enumeration.
1639 if (FromEnumType->getDecl()->isScoped())
1640 return false;
1641
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001642 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001644 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001645 return Context.hasSameUnqualifiedType(ToType,
1646 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001647 }
John McCall56774992009-12-09 09:09:27 +00001648
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1651 // to an rvalue a prvalue of the first of the following types that can
1652 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001653 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001655 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001657 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001659 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660 // Determine whether the type we're converting from is signed or
1661 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001662 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 // The types we'll try to promote to, in the appropriate
1666 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001667 QualType PromoteTypes[6] = {
1668 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001669 Context.LongTy, Context.UnsignedLongTy ,
1670 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001672 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1674 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001675 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1677 // We found the type that we can promote to. If this is the
1678 // type we wanted, we have a promotion. Otherwise, no
1679 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001680 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681 }
1682 }
1683 }
1684
1685 // An rvalue for an integral bit-field (9.6) can be converted to an
1686 // rvalue of type int if int can represent all the values of the
1687 // bit-field; otherwise, it can be converted to unsigned int if
1688 // unsigned int can represent all the values of the bit-field. If
1689 // the bit-field is larger yet, no integral promotion applies to
1690 // it. If the bit-field has an enumerated type, it is treated as any
1691 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001692 // FIXME: We should delay checking of bit-fields until we actually perform the
1693 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001694 using llvm::APSInt;
1695 if (From)
1696 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001697 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001698 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001699 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1700 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1701 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001703 // Are we promoting to an int from a bitfield that fits in an int?
1704 if (BitWidth < ToSize ||
1705 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1706 return To->getKind() == BuiltinType::Int;
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001709 // Are we promoting to an unsigned int from an unsigned bitfield
1710 // that fits into an unsigned int?
1711 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1712 return To->getKind() == BuiltinType::UInt;
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001715 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 // An rvalue of type bool can be converted to an rvalue of type int,
1720 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001721 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724
1725 return false;
1726}
1727
1728/// IsFloatingPointPromotion - Determines whether the conversion from
1729/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1730/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001731bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001732 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1733 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001734 /// An rvalue of type float can be converted to an rvalue of type
1735 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001736 if (FromBuiltin->getKind() == BuiltinType::Float &&
1737 ToBuiltin->getKind() == BuiltinType::Double)
1738 return true;
1739
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001740 // C99 6.3.1.5p1:
1741 // When a float is promoted to double or long double, or a
1742 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001744 (FromBuiltin->getKind() == BuiltinType::Float ||
1745 FromBuiltin->getKind() == BuiltinType::Double) &&
1746 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1747 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001748
1749 // Half can be promoted to float.
1750 if (FromBuiltin->getKind() == BuiltinType::Half &&
1751 ToBuiltin->getKind() == BuiltinType::Float)
1752 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001753 }
1754
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001755 return false;
1756}
1757
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001758/// \brief Determine if a conversion is a complex promotion.
1759///
1760/// A complex promotion is defined as a complex -> complex conversion
1761/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001762/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001763bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001764 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001765 if (!FromComplex)
1766 return false;
1767
John McCall9dd450b2009-09-21 23:43:11 +00001768 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001769 if (!ToComplex)
1770 return false;
1771
1772 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001773 ToComplex->getElementType()) ||
1774 IsIntegralPromotion(0, FromComplex->getElementType(),
1775 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001776}
1777
Douglas Gregor237f96c2008-11-26 23:31:11 +00001778/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1779/// the pointer type FromPtr to a pointer to type ToPointee, with the
1780/// same type qualifiers as FromPtr has on its pointee type. ToType,
1781/// if non-empty, will be a pointer to ToType that may or may not have
1782/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001783///
Mike Stump11289f42009-09-09 15:08:12 +00001784static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001785BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001786 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001787 ASTContext &Context,
1788 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 assert((FromPtr->getTypeClass() == Type::Pointer ||
1790 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1791 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792
John McCall31168b02011-06-15 23:02:42 +00001793 /// Conversions to 'id' subsume cv-qualifier conversions.
1794 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001795 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
1797 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001798 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001799 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001800 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall31168b02011-06-15 23:02:42 +00001802 if (StripObjCLifetime)
1803 Quals.removeObjCLifetime();
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001806 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001807 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001808 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001809 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001810
1811 // Build a pointer to ToPointee. It has the right qualifiers
1812 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001813 if (isa<ObjCObjectPointerType>(ToType))
1814 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001815 return Context.getPointerType(ToPointee);
1816 }
1817
1818 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001819 QualType QualifiedCanonToPointee
1820 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001822 if (isa<ObjCObjectPointerType>(ToType))
1823 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1824 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001825}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Mike Stump11289f42009-09-09 15:08:12 +00001827static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001828 bool InOverloadResolution,
1829 ASTContext &Context) {
1830 // Handle value-dependent integral null pointer constants correctly.
1831 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1832 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001833 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001834 return !InOverloadResolution;
1835
Douglas Gregor56751b52009-09-25 04:25:58 +00001836 return Expr->isNullPointerConstant(Context,
1837 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1838 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001839}
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841/// IsPointerConversion - Determines whether the conversion of the
1842/// expression From, which has the (possibly adjusted) type FromType,
1843/// can be converted to the type ToType via a pointer conversion (C++
1844/// 4.10). If so, returns true and places the converted type (that
1845/// might differ from ToType in its cv-qualifiers at some level) into
1846/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001847///
Douglas Gregora29dc052008-11-27 01:19:21 +00001848/// This routine also supports conversions to and from block pointers
1849/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1850/// pointers to interfaces. FIXME: Once we've determined the
1851/// appropriate overloading rules for Objective-C, we may want to
1852/// split the Objective-C checks into a different routine; however,
1853/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001854/// conversions, so for now they live here. IncompatibleObjC will be
1855/// set if the conversion is an allowed Objective-C conversion that
1856/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001857bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001858 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001859 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001860 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001861 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001862 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1863 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001864 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001865
Mike Stump11289f42009-09-09 15:08:12 +00001866 // Conversion from a null pointer constant to any Objective-C pointer type.
1867 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001868 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001869 ConvertedType = ToType;
1870 return true;
1871 }
1872
Douglas Gregor231d1c62008-11-27 00:15:41 +00001873 // Blocks: Block pointers can be converted to void*.
1874 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879 // Blocks: A null pointer constant can be converted to a block
1880 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Sebastian Redl576fd422009-05-10 18:38:11 +00001887 // If the left-hand-side is nullptr_t, the right side can be a null
1888 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001889 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001890 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001891 ConvertedType = ToType;
1892 return true;
1893 }
1894
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001895 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 if (!ToTypePtr)
1897 return false;
1898
1899 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001900 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001901 ConvertedType = ToType;
1902 return true;
1903 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001904
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001906 // , including objective-c pointers.
1907 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001908 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001910 ConvertedType = BuildSimilarlyQualifiedPointerType(
1911 FromType->getAs<ObjCObjectPointerType>(),
1912 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001913 ToType, Context);
1914 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001915 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001916 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001917 if (!FromTypePtr)
1918 return false;
1919
1920 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001921
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001923 // pointer conversion, so don't do all of the work below.
1924 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1925 return false;
1926
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927 // An rvalue of type "pointer to cv T," where T is an object type,
1928 // can be converted to an rvalue of type "pointer to cv void" (C++
1929 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001930 if (FromPointeeType->isIncompleteOrObjectType() &&
1931 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001932 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001933 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001934 ToType, Context,
1935 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936 return true;
1937 }
1938
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001939 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001940 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001941 ToPointeeType->isVoidType()) {
1942 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1943 ToPointeeType,
1944 ToType, Context);
1945 return true;
1946 }
1947
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001948 // When we're overloading in C, we allow a special kind of pointer
1949 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001951 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001953 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001954 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001955 return true;
1956 }
1957
Douglas Gregor5c407d92008-10-23 00:40:37 +00001958 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001959 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001960 // An rvalue of type "pointer to cv D," where D is a class type,
1961 // can be converted to an rvalue of type "pointer to cv B," where
1962 // B is a base class (clause 10) of D. If B is an inaccessible
1963 // (clause 11) or ambiguous (10.2) base class of D, a program that
1964 // necessitates this conversion is ill-formed. The result of the
1965 // conversion is a pointer to the base class sub-object of the
1966 // derived class object. The null pointer value is converted to
1967 // the null pointer value of the destination type.
1968 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001969 // Note that we do not check for ambiguity or inaccessibility
1970 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001971 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001972 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001973 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001974 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001975 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001977 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001978 ToType, Context);
1979 return true;
1980 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001981
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001982 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1983 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1985 ToPointeeType,
1986 ToType, Context);
1987 return true;
1988 }
1989
Douglas Gregora119f102008-12-19 19:13:09 +00001990 return false;
1991}
Douglas Gregoraec25842011-04-26 23:16:46 +00001992
1993/// \brief Adopt the given qualifiers for the given type.
1994static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1995 Qualifiers TQs = T.getQualifiers();
1996
1997 // Check whether qualifiers already match.
1998 if (TQs == Qs)
1999 return T;
2000
2001 if (Qs.compatiblyIncludes(TQs))
2002 return Context.getQualifiedType(T, Qs);
2003
2004 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2005}
Douglas Gregora119f102008-12-19 19:13:09 +00002006
2007/// isObjCPointerConversion - Determines whether this is an
2008/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2009/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002010bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002011 QualType& ConvertedType,
2012 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002013 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002014 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregoraec25842011-04-26 23:16:46 +00002016 // The set of qualifiers on the type we're converting from.
2017 Qualifiers FromQualifiers = FromType.getQualifiers();
2018
Steve Naroff7cae42b2009-07-10 23:34:53 +00002019 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002020 const ObjCObjectPointerType* ToObjCPtr =
2021 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002022 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002023 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002024
Steve Naroff7cae42b2009-07-10 23:34:53 +00002025 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002026 // If the pointee types are the same (ignoring qualifications),
2027 // then this is not a pointer conversion.
2028 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2029 FromObjCPtr->getPointeeType()))
2030 return false;
2031
Douglas Gregoraec25842011-04-26 23:16:46 +00002032 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002033 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002034 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002035 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002040 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002041 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002042 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002043 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002044 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002045 return true;
2046 }
2047 // Objective C++: We're able to convert from a pointer to an
2048 // interface to a pointer to a different interface.
2049 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002050 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2051 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002052 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002053 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2054 FromObjCPtr->getPointeeType()))
2055 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002057 ToObjCPtr->getPointeeType(),
2058 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002059 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002060 return true;
2061 }
2062
2063 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2064 // Okay: this is some kind of implicit downcast of Objective-C
2065 // interfaces, which is permitted. However, we're going to
2066 // complain about it.
2067 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002069 ToObjCPtr->getPointeeType(),
2070 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002071 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002072 return true;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002075 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002076 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002077 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002078 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002080 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002081 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002082 // to a block pointer type.
2083 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002084 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002085 return true;
2086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002087 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002090 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002092 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002093 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002094 return true;
2095 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002096 else
Douglas Gregora119f102008-12-19 19:13:09 +00002097 return false;
2098
Douglas Gregor033f56d2008-12-23 00:53:59 +00002099 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002100 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002101 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002102 else if (const BlockPointerType *FromBlockPtr =
2103 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002104 FromPointeeType = FromBlockPtr->getPointeeType();
2105 else
Douglas Gregora119f102008-12-19 19:13:09 +00002106 return false;
2107
Douglas Gregora119f102008-12-19 19:13:09 +00002108 // If we have pointers to pointers, recursively check whether this
2109 // is an Objective-C conversion.
2110 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2111 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2112 IncompatibleObjC)) {
2113 // We always complain about this conversion.
2114 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002115 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002116 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002117 return true;
2118 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002119 // Allow conversion of pointee being objective-c pointer to another one;
2120 // as in I* to id.
2121 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2122 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2123 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2124 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002125
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002126 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002127 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002128 return true;
2129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor033f56d2008-12-23 00:53:59 +00002131 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002132 // differences in the argument and result types are in Objective-C
2133 // pointer conversions. If so, we permit the conversion (but
2134 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002135 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002136 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002137 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002138 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002139 if (FromFunctionType && ToFunctionType) {
2140 // If the function types are exactly the same, this isn't an
2141 // Objective-C pointer conversion.
2142 if (Context.getCanonicalType(FromPointeeType)
2143 == Context.getCanonicalType(ToPointeeType))
2144 return false;
2145
2146 // Perform the quick checks that will tell us whether these
2147 // function types are obviously different.
2148 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2149 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2150 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2151 return false;
2152
2153 bool HasObjCConversion = false;
2154 if (Context.getCanonicalType(FromFunctionType->getResultType())
2155 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2156 // Okay, the types match exactly. Nothing to do.
2157 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2158 ToFunctionType->getResultType(),
2159 ConvertedType, IncompatibleObjC)) {
2160 // Okay, we have an Objective-C pointer conversion.
2161 HasObjCConversion = true;
2162 } else {
2163 // Function types are too different. Abort.
2164 return false;
2165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Douglas Gregora119f102008-12-19 19:13:09 +00002167 // Check argument types.
2168 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2169 ArgIdx != NumArgs; ++ArgIdx) {
2170 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2171 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2172 if (Context.getCanonicalType(FromArgType)
2173 == Context.getCanonicalType(ToArgType)) {
2174 // Okay, the types match exactly. Nothing to do.
2175 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2176 ConvertedType, IncompatibleObjC)) {
2177 // Okay, we have an Objective-C pointer conversion.
2178 HasObjCConversion = true;
2179 } else {
2180 // Argument types are too different. Abort.
2181 return false;
2182 }
2183 }
2184
2185 if (HasObjCConversion) {
2186 // We had an Objective-C conversion. Allow this pointer
2187 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002189 IncompatibleObjC = true;
2190 return true;
2191 }
2192 }
2193
Sebastian Redl72b597d2009-01-25 19:43:20 +00002194 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
John McCall31168b02011-06-15 23:02:42 +00002197/// \brief Determine whether this is an Objective-C writeback conversion,
2198/// used for parameter passing when performing automatic reference counting.
2199///
2200/// \param FromType The type we're converting form.
2201///
2202/// \param ToType The type we're converting to.
2203///
2204/// \param ConvertedType The type that will be produced after applying
2205/// this conversion.
2206bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2207 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002208 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002209 Context.hasSameUnqualifiedType(FromType, ToType))
2210 return false;
2211
2212 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2213 QualType ToPointee;
2214 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2215 ToPointee = ToPointer->getPointeeType();
2216 else
2217 return false;
2218
2219 Qualifiers ToQuals = ToPointee.getQualifiers();
2220 if (!ToPointee->isObjCLifetimeType() ||
2221 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002222 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002223 return false;
2224
2225 // Argument must be a pointer to __strong to __weak.
2226 QualType FromPointee;
2227 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2228 FromPointee = FromPointer->getPointeeType();
2229 else
2230 return false;
2231
2232 Qualifiers FromQuals = FromPointee.getQualifiers();
2233 if (!FromPointee->isObjCLifetimeType() ||
2234 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2235 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2236 return false;
2237
2238 // Make sure that we have compatible qualifiers.
2239 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2240 if (!ToQuals.compatiblyIncludes(FromQuals))
2241 return false;
2242
2243 // Remove qualifiers from the pointee type we're converting from; they
2244 // aren't used in the compatibility check belong, and we'll be adding back
2245 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2246 FromPointee = FromPointee.getUnqualifiedType();
2247
2248 // The unqualified form of the pointee types must be compatible.
2249 ToPointee = ToPointee.getUnqualifiedType();
2250 bool IncompatibleObjC;
2251 if (Context.typesAreCompatible(FromPointee, ToPointee))
2252 FromPointee = ToPointee;
2253 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2254 IncompatibleObjC))
2255 return false;
2256
2257 /// \brief Construct the type we're converting to, which is a pointer to
2258 /// __autoreleasing pointee.
2259 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2260 ConvertedType = Context.getPointerType(FromPointee);
2261 return true;
2262}
2263
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002264bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2265 QualType& ConvertedType) {
2266 QualType ToPointeeType;
2267 if (const BlockPointerType *ToBlockPtr =
2268 ToType->getAs<BlockPointerType>())
2269 ToPointeeType = ToBlockPtr->getPointeeType();
2270 else
2271 return false;
2272
2273 QualType FromPointeeType;
2274 if (const BlockPointerType *FromBlockPtr =
2275 FromType->getAs<BlockPointerType>())
2276 FromPointeeType = FromBlockPtr->getPointeeType();
2277 else
2278 return false;
2279 // We have pointer to blocks, check whether the only
2280 // differences in the argument and result types are in Objective-C
2281 // pointer conversions. If so, we permit the conversion.
2282
2283 const FunctionProtoType *FromFunctionType
2284 = FromPointeeType->getAs<FunctionProtoType>();
2285 const FunctionProtoType *ToFunctionType
2286 = ToPointeeType->getAs<FunctionProtoType>();
2287
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002288 if (!FromFunctionType || !ToFunctionType)
2289 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002290
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002291 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002292 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002293
2294 // Perform the quick checks that will tell us whether these
2295 // function types are obviously different.
2296 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2297 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2298 return false;
2299
2300 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2301 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2302 if (FromEInfo != ToEInfo)
2303 return false;
2304
2305 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002306 if (Context.hasSameType(FromFunctionType->getResultType(),
2307 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002308 // Okay, the types match exactly. Nothing to do.
2309 } else {
2310 QualType RHS = FromFunctionType->getResultType();
2311 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002312 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002313 !RHS.hasQualifiers() && LHS.hasQualifiers())
2314 LHS = LHS.getUnqualifiedType();
2315
2316 if (Context.hasSameType(RHS,LHS)) {
2317 // OK exact match.
2318 } else if (isObjCPointerConversion(RHS, LHS,
2319 ConvertedType, IncompatibleObjC)) {
2320 if (IncompatibleObjC)
2321 return false;
2322 // Okay, we have an Objective-C pointer conversion.
2323 }
2324 else
2325 return false;
2326 }
2327
2328 // Check argument types.
2329 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2330 ArgIdx != NumArgs; ++ArgIdx) {
2331 IncompatibleObjC = false;
2332 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2333 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2334 if (Context.hasSameType(FromArgType, ToArgType)) {
2335 // Okay, the types match exactly. Nothing to do.
2336 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2337 ConvertedType, IncompatibleObjC)) {
2338 if (IncompatibleObjC)
2339 return false;
2340 // Okay, we have an Objective-C pointer conversion.
2341 } else
2342 // Argument types are too different. Abort.
2343 return false;
2344 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002345 if (LangOpts.ObjCAutoRefCount &&
2346 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2347 ToFunctionType))
2348 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002349
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002350 ConvertedType = ToType;
2351 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002352}
2353
Richard Trieucaff2472011-11-23 22:32:32 +00002354enum {
2355 ft_default,
2356 ft_different_class,
2357 ft_parameter_arity,
2358 ft_parameter_mismatch,
2359 ft_return_type,
2360 ft_qualifer_mismatch
2361};
2362
2363/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2364/// function types. Catches different number of parameter, mismatch in
2365/// parameter types, and different return types.
2366void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2367 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002368 // If either type is not valid, include no extra info.
2369 if (FromType.isNull() || ToType.isNull()) {
2370 PDiag << ft_default;
2371 return;
2372 }
2373
Richard Trieucaff2472011-11-23 22:32:32 +00002374 // Get the function type from the pointers.
2375 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2376 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2377 *ToMember = ToType->getAs<MemberPointerType>();
2378 if (FromMember->getClass() != ToMember->getClass()) {
2379 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2380 << QualType(FromMember->getClass(), 0);
2381 return;
2382 }
2383 FromType = FromMember->getPointeeType();
2384 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002385 }
2386
Richard Trieu96ed5b62011-12-13 23:19:45 +00002387 if (FromType->isPointerType())
2388 FromType = FromType->getPointeeType();
2389 if (ToType->isPointerType())
2390 ToType = ToType->getPointeeType();
2391
2392 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002393 FromType = FromType.getNonReferenceType();
2394 ToType = ToType.getNonReferenceType();
2395
Richard Trieucaff2472011-11-23 22:32:32 +00002396 // Don't print extra info for non-specialized template functions.
2397 if (FromType->isInstantiationDependentType() &&
2398 !FromType->getAs<TemplateSpecializationType>()) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieu96ed5b62011-12-13 23:19:45 +00002403 // No extra info for same types.
2404 if (Context.hasSameType(FromType, ToType)) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
Richard Trieucaff2472011-11-23 22:32:32 +00002409 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2410 *ToFunction = ToType->getAs<FunctionProtoType>();
2411
2412 // Both types need to be function types.
2413 if (!FromFunction || !ToFunction) {
2414 PDiag << ft_default;
2415 return;
2416 }
2417
2418 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2419 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2420 << FromFunction->getNumArgs();
2421 return;
2422 }
2423
2424 // Handle different parameter types.
2425 unsigned ArgPos;
2426 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2427 PDiag << ft_parameter_mismatch << ArgPos + 1
2428 << ToFunction->getArgType(ArgPos)
2429 << FromFunction->getArgType(ArgPos);
2430 return;
2431 }
2432
2433 // Handle different return type.
2434 if (!Context.hasSameType(FromFunction->getResultType(),
2435 ToFunction->getResultType())) {
2436 PDiag << ft_return_type << ToFunction->getResultType()
2437 << FromFunction->getResultType();
2438 return;
2439 }
2440
2441 unsigned FromQuals = FromFunction->getTypeQuals(),
2442 ToQuals = ToFunction->getTypeQuals();
2443 if (FromQuals != ToQuals) {
2444 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2445 return;
2446 }
2447
2448 // Unable to find a difference, so add no extra info.
2449 PDiag << ft_default;
2450}
2451
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002452/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002453/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002454/// they have same number of arguments. This routine assumes that Objective-C
2455/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002456/// If the parameters are different, ArgPos will have the the parameter index
2457/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002459 const FunctionProtoType *NewType,
2460 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002462 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2463 N = NewType->arg_type_begin(),
2464 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2465 if (!Context.hasSameType(*O, *N)) {
2466 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2467 return false;
2468 }
2469 }
2470 return true;
2471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002473 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2474 N = NewType->arg_type_begin(),
2475 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2476 QualType ToType = (*O);
2477 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002478 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002479 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2480 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002481 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2482 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2483 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2484 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002485 continue;
2486 }
John McCall8b07ec22010-05-15 11:32:37 +00002487 else if (const ObjCObjectPointerType *PTTo =
2488 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002490 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002491 if (Context.hasSameUnqualifiedType(
2492 PTTo->getObjectType()->getBaseType(),
2493 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002494 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002495 }
Richard Trieucaff2472011-11-23 22:32:32 +00002496 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002498 }
2499 }
2500 return true;
2501}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002502
Douglas Gregor39c16d42008-10-24 04:54:22 +00002503/// CheckPointerConversion - Check the pointer conversion from the
2504/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002505/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002506/// conversions for which IsPointerConversion has already returned
2507/// true. It returns true and produces a diagnostic if there was an
2508/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002509bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002510 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002511 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002512 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002513 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002514 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002515
John McCall8cb679e2010-11-15 09:13:47 +00002516 Kind = CK_BitCast;
2517
Chandler Carruthffab8732011-04-09 07:32:05 +00002518 if (!IsCStyleOrFunctionalCast &&
2519 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2520 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2521 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002522 PDiag(diag::warn_impcast_bool_to_null_pointer)
2523 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002524
John McCall9320b872011-09-09 05:25:32 +00002525 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2526 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002527 QualType FromPointeeType = FromPtrType->getPointeeType(),
2528 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002529
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002530 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2531 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002532 // We must have a derived-to-base conversion. Check an
2533 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002534 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2535 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002536 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002537 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002538 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002540 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002541 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002542 }
2543 }
John McCall9320b872011-09-09 05:25:32 +00002544 } else if (const ObjCObjectPointerType *ToPtrType =
2545 ToType->getAs<ObjCObjectPointerType>()) {
2546 if (const ObjCObjectPointerType *FromPtrType =
2547 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002548 // Objective-C++ conversions are always okay.
2549 // FIXME: We should have a different class of conversions for the
2550 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002551 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002552 return false;
John McCall9320b872011-09-09 05:25:32 +00002553 } else if (FromType->isBlockPointerType()) {
2554 Kind = CK_BlockPointerToObjCPointerCast;
2555 } else {
2556 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002557 }
John McCall9320b872011-09-09 05:25:32 +00002558 } else if (ToType->isBlockPointerType()) {
2559 if (!FromType->isBlockPointerType())
2560 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002561 }
John McCall8cb679e2010-11-15 09:13:47 +00002562
2563 // We shouldn't fall into this case unless it's valid for other
2564 // reasons.
2565 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2566 Kind = CK_NullToPointer;
2567
Douglas Gregor39c16d42008-10-24 04:54:22 +00002568 return false;
2569}
2570
Sebastian Redl72b597d2009-01-25 19:43:20 +00002571/// IsMemberPointerConversion - Determines whether the conversion of the
2572/// expression From, which has the (possibly adjusted) type FromType, can be
2573/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2574/// If so, returns true and places the converted type (that might differ from
2575/// ToType in its cv-qualifiers at some level) into ConvertedType.
2576bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002577 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002578 bool InOverloadResolution,
2579 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002580 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002581 if (!ToTypePtr)
2582 return false;
2583
2584 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002585 if (From->isNullPointerConstant(Context,
2586 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2587 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002588 ConvertedType = ToType;
2589 return true;
2590 }
2591
2592 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002593 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002594 if (!FromTypePtr)
2595 return false;
2596
2597 // A pointer to member of B can be converted to a pointer to member of D,
2598 // where D is derived from B (C++ 4.11p2).
2599 QualType FromClass(FromTypePtr->getClass(), 0);
2600 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002601
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002602 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2603 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2604 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002605 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2606 ToClass.getTypePtr());
2607 return true;
2608 }
2609
2610 return false;
2611}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612
Sebastian Redl72b597d2009-01-25 19:43:20 +00002613/// CheckMemberPointerConversion - Check the member pointer conversion from the
2614/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002615/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002616/// for which IsMemberPointerConversion has already returned true. It returns
2617/// true and produces a diagnostic if there was an error, or returns false
2618/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002619bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002620 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002621 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002622 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002623 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002624 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002625 if (!FromPtrType) {
2626 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002627 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002628 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002629 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002630 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002631 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002632 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002633
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002634 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002635 assert(ToPtrType && "No member pointer cast has a target type "
2636 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002637
Sebastian Redled8f2002009-01-28 18:33:18 +00002638 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2639 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002640
Sebastian Redled8f2002009-01-28 18:33:18 +00002641 // FIXME: What about dependent types?
2642 assert(FromClass->isRecordType() && "Pointer into non-class.");
2643 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002644
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002645 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002646 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002647 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2648 assert(DerivationOkay &&
2649 "Should not have been called if derivation isn't OK.");
2650 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002651
Sebastian Redled8f2002009-01-28 18:33:18 +00002652 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2653 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002654 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2655 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2656 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2657 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002658 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002659
Douglas Gregor89ee6822009-02-28 01:32:25 +00002660 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002661 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2662 << FromClass << ToClass << QualType(VBase, 0)
2663 << From->getSourceRange();
2664 return true;
2665 }
2666
John McCall5b0829a2010-02-10 09:31:12 +00002667 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002668 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2669 Paths.front(),
2670 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002671
Anders Carlssond7923c62009-08-22 23:33:40 +00002672 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002673 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002674 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002675 return false;
2676}
2677
Douglas Gregor9a657932008-10-21 23:43:52 +00002678/// IsQualificationConversion - Determines whether the conversion from
2679/// an rvalue of type FromType to ToType is a qualification conversion
2680/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002681///
2682/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2683/// when the qualification conversion involves a change in the Objective-C
2684/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002685bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002687 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002688 FromType = Context.getCanonicalType(FromType);
2689 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002690 ObjCLifetimeConversion = false;
2691
Douglas Gregor9a657932008-10-21 23:43:52 +00002692 // If FromType and ToType are the same type, this is not a
2693 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002694 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002696
Douglas Gregor9a657932008-10-21 23:43:52 +00002697 // (C++ 4.4p4):
2698 // A conversion can add cv-qualifiers at levels other than the first
2699 // in multi-level pointers, subject to the following rules: [...]
2700 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002701 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002702 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002703 // Within each iteration of the loop, we check the qualifiers to
2704 // determine if this still looks like a qualification
2705 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002706 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002707 // until there are no more pointers or pointers-to-members left to
2708 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002709 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002710
Douglas Gregor90609aa2011-04-25 18:40:17 +00002711 Qualifiers FromQuals = FromType.getQualifiers();
2712 Qualifiers ToQuals = ToType.getQualifiers();
2713
John McCall31168b02011-06-15 23:02:42 +00002714 // Objective-C ARC:
2715 // Check Objective-C lifetime conversions.
2716 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2717 UnwrappedAnyPointer) {
2718 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2719 ObjCLifetimeConversion = true;
2720 FromQuals.removeObjCLifetime();
2721 ToQuals.removeObjCLifetime();
2722 } else {
2723 // Qualification conversions cannot cast between different
2724 // Objective-C lifetime qualifiers.
2725 return false;
2726 }
2727 }
2728
Douglas Gregorf30053d2011-05-08 06:09:53 +00002729 // Allow addition/removal of GC attributes but not changing GC attributes.
2730 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2731 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2732 FromQuals.removeObjCGCAttr();
2733 ToQuals.removeObjCGCAttr();
2734 }
2735
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 // -- for every j > 0, if const is in cv 1,j then const is in cv
2737 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002738 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Douglas Gregor9a657932008-10-21 23:43:52 +00002741 // -- if the cv 1,j and cv 2,j are different, then const is in
2742 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002743 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002744 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002745 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor9a657932008-10-21 23:43:52 +00002747 // Keep track of whether all prior cv-qualifiers in the "to" type
2748 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002749 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002750 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002751 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002752
2753 // We are left with FromType and ToType being the pointee types
2754 // after unwrapping the original FromType and ToType the same number
2755 // of types. If we unwrapped any pointers, and if FromType and
2756 // ToType have the same unqualified type (since we checked
2757 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002758 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002759}
2760
Sebastian Redle5417162012-03-27 18:33:03 +00002761static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2762 CXXConstructorDecl *Constructor,
2763 QualType Type) {
2764 const FunctionProtoType *CtorType =
2765 Constructor->getType()->getAs<FunctionProtoType>();
2766 if (CtorType->getNumArgs() > 0) {
2767 QualType FirstArg = CtorType->getArgType(0);
2768 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2769 return true;
2770 }
2771 return false;
2772}
2773
Sebastian Redl82ace982012-02-11 23:51:08 +00002774static OverloadingResult
2775IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2776 CXXRecordDecl *To,
2777 UserDefinedConversionSequence &User,
2778 OverloadCandidateSet &CandidateSet,
2779 bool AllowExplicit) {
2780 DeclContext::lookup_iterator Con, ConEnd;
2781 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2782 Con != ConEnd; ++Con) {
2783 NamedDecl *D = *Con;
2784 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2785
2786 // Find the constructor (which may be a template).
2787 CXXConstructorDecl *Constructor = 0;
2788 FunctionTemplateDecl *ConstructorTmpl
2789 = dyn_cast<FunctionTemplateDecl>(D);
2790 if (ConstructorTmpl)
2791 Constructor
2792 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2793 else
2794 Constructor = cast<CXXConstructorDecl>(D);
2795
2796 bool Usable = !Constructor->isInvalidDecl() &&
2797 S.isInitListConstructor(Constructor) &&
2798 (AllowExplicit || !Constructor->isExplicit());
2799 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002800 // If the first argument is (a reference to) the target type,
2801 // suppress conversions.
2802 bool SuppressUserConversions =
2803 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002804 if (ConstructorTmpl)
2805 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2806 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002807 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002808 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002809 else
2810 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002811 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002812 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002813 }
2814 }
2815
2816 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2817
2818 OverloadCandidateSet::iterator Best;
2819 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2820 case OR_Success: {
2821 // Record the standard conversion we used and the conversion function.
2822 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2823 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2824
2825 QualType ThisType = Constructor->getThisType(S.Context);
2826 // Initializer lists don't have conversions as such.
2827 User.Before.setAsIdentityConversion();
2828 User.HadMultipleCandidates = HadMultipleCandidates;
2829 User.ConversionFunction = Constructor;
2830 User.FoundConversionFunction = Best->FoundDecl;
2831 User.After.setAsIdentityConversion();
2832 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2833 User.After.setAllToTypes(ToType);
2834 return OR_Success;
2835 }
2836
2837 case OR_No_Viable_Function:
2838 return OR_No_Viable_Function;
2839 case OR_Deleted:
2840 return OR_Deleted;
2841 case OR_Ambiguous:
2842 return OR_Ambiguous;
2843 }
2844
2845 llvm_unreachable("Invalid OverloadResult!");
2846}
2847
Douglas Gregor576e98c2009-01-30 23:27:23 +00002848/// Determines whether there is a user-defined conversion sequence
2849/// (C++ [over.ics.user]) that converts expression From to the type
2850/// ToType. If such a conversion exists, User will contain the
2851/// user-defined conversion sequence that performs such a conversion
2852/// and this routine will return true. Otherwise, this routine returns
2853/// false and User is unspecified.
2854///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002855/// \param AllowExplicit true if the conversion should consider C++0x
2856/// "explicit" conversion functions as well as non-explicit conversion
2857/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002858static OverloadingResult
2859IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002860 UserDefinedConversionSequence &User,
2861 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002862 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002863 // Whether we will only visit constructors.
2864 bool ConstructorsOnly = false;
2865
2866 // If the type we are conversion to is a class type, enumerate its
2867 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002868 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002869 // C++ [over.match.ctor]p1:
2870 // When objects of class type are direct-initialized (8.5), or
2871 // copy-initialized from an expression of the same or a
2872 // derived class type (8.5), overload resolution selects the
2873 // constructor. [...] For copy-initialization, the candidate
2874 // functions are all the converting constructors (12.3.1) of
2875 // that class. The argument list is the expression-list within
2876 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002877 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002878 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002879 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002880 ConstructorsOnly = true;
2881
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002882 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2883 // RequireCompleteType may have returned true due to some invalid decl
2884 // during template instantiation, but ToType may be complete enough now
2885 // to try to recover.
2886 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002887 // We're not going to find any constructors.
2888 } else if (CXXRecordDecl *ToRecordDecl
2889 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002890
2891 Expr **Args = &From;
2892 unsigned NumArgs = 1;
2893 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002894 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002895 // But first, see if there is an init-list-contructor that will work.
2896 OverloadingResult Result = IsInitializerListConstructorConversion(
2897 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2898 if (Result != OR_No_Viable_Function)
2899 return Result;
2900 // Never mind.
2901 CandidateSet.clear();
2902
2903 // If we're list-initializing, we pass the individual elements as
2904 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002905 Args = InitList->getInits();
2906 NumArgs = InitList->getNumInits();
2907 ListInitializing = true;
2908 }
2909
Douglas Gregor89ee6822009-02-28 01:32:25 +00002910 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002911 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002912 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002913 NamedDecl *D = *Con;
2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2915
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002916 // Find the constructor (which may be a template).
2917 CXXConstructorDecl *Constructor = 0;
2918 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002919 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002920 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002921 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002922 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2923 else
John McCalla0296f72010-03-19 07:35:19 +00002924 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002926 bool Usable = !Constructor->isInvalidDecl();
2927 if (ListInitializing)
2928 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2929 else
2930 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2931 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00002932 bool SuppressUserConversions = !ConstructorsOnly;
2933 if (SuppressUserConversions && ListInitializing) {
2934 SuppressUserConversions = false;
2935 if (NumArgs == 1) {
2936 // If the first argument is (a reference to) the target type,
2937 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00002938 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2939 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00002940 }
2941 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002942 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002943 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2944 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002945 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002946 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002947 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002948 // Allow one user-defined conversion when user specifies a
2949 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002950 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002951 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002952 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002953 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002954 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002955 }
2956 }
2957
Douglas Gregor5ab11652010-04-17 22:01:05 +00002958 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002959 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002960 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2961 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002962 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002963 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002964 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002965 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002966 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2967 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002968 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002969 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002970 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002971 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002972 DeclAccessPair FoundDecl = I.getPair();
2973 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002974 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2975 if (isa<UsingShadowDecl>(D))
2976 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2977
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002978 CXXConversionDecl *Conv;
2979 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002980 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2981 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002982 else
John McCallda4458e2010-03-31 01:36:47 +00002983 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002984
2985 if (AllowExplicit || !Conv->isExplicit()) {
2986 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002987 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2988 ActingContext, From, ToType,
2989 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002990 else
John McCall5c32be02010-08-24 20:38:10 +00002991 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2992 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002993 }
2994 }
2995 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002996 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002997
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002998 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2999
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003000 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003001 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003002 case OR_Success:
3003 // Record the standard conversion we used and the conversion function.
3004 if (CXXConstructorDecl *Constructor
3005 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003006 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003007
John McCall5c32be02010-08-24 20:38:10 +00003008 // C++ [over.ics.user]p1:
3009 // If the user-defined conversion is specified by a
3010 // constructor (12.3.1), the initial standard conversion
3011 // sequence converts the source type to the type required by
3012 // the argument of the constructor.
3013 //
3014 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003015 if (isa<InitListExpr>(From)) {
3016 // Initializer lists don't have conversions as such.
3017 User.Before.setAsIdentityConversion();
3018 } else {
3019 if (Best->Conversions[0].isEllipsis())
3020 User.EllipsisConversion = true;
3021 else {
3022 User.Before = Best->Conversions[0].Standard;
3023 User.EllipsisConversion = false;
3024 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003025 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003026 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003027 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003028 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003029 User.After.setAsIdentityConversion();
3030 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3031 User.After.setAllToTypes(ToType);
3032 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003033 }
3034 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003035 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003036 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003037
John McCall5c32be02010-08-24 20:38:10 +00003038 // C++ [over.ics.user]p1:
3039 //
3040 // [...] If the user-defined conversion is specified by a
3041 // conversion function (12.3.2), the initial standard
3042 // conversion sequence converts the source type to the
3043 // implicit object parameter of the conversion function.
3044 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003045 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003046 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003047 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003048 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003049
John McCall5c32be02010-08-24 20:38:10 +00003050 // C++ [over.ics.user]p2:
3051 // The second standard conversion sequence converts the
3052 // result of the user-defined conversion to the target type
3053 // for the sequence. Since an implicit conversion sequence
3054 // is an initialization, the special rules for
3055 // initialization by user-defined conversion apply when
3056 // selecting the best user-defined conversion for a
3057 // user-defined conversion sequence (see 13.3.3 and
3058 // 13.3.3.1).
3059 User.After = Best->FinalConversion;
3060 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003061 }
David Blaikie8a40f702012-01-17 06:56:22 +00003062 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003063
John McCall5c32be02010-08-24 20:38:10 +00003064 case OR_No_Viable_Function:
3065 return OR_No_Viable_Function;
3066 case OR_Deleted:
3067 // No conversion here! We're done.
3068 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069
John McCall5c32be02010-08-24 20:38:10 +00003070 case OR_Ambiguous:
3071 return OR_Ambiguous;
3072 }
3073
David Blaikie8a40f702012-01-17 06:56:22 +00003074 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003075}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003077bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003078Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003079 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003080 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003082 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003083 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003084 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003085 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003086 diag::err_typecheck_ambiguous_condition)
3087 << From->getType() << ToType << From->getSourceRange();
3088 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003089 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003090 diag::err_typecheck_nonviable_condition)
3091 << From->getType() << ToType << From->getSourceRange();
3092 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003093 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003094 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003096}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003097
Douglas Gregor2837aa22012-02-22 17:32:19 +00003098/// \brief Compare the user-defined conversion functions or constructors
3099/// of two user-defined conversion sequences to determine whether any ordering
3100/// is possible.
3101static ImplicitConversionSequence::CompareKind
3102compareConversionFunctions(Sema &S,
3103 FunctionDecl *Function1,
3104 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003105 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003106 return ImplicitConversionSequence::Indistinguishable;
3107
3108 // Objective-C++:
3109 // If both conversion functions are implicitly-declared conversions from
3110 // a lambda closure type to a function pointer and a block pointer,
3111 // respectively, always prefer the conversion to a function pointer,
3112 // because the function pointer is more lightweight and is more likely
3113 // to keep code working.
3114 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3115 if (!Conv1)
3116 return ImplicitConversionSequence::Indistinguishable;
3117
3118 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3119 if (!Conv2)
3120 return ImplicitConversionSequence::Indistinguishable;
3121
3122 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3123 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3124 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3125 if (Block1 != Block2)
3126 return Block1? ImplicitConversionSequence::Worse
3127 : ImplicitConversionSequence::Better;
3128 }
3129
3130 return ImplicitConversionSequence::Indistinguishable;
3131}
3132
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003133/// CompareImplicitConversionSequences - Compare two implicit
3134/// conversion sequences to determine whether one is better than the
3135/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003136static ImplicitConversionSequence::CompareKind
3137CompareImplicitConversionSequences(Sema &S,
3138 const ImplicitConversionSequence& ICS1,
3139 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003140{
3141 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3142 // conversion sequences (as defined in 13.3.3.1)
3143 // -- a standard conversion sequence (13.3.3.1.1) is a better
3144 // conversion sequence than a user-defined conversion sequence or
3145 // an ellipsis conversion sequence, and
3146 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3147 // conversion sequence than an ellipsis conversion sequence
3148 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003149 //
John McCall0d1da222010-01-12 00:44:57 +00003150 // C++0x [over.best.ics]p10:
3151 // For the purpose of ranking implicit conversion sequences as
3152 // described in 13.3.3.2, the ambiguous conversion sequence is
3153 // treated as a user-defined sequence that is indistinguishable
3154 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003155 if (ICS1.getKindRank() < ICS2.getKindRank())
3156 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003157 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003158 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003159
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003160 // The following checks require both conversion sequences to be of
3161 // the same kind.
3162 if (ICS1.getKind() != ICS2.getKind())
3163 return ImplicitConversionSequence::Indistinguishable;
3164
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003165 ImplicitConversionSequence::CompareKind Result =
3166 ImplicitConversionSequence::Indistinguishable;
3167
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003168 // Two implicit conversion sequences of the same form are
3169 // indistinguishable conversion sequences unless one of the
3170 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003171 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003172 Result = CompareStandardConversionSequences(S,
3173 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003174 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003175 // User-defined conversion sequence U1 is a better conversion
3176 // sequence than another user-defined conversion sequence U2 if
3177 // they contain the same user-defined conversion function or
3178 // constructor and if the second standard conversion sequence of
3179 // U1 is better than the second standard conversion sequence of
3180 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003181 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003182 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003183 Result = CompareStandardConversionSequences(S,
3184 ICS1.UserDefined.After,
3185 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003186 else
3187 Result = compareConversionFunctions(S,
3188 ICS1.UserDefined.ConversionFunction,
3189 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003190 }
3191
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003192 // List-initialization sequence L1 is a better conversion sequence than
3193 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3194 // for some X and L2 does not.
3195 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003196 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003197 ICS1.isListInitializationSequence() &&
3198 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003199 if (ICS1.isStdInitializerListElement() &&
3200 !ICS2.isStdInitializerListElement())
3201 return ImplicitConversionSequence::Better;
3202 if (!ICS1.isStdInitializerListElement() &&
3203 ICS2.isStdInitializerListElement())
3204 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003205 }
3206
3207 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003208}
3209
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003210static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3211 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3212 Qualifiers Quals;
3213 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003217 return Context.hasSameUnqualifiedType(T1, T2);
3218}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003220// Per 13.3.3.2p3, compare the given standard conversion sequences to
3221// determine if one is a proper subset of the other.
3222static ImplicitConversionSequence::CompareKind
3223compareStandardConversionSubsets(ASTContext &Context,
3224 const StandardConversionSequence& SCS1,
3225 const StandardConversionSequence& SCS2) {
3226 ImplicitConversionSequence::CompareKind Result
3227 = ImplicitConversionSequence::Indistinguishable;
3228
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003230 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003231 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3232 return ImplicitConversionSequence::Better;
3233 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3234 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003236 if (SCS1.Second != SCS2.Second) {
3237 if (SCS1.Second == ICK_Identity)
3238 Result = ImplicitConversionSequence::Better;
3239 else if (SCS2.Second == ICK_Identity)
3240 Result = ImplicitConversionSequence::Worse;
3241 else
3242 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003243 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003244 return ImplicitConversionSequence::Indistinguishable;
3245
3246 if (SCS1.Third == SCS2.Third) {
3247 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3248 : ImplicitConversionSequence::Indistinguishable;
3249 }
3250
3251 if (SCS1.Third == ICK_Identity)
3252 return Result == ImplicitConversionSequence::Worse
3253 ? ImplicitConversionSequence::Indistinguishable
3254 : ImplicitConversionSequence::Better;
3255
3256 if (SCS2.Third == ICK_Identity)
3257 return Result == ImplicitConversionSequence::Better
3258 ? ImplicitConversionSequence::Indistinguishable
3259 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003261 return ImplicitConversionSequence::Indistinguishable;
3262}
3263
Douglas Gregore696ebb2011-01-26 14:52:12 +00003264/// \brief Determine whether one of the given reference bindings is better
3265/// than the other based on what kind of bindings they are.
3266static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3267 const StandardConversionSequence &SCS2) {
3268 // C++0x [over.ics.rank]p3b4:
3269 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3270 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003272 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003274 // reference*.
3275 //
3276 // FIXME: Rvalue references. We're going rogue with the above edits,
3277 // because the semantics in the current C++0x working paper (N3225 at the
3278 // time of this writing) break the standard definition of std::forward
3279 // and std::reference_wrapper when dealing with references to functions.
3280 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003281 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3282 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3283 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284
Douglas Gregore696ebb2011-01-26 14:52:12 +00003285 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3286 SCS2.IsLvalueReference) ||
3287 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3288 !SCS2.IsLvalueReference);
3289}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003291/// CompareStandardConversionSequences - Compare two standard
3292/// conversion sequences to determine whether one is better than the
3293/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003294static ImplicitConversionSequence::CompareKind
3295CompareStandardConversionSequences(Sema &S,
3296 const StandardConversionSequence& SCS1,
3297 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003298{
3299 // Standard conversion sequence S1 is a better conversion sequence
3300 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3301
3302 // -- S1 is a proper subsequence of S2 (comparing the conversion
3303 // sequences in the canonical form defined by 13.3.3.1.1,
3304 // excluding any Lvalue Transformation; the identity conversion
3305 // sequence is considered to be a subsequence of any
3306 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003307 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003308 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003309 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003310
3311 // -- the rank of S1 is better than the rank of S2 (by the rules
3312 // defined below), or, if not that,
3313 ImplicitConversionRank Rank1 = SCS1.getRank();
3314 ImplicitConversionRank Rank2 = SCS2.getRank();
3315 if (Rank1 < Rank2)
3316 return ImplicitConversionSequence::Better;
3317 else if (Rank2 < Rank1)
3318 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003319
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003320 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3321 // are indistinguishable unless one of the following rules
3322 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003324 // A conversion that is not a conversion of a pointer, or
3325 // pointer to member, to bool is better than another conversion
3326 // that is such a conversion.
3327 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3328 return SCS2.isPointerConversionToBool()
3329 ? ImplicitConversionSequence::Better
3330 : ImplicitConversionSequence::Worse;
3331
Douglas Gregor5c407d92008-10-23 00:40:37 +00003332 // C++ [over.ics.rank]p4b2:
3333 //
3334 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003335 // conversion of B* to A* is better than conversion of B* to
3336 // void*, and conversion of A* to void* is better than conversion
3337 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003338 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003339 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003340 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003341 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003342 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3343 // Exactly one of the conversion sequences is a conversion to
3344 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003345 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3346 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003347 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3348 // Neither conversion sequence converts to a void pointer; compare
3349 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003350 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003351 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003352 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003353 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3354 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003355 // Both conversion sequences are conversions to void
3356 // pointers. Compare the source types to determine if there's an
3357 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003358 QualType FromType1 = SCS1.getFromType();
3359 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003360
3361 // Adjust the types we're converting from via the array-to-pointer
3362 // conversion, if we need to.
3363 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003364 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003365 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003366 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003367
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003368 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3369 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003370
John McCall5c32be02010-08-24 20:38:10 +00003371 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003372 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003373 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003374 return ImplicitConversionSequence::Worse;
3375
3376 // Objective-C++: If one interface is more specific than the
3377 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003378 const ObjCObjectPointerType* FromObjCPtr1
3379 = FromType1->getAs<ObjCObjectPointerType>();
3380 const ObjCObjectPointerType* FromObjCPtr2
3381 = FromType2->getAs<ObjCObjectPointerType>();
3382 if (FromObjCPtr1 && FromObjCPtr2) {
3383 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3384 FromObjCPtr2);
3385 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3386 FromObjCPtr1);
3387 if (AssignLeft != AssignRight) {
3388 return AssignLeft? ImplicitConversionSequence::Better
3389 : ImplicitConversionSequence::Worse;
3390 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003391 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003392 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003393
3394 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3395 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003396 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003397 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003398 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003399
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003400 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003401 // Check for a better reference binding based on the kind of bindings.
3402 if (isBetterReferenceBindingKind(SCS1, SCS2))
3403 return ImplicitConversionSequence::Better;
3404 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3405 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406
Sebastian Redlb28b4072009-03-22 23:49:27 +00003407 // C++ [over.ics.rank]p3b4:
3408 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3409 // which the references refer are the same type except for
3410 // top-level cv-qualifiers, and the type to which the reference
3411 // initialized by S2 refers is more cv-qualified than the type
3412 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003413 QualType T1 = SCS1.getToType(2);
3414 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003415 T1 = S.Context.getCanonicalType(T1);
3416 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003417 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003418 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3419 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003420 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003421 // Objective-C++ ARC: If the references refer to objects with different
3422 // lifetimes, prefer bindings that don't change lifetime.
3423 if (SCS1.ObjCLifetimeConversionBinding !=
3424 SCS2.ObjCLifetimeConversionBinding) {
3425 return SCS1.ObjCLifetimeConversionBinding
3426 ? ImplicitConversionSequence::Worse
3427 : ImplicitConversionSequence::Better;
3428 }
3429
Chandler Carruth8e543b32010-12-12 08:17:55 +00003430 // If the type is an array type, promote the element qualifiers to the
3431 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003432 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003433 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003434 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003435 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003436 if (T2.isMoreQualifiedThan(T1))
3437 return ImplicitConversionSequence::Better;
3438 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003439 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003440 }
3441 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003442
Francois Pichet08d2fa02011-09-18 21:37:37 +00003443 // In Microsoft mode, prefer an integral conversion to a
3444 // floating-to-integral conversion if the integral conversion
3445 // is between types of the same size.
3446 // For example:
3447 // void f(float);
3448 // void f(int);
3449 // int main {
3450 // long a;
3451 // f(a);
3452 // }
3453 // Here, MSVC will call f(int) instead of generating a compile error
3454 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003455 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003456 SCS1.Second == ICK_Integral_Conversion &&
3457 SCS2.Second == ICK_Floating_Integral &&
3458 S.Context.getTypeSize(SCS1.getFromType()) ==
3459 S.Context.getTypeSize(SCS1.getToType(2)))
3460 return ImplicitConversionSequence::Better;
3461
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003462 return ImplicitConversionSequence::Indistinguishable;
3463}
3464
3465/// CompareQualificationConversions - Compares two standard conversion
3466/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003467/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3468ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003469CompareQualificationConversions(Sema &S,
3470 const StandardConversionSequence& SCS1,
3471 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003472 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003473 // -- S1 and S2 differ only in their qualification conversion and
3474 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3475 // cv-qualification signature of type T1 is a proper subset of
3476 // the cv-qualification signature of type T2, and S1 is not the
3477 // deprecated string literal array-to-pointer conversion (4.2).
3478 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3479 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3480 return ImplicitConversionSequence::Indistinguishable;
3481
3482 // FIXME: the example in the standard doesn't use a qualification
3483 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003484 QualType T1 = SCS1.getToType(2);
3485 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003486 T1 = S.Context.getCanonicalType(T1);
3487 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003488 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003489 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3490 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003491
3492 // If the types are the same, we won't learn anything by unwrapped
3493 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003494 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003495 return ImplicitConversionSequence::Indistinguishable;
3496
Chandler Carruth607f38e2009-12-29 07:16:59 +00003497 // If the type is an array type, promote the element qualifiers to the type
3498 // for comparison.
3499 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003500 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003501 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003502 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003503
Mike Stump11289f42009-09-09 15:08:12 +00003504 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003505 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003506
3507 // Objective-C++ ARC:
3508 // Prefer qualification conversions not involving a change in lifetime
3509 // to qualification conversions that do not change lifetime.
3510 if (SCS1.QualificationIncludesObjCLifetime !=
3511 SCS2.QualificationIncludesObjCLifetime) {
3512 Result = SCS1.QualificationIncludesObjCLifetime
3513 ? ImplicitConversionSequence::Worse
3514 : ImplicitConversionSequence::Better;
3515 }
3516
John McCall5c32be02010-08-24 20:38:10 +00003517 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003518 // Within each iteration of the loop, we check the qualifiers to
3519 // determine if this still looks like a qualification
3520 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003521 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003522 // until there are no more pointers or pointers-to-members left
3523 // to unwrap. This essentially mimics what
3524 // IsQualificationConversion does, but here we're checking for a
3525 // strict subset of qualifiers.
3526 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3527 // The qualifiers are the same, so this doesn't tell us anything
3528 // about how the sequences rank.
3529 ;
3530 else if (T2.isMoreQualifiedThan(T1)) {
3531 // T1 has fewer qualifiers, so it could be the better sequence.
3532 if (Result == ImplicitConversionSequence::Worse)
3533 // Neither has qualifiers that are a subset of the other's
3534 // qualifiers.
3535 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003536
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003537 Result = ImplicitConversionSequence::Better;
3538 } else if (T1.isMoreQualifiedThan(T2)) {
3539 // T2 has fewer qualifiers, so it could be the better sequence.
3540 if (Result == ImplicitConversionSequence::Better)
3541 // Neither has qualifiers that are a subset of the other's
3542 // qualifiers.
3543 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003544
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003545 Result = ImplicitConversionSequence::Worse;
3546 } else {
3547 // Qualifiers are disjoint.
3548 return ImplicitConversionSequence::Indistinguishable;
3549 }
3550
3551 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003552 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003553 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003554 }
3555
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003556 // Check that the winning standard conversion sequence isn't using
3557 // the deprecated string literal array to pointer conversion.
3558 switch (Result) {
3559 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003560 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003561 Result = ImplicitConversionSequence::Indistinguishable;
3562 break;
3563
3564 case ImplicitConversionSequence::Indistinguishable:
3565 break;
3566
3567 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003568 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003569 Result = ImplicitConversionSequence::Indistinguishable;
3570 break;
3571 }
3572
3573 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003574}
3575
Douglas Gregor5c407d92008-10-23 00:40:37 +00003576/// CompareDerivedToBaseConversions - Compares two standard conversion
3577/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003578/// various kinds of derived-to-base conversions (C++
3579/// [over.ics.rank]p4b3). As part of these checks, we also look at
3580/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003581ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003582CompareDerivedToBaseConversions(Sema &S,
3583 const StandardConversionSequence& SCS1,
3584 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003585 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003586 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003587 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003588 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003589
3590 // Adjust the types we're converting from via the array-to-pointer
3591 // conversion, if we need to.
3592 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003593 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003594 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003595 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003596
3597 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003598 FromType1 = S.Context.getCanonicalType(FromType1);
3599 ToType1 = S.Context.getCanonicalType(ToType1);
3600 FromType2 = S.Context.getCanonicalType(FromType2);
3601 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003602
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003603 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003604 //
3605 // If class B is derived directly or indirectly from class A and
3606 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003607 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003608 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003609 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003610 SCS2.Second == ICK_Pointer_Conversion &&
3611 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3612 FromType1->isPointerType() && FromType2->isPointerType() &&
3613 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003614 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003615 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003616 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003617 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003618 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003619 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003620 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003621 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003622
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003623 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003624 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003625 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003626 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003627 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003628 return ImplicitConversionSequence::Worse;
3629 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003630
3631 // -- conversion of B* to A* is better than conversion of C* to A*,
3632 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003633 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003634 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003635 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003636 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003637 }
3638 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3639 SCS2.Second == ICK_Pointer_Conversion) {
3640 const ObjCObjectPointerType *FromPtr1
3641 = FromType1->getAs<ObjCObjectPointerType>();
3642 const ObjCObjectPointerType *FromPtr2
3643 = FromType2->getAs<ObjCObjectPointerType>();
3644 const ObjCObjectPointerType *ToPtr1
3645 = ToType1->getAs<ObjCObjectPointerType>();
3646 const ObjCObjectPointerType *ToPtr2
3647 = ToType2->getAs<ObjCObjectPointerType>();
3648
3649 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3650 // Apply the same conversion ranking rules for Objective-C pointer types
3651 // that we do for C++ pointers to class types. However, we employ the
3652 // Objective-C pseudo-subtyping relationship used for assignment of
3653 // Objective-C pointer types.
3654 bool FromAssignLeft
3655 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3656 bool FromAssignRight
3657 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3658 bool ToAssignLeft
3659 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3660 bool ToAssignRight
3661 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3662
3663 // A conversion to an a non-id object pointer type or qualified 'id'
3664 // type is better than a conversion to 'id'.
3665 if (ToPtr1->isObjCIdType() &&
3666 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3667 return ImplicitConversionSequence::Worse;
3668 if (ToPtr2->isObjCIdType() &&
3669 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3670 return ImplicitConversionSequence::Better;
3671
3672 // A conversion to a non-id object pointer type is better than a
3673 // conversion to a qualified 'id' type
3674 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3675 return ImplicitConversionSequence::Worse;
3676 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3677 return ImplicitConversionSequence::Better;
3678
3679 // A conversion to an a non-Class object pointer type or qualified 'Class'
3680 // type is better than a conversion to 'Class'.
3681 if (ToPtr1->isObjCClassType() &&
3682 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3683 return ImplicitConversionSequence::Worse;
3684 if (ToPtr2->isObjCClassType() &&
3685 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3686 return ImplicitConversionSequence::Better;
3687
3688 // A conversion to a non-Class object pointer type is better than a
3689 // conversion to a qualified 'Class' type.
3690 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3691 return ImplicitConversionSequence::Worse;
3692 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3693 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003694
Douglas Gregor058d3de2011-01-31 18:51:41 +00003695 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3696 if (S.Context.hasSameType(FromType1, FromType2) &&
3697 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3698 (ToAssignLeft != ToAssignRight))
3699 return ToAssignLeft? ImplicitConversionSequence::Worse
3700 : ImplicitConversionSequence::Better;
3701
3702 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3703 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3704 (FromAssignLeft != FromAssignRight))
3705 return FromAssignLeft? ImplicitConversionSequence::Better
3706 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003707 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003708 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003709
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003710 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003711 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3712 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3713 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003715 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003717 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003719 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003721 ToType2->getAs<MemberPointerType>();
3722 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3723 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3724 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3725 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3726 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3727 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3728 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3729 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003730 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003731 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003732 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003733 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003734 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003735 return ImplicitConversionSequence::Better;
3736 }
3737 // conversion of B::* to C::* is better than conversion of A::* to C::*
3738 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003739 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003740 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003741 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003742 return ImplicitConversionSequence::Worse;
3743 }
3744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor5ab11652010-04-17 22:01:05 +00003746 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003747 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003748 // -- binding of an expression of type C to a reference of type
3749 // B& is better than binding an expression of type C to a
3750 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003751 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3752 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3753 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003754 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003755 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003756 return ImplicitConversionSequence::Worse;
3757 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003758
Douglas Gregor2fe98832008-11-03 19:09:14 +00003759 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003760 // -- binding of an expression of type B to a reference of type
3761 // A& is better than binding an expression of type C to a
3762 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003763 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3764 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3765 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003766 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003767 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003768 return ImplicitConversionSequence::Worse;
3769 }
3770 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003771
Douglas Gregor5c407d92008-10-23 00:40:37 +00003772 return ImplicitConversionSequence::Indistinguishable;
3773}
3774
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003775/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3776/// determine whether they are reference-related,
3777/// reference-compatible, reference-compatible with added
3778/// qualification, or incompatible, for use in C++ initialization by
3779/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3780/// type, and the first type (T1) is the pointee type of the reference
3781/// type being initialized.
3782Sema::ReferenceCompareResult
3783Sema::CompareReferenceRelationship(SourceLocation Loc,
3784 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003785 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003786 bool &ObjCConversion,
3787 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003788 assert(!OrigT1->isReferenceType() &&
3789 "T1 must be the pointee type of the reference type");
3790 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3791
3792 QualType T1 = Context.getCanonicalType(OrigT1);
3793 QualType T2 = Context.getCanonicalType(OrigT2);
3794 Qualifiers T1Quals, T2Quals;
3795 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3796 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3797
3798 // C++ [dcl.init.ref]p4:
3799 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3800 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3801 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003802 DerivedToBase = false;
3803 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003804 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003805 if (UnqualT1 == UnqualT2) {
3806 // Nothing to do.
3807 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003808 IsDerivedFrom(UnqualT2, UnqualT1))
3809 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003810 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3811 UnqualT2->isObjCObjectOrInterfaceType() &&
3812 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3813 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003814 else
3815 return Ref_Incompatible;
3816
3817 // At this point, we know that T1 and T2 are reference-related (at
3818 // least).
3819
3820 // If the type is an array type, promote the element qualifiers to the type
3821 // for comparison.
3822 if (isa<ArrayType>(T1) && T1Quals)
3823 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3824 if (isa<ArrayType>(T2) && T2Quals)
3825 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3826
3827 // C++ [dcl.init.ref]p4:
3828 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3829 // reference-related to T2 and cv1 is the same cv-qualification
3830 // as, or greater cv-qualification than, cv2. For purposes of
3831 // overload resolution, cases for which cv1 is greater
3832 // cv-qualification than cv2 are identified as
3833 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003834 //
3835 // Note that we also require equivalence of Objective-C GC and address-space
3836 // qualifiers when performing these computations, so that e.g., an int in
3837 // address space 1 is not reference-compatible with an int in address
3838 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003839 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3840 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3841 T1Quals.removeObjCLifetime();
3842 T2Quals.removeObjCLifetime();
3843 ObjCLifetimeConversion = true;
3844 }
3845
Douglas Gregord517d552011-04-28 17:56:11 +00003846 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003847 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003848 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003849 return Ref_Compatible_With_Added_Qualification;
3850 else
3851 return Ref_Related;
3852}
3853
Douglas Gregor836a7e82010-08-11 02:15:33 +00003854/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003855/// with DeclType. Return true if something definite is found.
3856static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003857FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3858 QualType DeclType, SourceLocation DeclLoc,
3859 Expr *Init, QualType T2, bool AllowRvalues,
3860 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003861 assert(T2->isRecordType() && "Can only find conversions of record types.");
3862 CXXRecordDecl *T2RecordDecl
3863 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3864
3865 OverloadCandidateSet CandidateSet(DeclLoc);
3866 const UnresolvedSetImpl *Conversions
3867 = T2RecordDecl->getVisibleConversionFunctions();
3868 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3869 E = Conversions->end(); I != E; ++I) {
3870 NamedDecl *D = *I;
3871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3872 if (isa<UsingShadowDecl>(D))
3873 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3874
3875 FunctionTemplateDecl *ConvTemplate
3876 = dyn_cast<FunctionTemplateDecl>(D);
3877 CXXConversionDecl *Conv;
3878 if (ConvTemplate)
3879 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3880 else
3881 Conv = cast<CXXConversionDecl>(D);
3882
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003884 // explicit conversions, skip it.
3885 if (!AllowExplicit && Conv->isExplicit())
3886 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor836a7e82010-08-11 02:15:33 +00003888 if (AllowRvalues) {
3889 bool DerivedToBase = false;
3890 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003891 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003892
3893 // If we are initializing an rvalue reference, don't permit conversion
3894 // functions that return lvalues.
3895 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3896 const ReferenceType *RefType
3897 = Conv->getConversionType()->getAs<LValueReferenceType>();
3898 if (RefType && !RefType->getPointeeType()->isFunctionType())
3899 continue;
3900 }
3901
Douglas Gregor836a7e82010-08-11 02:15:33 +00003902 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003903 S.CompareReferenceRelationship(
3904 DeclLoc,
3905 Conv->getConversionType().getNonReferenceType()
3906 .getUnqualifiedType(),
3907 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003908 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003909 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003910 continue;
3911 } else {
3912 // If the conversion function doesn't return a reference type,
3913 // it can't be considered for this conversion. An rvalue reference
3914 // is only acceptable if its referencee is a function type.
3915
3916 const ReferenceType *RefType =
3917 Conv->getConversionType()->getAs<ReferenceType>();
3918 if (!RefType ||
3919 (!RefType->isLValueReferenceType() &&
3920 !RefType->getPointeeType()->isFunctionType()))
3921 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923
Douglas Gregor836a7e82010-08-11 02:15:33 +00003924 if (ConvTemplate)
3925 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003926 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003927 else
3928 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003929 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003930 }
3931
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003932 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3933
Sebastian Redld92badf2010-06-30 18:13:39 +00003934 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003935 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003936 case OR_Success:
3937 // C++ [over.ics.ref]p1:
3938 //
3939 // [...] If the parameter binds directly to the result of
3940 // applying a conversion function to the argument
3941 // expression, the implicit conversion sequence is a
3942 // user-defined conversion sequence (13.3.3.1.2), with the
3943 // second standard conversion sequence either an identity
3944 // conversion or, if the conversion function returns an
3945 // entity of a type that is a derived class of the parameter
3946 // type, a derived-to-base Conversion.
3947 if (!Best->FinalConversion.DirectBinding)
3948 return false;
3949
Chandler Carruth30141632011-02-25 19:41:05 +00003950 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003951 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003952 ICS.setUserDefined();
3953 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3954 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003955 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003956 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003957 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003958 ICS.UserDefined.EllipsisConversion = false;
3959 assert(ICS.UserDefined.After.ReferenceBinding &&
3960 ICS.UserDefined.After.DirectBinding &&
3961 "Expected a direct reference binding!");
3962 return true;
3963
3964 case OR_Ambiguous:
3965 ICS.setAmbiguous();
3966 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3967 Cand != CandidateSet.end(); ++Cand)
3968 if (Cand->Viable)
3969 ICS.Ambiguous.addConversion(Cand->Function);
3970 return true;
3971
3972 case OR_No_Viable_Function:
3973 case OR_Deleted:
3974 // There was no suitable conversion, or we found a deleted
3975 // conversion; continue with other checks.
3976 return false;
3977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978
David Blaikie8a40f702012-01-17 06:56:22 +00003979 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003980}
3981
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003982/// \brief Compute an implicit conversion sequence for reference
3983/// initialization.
3984static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003985TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003986 SourceLocation DeclLoc,
3987 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003988 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3990
3991 // Most paths end in a failed conversion.
3992 ImplicitConversionSequence ICS;
3993 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3994
3995 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3996 QualType T2 = Init->getType();
3997
3998 // If the initializer is the address of an overloaded function, try
3999 // to resolve the overloaded function. If all goes well, T2 is the
4000 // type of the resulting function.
4001 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4002 DeclAccessPair Found;
4003 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4004 false, Found))
4005 T2 = Fn->getType();
4006 }
4007
4008 // Compute some basic properties of the types and the initializer.
4009 bool isRValRef = DeclType->isRValueReferenceType();
4010 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004011 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004012 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004013 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004014 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004015 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004016 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004017
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004018
Sebastian Redld92badf2010-06-30 18:13:39 +00004019 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004020 // A reference to type "cv1 T1" is initialized by an expression
4021 // of type "cv2 T2" as follows:
4022
Sebastian Redld92badf2010-06-30 18:13:39 +00004023 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004024 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004025 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4026 // reference-compatible with "cv2 T2," or
4027 //
4028 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4029 if (InitCategory.isLValue() &&
4030 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004031 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004032 // When a parameter of reference type binds directly (8.5.3)
4033 // to an argument expression, the implicit conversion sequence
4034 // is the identity conversion, unless the argument expression
4035 // has a type that is a derived class of the parameter type,
4036 // in which case the implicit conversion sequence is a
4037 // derived-to-base Conversion (13.3.3.1).
4038 ICS.setStandard();
4039 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004040 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4041 : ObjCConversion? ICK_Compatible_Conversion
4042 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004043 ICS.Standard.Third = ICK_Identity;
4044 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4045 ICS.Standard.setToType(0, T2);
4046 ICS.Standard.setToType(1, T1);
4047 ICS.Standard.setToType(2, T1);
4048 ICS.Standard.ReferenceBinding = true;
4049 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004050 ICS.Standard.IsLvalueReference = !isRValRef;
4051 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4052 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004053 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004054 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004055 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004056
Sebastian Redld92badf2010-06-30 18:13:39 +00004057 // Nothing more to do: the inaccessibility/ambiguity check for
4058 // derived-to-base conversions is suppressed when we're
4059 // computing the implicit conversion sequence (C++
4060 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004061 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004062 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004063
Sebastian Redld92badf2010-06-30 18:13:39 +00004064 // -- has a class type (i.e., T2 is a class type), where T1 is
4065 // not reference-related to T2, and can be implicitly
4066 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4067 // is reference-compatible with "cv3 T3" 92) (this
4068 // conversion is selected by enumerating the applicable
4069 // conversion functions (13.3.1.6) and choosing the best
4070 // one through overload resolution (13.3)),
4071 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004073 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004074 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4075 Init, T2, /*AllowRvalues=*/false,
4076 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004077 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004078 }
4079 }
4080
Sebastian Redld92badf2010-06-30 18:13:39 +00004081 // -- Otherwise, the reference shall be an lvalue reference to a
4082 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004083 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004085 // We actually handle one oddity of C++ [over.ics.ref] at this
4086 // point, which is that, due to p2 (which short-circuits reference
4087 // binding by only attempting a simple conversion for non-direct
4088 // bindings) and p3's strange wording, we allow a const volatile
4089 // reference to bind to an rvalue. Hence the check for the presence
4090 // of "const" rather than checking for "const" being the only
4091 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004092 // This is also the point where rvalue references and lvalue inits no longer
4093 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004094 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004095 return ICS;
4096
Douglas Gregorf143cd52011-01-24 16:14:37 +00004097 // -- If the initializer expression
4098 //
4099 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004100 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004101 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4102 (InitCategory.isXValue() ||
4103 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4104 (InitCategory.isLValue() && T2->isFunctionType()))) {
4105 ICS.setStandard();
4106 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004108 : ObjCConversion? ICK_Compatible_Conversion
4109 : ICK_Identity;
4110 ICS.Standard.Third = ICK_Identity;
4111 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4112 ICS.Standard.setToType(0, T2);
4113 ICS.Standard.setToType(1, T1);
4114 ICS.Standard.setToType(2, T1);
4115 ICS.Standard.ReferenceBinding = true;
4116 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4117 // binding unless we're binding to a class prvalue.
4118 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4119 // allow the use of rvalue references in C++98/03 for the benefit of
4120 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004122 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004123 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004124 ICS.Standard.IsLvalueReference = !isRValRef;
4125 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004127 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004128 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004129 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132
Douglas Gregorf143cd52011-01-24 16:14:37 +00004133 // -- has a class type (i.e., T2 is a class type), where T1 is not
4134 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 // an xvalue, class prvalue, or function lvalue of type
4136 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004137 // "cv3 T3",
4138 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004140 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004142 // class subobject).
4143 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004145 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4146 Init, T2, /*AllowRvalues=*/true,
4147 AllowExplicit)) {
4148 // In the second case, if the reference is an rvalue reference
4149 // and the second standard conversion sequence of the
4150 // user-defined conversion sequence includes an lvalue-to-rvalue
4151 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004153 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4154 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4155
Douglas Gregor95273c32011-01-21 16:36:05 +00004156 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004159 // -- Otherwise, a temporary of type "cv1 T1" is created and
4160 // initialized from the initializer expression using the
4161 // rules for a non-reference copy initialization (8.5). The
4162 // reference is then bound to the temporary. If T1 is
4163 // reference-related to T2, cv1 must be the same
4164 // cv-qualification as, or greater cv-qualification than,
4165 // cv2; otherwise, the program is ill-formed.
4166 if (RefRelationship == Sema::Ref_Related) {
4167 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4168 // we would be reference-compatible or reference-compatible with
4169 // added qualification. But that wasn't the case, so the reference
4170 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004171 //
4172 // Note that we only want to check address spaces and cvr-qualifiers here.
4173 // ObjC GC and lifetime qualifiers aren't important.
4174 Qualifiers T1Quals = T1.getQualifiers();
4175 Qualifiers T2Quals = T2.getQualifiers();
4176 T1Quals.removeObjCGCAttr();
4177 T1Quals.removeObjCLifetime();
4178 T2Quals.removeObjCGCAttr();
4179 T2Quals.removeObjCLifetime();
4180 if (!T1Quals.compatiblyIncludes(T2Quals))
4181 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004182 }
4183
4184 // If at least one of the types is a class type, the types are not
4185 // related, and we aren't allowed any user conversions, the
4186 // reference binding fails. This case is important for breaking
4187 // recursion, since TryImplicitConversion below will attempt to
4188 // create a temporary through the use of a copy constructor.
4189 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4190 (T1->isRecordType() || T2->isRecordType()))
4191 return ICS;
4192
Douglas Gregorcba72b12011-01-21 05:18:22 +00004193 // If T1 is reference-related to T2 and the reference is an rvalue
4194 // reference, the initializer expression shall not be an lvalue.
4195 if (RefRelationship >= Sema::Ref_Related &&
4196 isRValRef && Init->Classify(S.Context).isLValue())
4197 return ICS;
4198
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004199 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004200 // When a parameter of reference type is not bound directly to
4201 // an argument expression, the conversion sequence is the one
4202 // required to convert the argument expression to the
4203 // underlying type of the reference according to
4204 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4205 // to copy-initializing a temporary of the underlying type with
4206 // the argument expression. Any difference in top-level
4207 // cv-qualification is subsumed by the initialization itself
4208 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004209 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4210 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004211 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004212 /*CStyle=*/false,
4213 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004214
4215 // Of course, that's still a reference binding.
4216 if (ICS.isStandard()) {
4217 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004218 ICS.Standard.IsLvalueReference = !isRValRef;
4219 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4220 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004221 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004222 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004223 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004224 // Don't allow rvalue references to bind to lvalues.
4225 if (DeclType->isRValueReferenceType()) {
4226 if (const ReferenceType *RefType
4227 = ICS.UserDefined.ConversionFunction->getResultType()
4228 ->getAs<LValueReferenceType>()) {
4229 if (!RefType->getPointeeType()->isFunctionType()) {
4230 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4231 DeclType);
4232 return ICS;
4233 }
4234 }
4235 }
4236
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004237 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004238 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4239 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4240 ICS.UserDefined.After.BindsToRvalue = true;
4241 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4242 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004243 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004244
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004245 return ICS;
4246}
4247
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004248static ImplicitConversionSequence
4249TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4250 bool SuppressUserConversions,
4251 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004252 bool AllowObjCWritebackConversion,
4253 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004254
4255/// TryListConversion - Try to copy-initialize a value of type ToType from the
4256/// initializer list From.
4257static ImplicitConversionSequence
4258TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4259 bool SuppressUserConversions,
4260 bool InOverloadResolution,
4261 bool AllowObjCWritebackConversion) {
4262 // C++11 [over.ics.list]p1:
4263 // When an argument is an initializer list, it is not an expression and
4264 // special rules apply for converting it to a parameter type.
4265
4266 ImplicitConversionSequence Result;
4267 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004268 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004269
Sebastian Redl09edce02012-01-23 22:09:39 +00004270 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004271 // initialized from init lists.
4272 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4273 return Result;
4274
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004275 // C++11 [over.ics.list]p2:
4276 // If the parameter type is std::initializer_list<X> or "array of X" and
4277 // all the elements can be implicitly converted to X, the implicit
4278 // conversion sequence is the worst conversion necessary to convert an
4279 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004280 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004281 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004282 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004283 X = S.Context.getBaseElementType(ToType);
4284 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004285 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004286 if (!X.isNull()) {
4287 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4288 Expr *Init = From->getInit(i);
4289 ImplicitConversionSequence ICS =
4290 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4291 InOverloadResolution,
4292 AllowObjCWritebackConversion);
4293 // If a single element isn't convertible, fail.
4294 if (ICS.isBad()) {
4295 Result = ICS;
4296 break;
4297 }
4298 // Otherwise, look for the worst conversion.
4299 if (Result.isBad() ||
4300 CompareImplicitConversionSequences(S, ICS, Result) ==
4301 ImplicitConversionSequence::Worse)
4302 Result = ICS;
4303 }
4304 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004305 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004306 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004307 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004308
4309 // C++11 [over.ics.list]p3:
4310 // Otherwise, if the parameter is a non-aggregate class X and overload
4311 // resolution chooses a single best constructor [...] the implicit
4312 // conversion sequence is a user-defined conversion sequence. If multiple
4313 // constructors are viable but none is better than the others, the
4314 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004315 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4316 // This function can deal with initializer lists.
4317 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4318 /*AllowExplicit=*/false,
4319 InOverloadResolution, /*CStyle=*/false,
4320 AllowObjCWritebackConversion);
4321 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004322 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004323 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004324
4325 // C++11 [over.ics.list]p4:
4326 // Otherwise, if the parameter has an aggregate type which can be
4327 // initialized from the initializer list [...] the implicit conversion
4328 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004329 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004330 // Type is an aggregate, argument is an init list. At this point it comes
4331 // down to checking whether the initialization works.
4332 // FIXME: Find out whether this parameter is consumed or not.
4333 InitializedEntity Entity =
4334 InitializedEntity::InitializeParameter(S.Context, ToType,
4335 /*Consumed=*/false);
4336 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4337 Result.setUserDefined();
4338 Result.UserDefined.Before.setAsIdentityConversion();
4339 // Initializer lists don't have a type.
4340 Result.UserDefined.Before.setFromType(QualType());
4341 Result.UserDefined.Before.setAllToTypes(QualType());
4342
4343 Result.UserDefined.After.setAsIdentityConversion();
4344 Result.UserDefined.After.setFromType(ToType);
4345 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004346 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004347 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004348 return Result;
4349 }
4350
4351 // C++11 [over.ics.list]p5:
4352 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004353 if (ToType->isReferenceType()) {
4354 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4355 // mention initializer lists in any way. So we go by what list-
4356 // initialization would do and try to extrapolate from that.
4357
4358 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4359
4360 // If the initializer list has a single element that is reference-related
4361 // to the parameter type, we initialize the reference from that.
4362 if (From->getNumInits() == 1) {
4363 Expr *Init = From->getInit(0);
4364
4365 QualType T2 = Init->getType();
4366
4367 // If the initializer is the address of an overloaded function, try
4368 // to resolve the overloaded function. If all goes well, T2 is the
4369 // type of the resulting function.
4370 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4371 DeclAccessPair Found;
4372 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4373 Init, ToType, false, Found))
4374 T2 = Fn->getType();
4375 }
4376
4377 // Compute some basic properties of the types and the initializer.
4378 bool dummy1 = false;
4379 bool dummy2 = false;
4380 bool dummy3 = false;
4381 Sema::ReferenceCompareResult RefRelationship
4382 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4383 dummy2, dummy3);
4384
4385 if (RefRelationship >= Sema::Ref_Related)
4386 return TryReferenceInit(S, Init, ToType,
4387 /*FIXME:*/From->getLocStart(),
4388 SuppressUserConversions,
4389 /*AllowExplicit=*/false);
4390 }
4391
4392 // Otherwise, we bind the reference to a temporary created from the
4393 // initializer list.
4394 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4395 InOverloadResolution,
4396 AllowObjCWritebackConversion);
4397 if (Result.isFailure())
4398 return Result;
4399 assert(!Result.isEllipsis() &&
4400 "Sub-initialization cannot result in ellipsis conversion.");
4401
4402 // Can we even bind to a temporary?
4403 if (ToType->isRValueReferenceType() ||
4404 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4405 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4406 Result.UserDefined.After;
4407 SCS.ReferenceBinding = true;
4408 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4409 SCS.BindsToRvalue = true;
4410 SCS.BindsToFunctionLvalue = false;
4411 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4412 SCS.ObjCLifetimeConversionBinding = false;
4413 } else
4414 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4415 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004416 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004417 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004418
4419 // C++11 [over.ics.list]p6:
4420 // Otherwise, if the parameter type is not a class:
4421 if (!ToType->isRecordType()) {
4422 // - if the initializer list has one element, the implicit conversion
4423 // sequence is the one required to convert the element to the
4424 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004425 unsigned NumInits = From->getNumInits();
4426 if (NumInits == 1)
4427 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4428 SuppressUserConversions,
4429 InOverloadResolution,
4430 AllowObjCWritebackConversion);
4431 // - if the initializer list has no elements, the implicit conversion
4432 // sequence is the identity conversion.
4433 else if (NumInits == 0) {
4434 Result.setStandard();
4435 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004436 Result.Standard.setFromType(ToType);
4437 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004438 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004439 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004440 return Result;
4441 }
4442
4443 // C++11 [over.ics.list]p7:
4444 // In all cases other than those enumerated above, no conversion is possible
4445 return Result;
4446}
4447
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004448/// TryCopyInitialization - Try to copy-initialize a value of type
4449/// ToType from the expression From. Return the implicit conversion
4450/// sequence required to pass this argument, which may be a bad
4451/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004452/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004453/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004454static ImplicitConversionSequence
4455TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004457 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004458 bool AllowObjCWritebackConversion,
4459 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004460 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4461 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4462 InOverloadResolution,AllowObjCWritebackConversion);
4463
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004464 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004465 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004466 /*FIXME:*/From->getLocStart(),
4467 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004468 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004469
John McCall5c32be02010-08-24 20:38:10 +00004470 return TryImplicitConversion(S, From, ToType,
4471 SuppressUserConversions,
4472 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004473 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004474 /*CStyle=*/false,
4475 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004476}
4477
Anna Zaks1b068122011-07-28 19:46:48 +00004478static bool TryCopyInitialization(const CanQualType FromQTy,
4479 const CanQualType ToQTy,
4480 Sema &S,
4481 SourceLocation Loc,
4482 ExprValueKind FromVK) {
4483 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4484 ImplicitConversionSequence ICS =
4485 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4486
4487 return !ICS.isBad();
4488}
4489
Douglas Gregor436424c2008-11-18 23:14:02 +00004490/// TryObjectArgumentInitialization - Try to initialize the object
4491/// parameter of the given member function (@c Method) from the
4492/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004493static ImplicitConversionSequence
4494TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004495 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004496 CXXMethodDecl *Method,
4497 CXXRecordDecl *ActingContext) {
4498 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004499 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4500 // const volatile object.
4501 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4502 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004503 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004504
4505 // Set up the conversion sequence as a "bad" conversion, to allow us
4506 // to exit early.
4507 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004508
4509 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004510 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004511 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004512 FromType = PT->getPointeeType();
4513
Douglas Gregor02824322011-01-26 19:30:28 +00004514 // When we had a pointer, it's implicitly dereferenced, so we
4515 // better have an lvalue.
4516 assert(FromClassification.isLValue());
4517 }
4518
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004519 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004520
Douglas Gregor02824322011-01-26 19:30:28 +00004521 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004523 // parameter is
4524 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004525 // - "lvalue reference to cv X" for functions declared without a
4526 // ref-qualifier or with the & ref-qualifier
4527 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004528 // ref-qualifier
4529 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004531 // cv-qualification on the member function declaration.
4532 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004534 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004535 // (C++ [over.match.funcs]p5). We perform a simplified version of
4536 // reference binding here, that allows class rvalues to bind to
4537 // non-constant references.
4538
Douglas Gregor02824322011-01-26 19:30:28 +00004539 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004540 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004542 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004543 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004544 ICS.setBad(BadConversionSequence::bad_qualifiers,
4545 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004546 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004547 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004548
4549 // Check that we have either the same type or a derived type. It
4550 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004551 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004552 ImplicitConversionKind SecondKind;
4553 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4554 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004555 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004556 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004557 else {
John McCall65eb8792010-02-25 01:37:24 +00004558 ICS.setBad(BadConversionSequence::unrelated_class,
4559 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004560 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004561 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004562
Douglas Gregor02824322011-01-26 19:30:28 +00004563 // Check the ref-qualifier.
4564 switch (Method->getRefQualifier()) {
4565 case RQ_None:
4566 // Do nothing; we don't care about lvalueness or rvalueness.
4567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Douglas Gregor02824322011-01-26 19:30:28 +00004569 case RQ_LValue:
4570 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4571 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004573 ImplicitParamType);
4574 return ICS;
4575 }
4576 break;
4577
4578 case RQ_RValue:
4579 if (!FromClassification.isRValue()) {
4580 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004582 ImplicitParamType);
4583 return ICS;
4584 }
4585 break;
4586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587
Douglas Gregor436424c2008-11-18 23:14:02 +00004588 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004589 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004590 ICS.Standard.setAsIdentityConversion();
4591 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004592 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004593 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004594 ICS.Standard.ReferenceBinding = true;
4595 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004597 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004598 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4599 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4600 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004601 return ICS;
4602}
4603
4604/// PerformObjectArgumentInitialization - Perform initialization of
4605/// the implicit object parameter for the given Method with the given
4606/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004607ExprResult
4608Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004610 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004611 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004612 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004613 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004614 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004615
Douglas Gregor02824322011-01-26 19:30:28 +00004616 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004617 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004618 FromRecordType = PT->getPointeeType();
4619 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004620 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004621 } else {
4622 FromRecordType = From->getType();
4623 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004624 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004625 }
4626
John McCall6e9f8f62009-12-03 04:06:58 +00004627 // Note that we always use the true parent context when performing
4628 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004629 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004630 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4631 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004632 if (ICS.isBad()) {
4633 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4634 Qualifiers FromQs = FromRecordType.getQualifiers();
4635 Qualifiers ToQs = DestType.getQualifiers();
4636 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4637 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004638 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004639 diag::err_member_function_call_bad_cvr)
4640 << Method->getDeclName() << FromRecordType << (CVR - 1)
4641 << From->getSourceRange();
4642 Diag(Method->getLocation(), diag::note_previous_decl)
4643 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004644 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004645 }
4646 }
4647
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004648 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004649 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004650 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004651 }
Mike Stump11289f42009-09-09 15:08:12 +00004652
John Wiegley01296292011-04-08 18:41:53 +00004653 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4654 ExprResult FromRes =
4655 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4656 if (FromRes.isInvalid())
4657 return ExprError();
4658 From = FromRes.take();
4659 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004660
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004661 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004662 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004663 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004664 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004665}
4666
Douglas Gregor5fb53972009-01-14 15:45:31 +00004667/// TryContextuallyConvertToBool - Attempt to contextually convert the
4668/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004669static ImplicitConversionSequence
4670TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004671 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004672 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004673 // FIXME: Are these flags correct?
4674 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004675 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004676 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004677 /*CStyle=*/false,
4678 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004679}
4680
4681/// PerformContextuallyConvertToBool - Perform a contextual conversion
4682/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004683ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004684 if (checkPlaceholderForOverload(*this, From))
4685 return ExprError();
4686
John McCall5c32be02010-08-24 20:38:10 +00004687 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004688 if (!ICS.isBad())
4689 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004690
Fariborz Jahanian76197412009-11-18 18:26:29 +00004691 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004692 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004693 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004694 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004695 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697
Richard Smithf8379a02012-01-18 23:55:52 +00004698/// Check that the specified conversion is permitted in a converted constant
4699/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4700/// is acceptable.
4701static bool CheckConvertedConstantConversions(Sema &S,
4702 StandardConversionSequence &SCS) {
4703 // Since we know that the target type is an integral or unscoped enumeration
4704 // type, most conversion kinds are impossible. All possible First and Third
4705 // conversions are fine.
4706 switch (SCS.Second) {
4707 case ICK_Identity:
4708 case ICK_Integral_Promotion:
4709 case ICK_Integral_Conversion:
4710 return true;
4711
4712 case ICK_Boolean_Conversion:
4713 // Conversion from an integral or unscoped enumeration type to bool is
4714 // classified as ICK_Boolean_Conversion, but it's also an integral
4715 // conversion, so it's permitted in a converted constant expression.
4716 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4717 SCS.getToType(2)->isBooleanType();
4718
4719 case ICK_Floating_Integral:
4720 case ICK_Complex_Real:
4721 return false;
4722
4723 case ICK_Lvalue_To_Rvalue:
4724 case ICK_Array_To_Pointer:
4725 case ICK_Function_To_Pointer:
4726 case ICK_NoReturn_Adjustment:
4727 case ICK_Qualification:
4728 case ICK_Compatible_Conversion:
4729 case ICK_Vector_Conversion:
4730 case ICK_Vector_Splat:
4731 case ICK_Derived_To_Base:
4732 case ICK_Pointer_Conversion:
4733 case ICK_Pointer_Member:
4734 case ICK_Block_Pointer_Conversion:
4735 case ICK_Writeback_Conversion:
4736 case ICK_Floating_Promotion:
4737 case ICK_Complex_Promotion:
4738 case ICK_Complex_Conversion:
4739 case ICK_Floating_Conversion:
4740 case ICK_TransparentUnionConversion:
4741 llvm_unreachable("unexpected second conversion kind");
4742
4743 case ICK_Num_Conversion_Kinds:
4744 break;
4745 }
4746
4747 llvm_unreachable("unknown conversion kind");
4748}
4749
4750/// CheckConvertedConstantExpression - Check that the expression From is a
4751/// converted constant expression of type T, perform the conversion and produce
4752/// the converted expression, per C++11 [expr.const]p3.
4753ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4754 llvm::APSInt &Value,
4755 CCEKind CCE) {
4756 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4757 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4758
4759 if (checkPlaceholderForOverload(*this, From))
4760 return ExprError();
4761
4762 // C++11 [expr.const]p3 with proposed wording fixes:
4763 // A converted constant expression of type T is a core constant expression,
4764 // implicitly converted to a prvalue of type T, where the converted
4765 // expression is a literal constant expression and the implicit conversion
4766 // sequence contains only user-defined conversions, lvalue-to-rvalue
4767 // conversions, integral promotions, and integral conversions other than
4768 // narrowing conversions.
4769 ImplicitConversionSequence ICS =
4770 TryImplicitConversion(From, T,
4771 /*SuppressUserConversions=*/false,
4772 /*AllowExplicit=*/false,
4773 /*InOverloadResolution=*/false,
4774 /*CStyle=*/false,
4775 /*AllowObjcWritebackConversion=*/false);
4776 StandardConversionSequence *SCS = 0;
4777 switch (ICS.getKind()) {
4778 case ImplicitConversionSequence::StandardConversion:
4779 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004780 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004781 diag::err_typecheck_converted_constant_expression_disallowed)
4782 << From->getType() << From->getSourceRange() << T;
4783 SCS = &ICS.Standard;
4784 break;
4785 case ImplicitConversionSequence::UserDefinedConversion:
4786 // We are converting from class type to an integral or enumeration type, so
4787 // the Before sequence must be trivial.
4788 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004789 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004790 diag::err_typecheck_converted_constant_expression_disallowed)
4791 << From->getType() << From->getSourceRange() << T;
4792 SCS = &ICS.UserDefined.After;
4793 break;
4794 case ImplicitConversionSequence::AmbiguousConversion:
4795 case ImplicitConversionSequence::BadConversion:
4796 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004797 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004798 diag::err_typecheck_converted_constant_expression)
4799 << From->getType() << From->getSourceRange() << T;
4800 return ExprError();
4801
4802 case ImplicitConversionSequence::EllipsisConversion:
4803 llvm_unreachable("ellipsis conversion in converted constant expression");
4804 }
4805
4806 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4807 if (Result.isInvalid())
4808 return Result;
4809
4810 // Check for a narrowing implicit conversion.
4811 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004812 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004813 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4814 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004815 case NK_Variable_Narrowing:
4816 // Implicit conversion to a narrower type, and the value is not a constant
4817 // expression. We'll diagnose this in a moment.
4818 case NK_Not_Narrowing:
4819 break;
4820
4821 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004822 Diag(From->getLocStart(),
4823 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4824 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004825 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004826 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004827 break;
4828
4829 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004830 Diag(From->getLocStart(),
4831 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4832 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004833 << CCE << /*Constant*/0 << From->getType() << T;
4834 break;
4835 }
4836
4837 // Check the expression is a constant expression.
4838 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4839 Expr::EvalResult Eval;
4840 Eval.Diag = &Notes;
4841
4842 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4843 // The expression can't be folded, so we can't keep it at this position in
4844 // the AST.
4845 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004846 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004847 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004848
4849 if (Notes.empty()) {
4850 // It's a constant expression.
4851 return Result;
4852 }
Richard Smithf8379a02012-01-18 23:55:52 +00004853 }
4854
4855 // It's not a constant expression. Produce an appropriate diagnostic.
4856 if (Notes.size() == 1 &&
4857 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4858 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4859 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004860 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004861 << CCE << From->getSourceRange();
4862 for (unsigned I = 0; I < Notes.size(); ++I)
4863 Diag(Notes[I].first, Notes[I].second);
4864 }
Richard Smith911e1422012-01-30 22:27:01 +00004865 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004866}
4867
John McCallfec112d2011-09-09 06:11:02 +00004868/// dropPointerConversions - If the given standard conversion sequence
4869/// involves any pointer conversions, remove them. This may change
4870/// the result type of the conversion sequence.
4871static void dropPointerConversion(StandardConversionSequence &SCS) {
4872 if (SCS.Second == ICK_Pointer_Conversion) {
4873 SCS.Second = ICK_Identity;
4874 SCS.Third = ICK_Identity;
4875 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4876 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004877}
John McCall5c32be02010-08-24 20:38:10 +00004878
John McCallfec112d2011-09-09 06:11:02 +00004879/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4880/// convert the expression From to an Objective-C pointer type.
4881static ImplicitConversionSequence
4882TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4883 // Do an implicit conversion to 'id'.
4884 QualType Ty = S.Context.getObjCIdType();
4885 ImplicitConversionSequence ICS
4886 = TryImplicitConversion(S, From, Ty,
4887 // FIXME: Are these flags correct?
4888 /*SuppressUserConversions=*/false,
4889 /*AllowExplicit=*/true,
4890 /*InOverloadResolution=*/false,
4891 /*CStyle=*/false,
4892 /*AllowObjCWritebackConversion=*/false);
4893
4894 // Strip off any final conversions to 'id'.
4895 switch (ICS.getKind()) {
4896 case ImplicitConversionSequence::BadConversion:
4897 case ImplicitConversionSequence::AmbiguousConversion:
4898 case ImplicitConversionSequence::EllipsisConversion:
4899 break;
4900
4901 case ImplicitConversionSequence::UserDefinedConversion:
4902 dropPointerConversion(ICS.UserDefined.After);
4903 break;
4904
4905 case ImplicitConversionSequence::StandardConversion:
4906 dropPointerConversion(ICS.Standard);
4907 break;
4908 }
4909
4910 return ICS;
4911}
4912
4913/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4914/// conversion of the expression From to an Objective-C pointer type.
4915ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004916 if (checkPlaceholderForOverload(*this, From))
4917 return ExprError();
4918
John McCall8b07ec22010-05-15 11:32:37 +00004919 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004920 ImplicitConversionSequence ICS =
4921 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004922 if (!ICS.isBad())
4923 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004924 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004925}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004926
Richard Smith8dd34252012-02-04 07:07:42 +00004927/// Determine whether the provided type is an integral type, or an enumeration
4928/// type of a permitted flavor.
4929static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4930 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4931 : T->isIntegralOrUnscopedEnumerationType();
4932}
4933
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004935/// enumeration type.
4936///
4937/// This routine will attempt to convert an expression of class type to an
4938/// integral or enumeration type, if that class type only has a single
4939/// conversion to an integral or enumeration type.
4940///
Douglas Gregor4799d032010-06-30 00:20:43 +00004941/// \param Loc The source location of the construct that requires the
4942/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004943///
Douglas Gregor4799d032010-06-30 00:20:43 +00004944/// \param FromE The expression we're converting from.
4945///
4946/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4947/// have integral or enumeration type.
4948///
4949/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4950/// incomplete class type.
4951///
4952/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4953/// explicit conversion function (because no implicit conversion functions
4954/// were available). This is a recovery mode.
4955///
4956/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4957/// showing which conversion was picked.
4958///
4959/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4960/// conversion function that could convert to integral or enumeration type.
4961///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004963/// usable conversion function.
4964///
4965/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4966/// function, which may be an extension in this case.
4967///
Richard Smith8dd34252012-02-04 07:07:42 +00004968/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4969/// enumerations should be considered.
4970///
Douglas Gregor4799d032010-06-30 00:20:43 +00004971/// \returns The expression, converted to an integral or enumeration type if
4972/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973ExprResult
John McCallb268a282010-08-23 23:25:46 +00004974Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004975 const PartialDiagnostic &NotIntDiag,
4976 const PartialDiagnostic &IncompleteDiag,
4977 const PartialDiagnostic &ExplicitConvDiag,
4978 const PartialDiagnostic &ExplicitConvNote,
4979 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004980 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004981 const PartialDiagnostic &ConvDiag,
4982 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004983 // We can't perform any more checking for type-dependent expressions.
4984 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004985 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
Eli Friedman1da70392012-01-26 00:26:18 +00004987 // Process placeholders immediately.
4988 if (From->hasPlaceholderType()) {
4989 ExprResult result = CheckPlaceholderExpr(From);
4990 if (result.isInvalid()) return result;
4991 From = result.take();
4992 }
4993
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004994 // If the expression already has integral or enumeration type, we're golden.
4995 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00004996 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00004997 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004998
4999 // FIXME: Check for missing '()' if T is a function type?
5000
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001 // 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 +00005002 // expression of integral or enumeration type.
5003 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005004 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00005005 if (NotIntDiag.getDiagID())
5006 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005007 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005010 // We must have a complete class type.
5011 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00005012 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005014 // Look for a conversion to an integral or enumeration type.
5015 UnresolvedSet<4> ViableConversions;
5016 UnresolvedSet<4> ExplicitConversions;
5017 const UnresolvedSetImpl *Conversions
5018 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005020 bool HadMultipleCandidates = (Conversions->size() > 1);
5021
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005022 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 E = Conversions->end();
5024 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005025 ++I) {
5026 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005027 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5028 if (isIntegralOrEnumerationType(
5029 Conversion->getConversionType().getNonReferenceType(),
5030 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005031 if (Conversion->isExplicit())
5032 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5033 else
5034 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5035 }
Richard Smith8dd34252012-02-04 07:07:42 +00005036 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005039 switch (ViableConversions.size()) {
5040 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005041 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005042 DeclAccessPair Found = ExplicitConversions[0];
5043 CXXConversionDecl *Conversion
5044 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005046 // The user probably meant to invoke the given explicit
5047 // conversion; use it.
5048 QualType ConvTy
5049 = Conversion->getConversionType().getNonReferenceType();
5050 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005051 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005053 Diag(Loc, ExplicitConvDiag)
5054 << T << ConvTy
5055 << FixItHint::CreateInsertion(From->getLocStart(),
5056 "static_cast<" + TypeStr + ">(")
5057 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5058 ")");
5059 Diag(Conversion->getLocation(), ExplicitConvNote)
5060 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
5062 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 // explicit conversion function.
5064 if (isSFINAEContext())
5065 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005067 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005068 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5069 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005070 if (Result.isInvalid())
5071 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005072 // Record usage of conversion in an implicit cast.
5073 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5074 CK_UserDefinedConversion,
5075 Result.get(), 0,
5076 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005079 // We'll complain below about a non-integral condition type.
5080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005082 case 1: {
5083 // Apply this conversion.
5084 DeclAccessPair Found = ViableConversions[0];
5085 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Douglas Gregor4799d032010-06-30 00:20:43 +00005087 CXXConversionDecl *Conversion
5088 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5089 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005091 if (ConvDiag.getDiagID()) {
5092 if (isSFINAEContext())
5093 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005094
Douglas Gregor4799d032010-06-30 00:20:43 +00005095 Diag(Loc, ConvDiag)
5096 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005099 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5100 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005101 if (Result.isInvalid())
5102 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005103 // Record usage of conversion in an implicit cast.
5104 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5105 CK_UserDefinedConversion,
5106 Result.get(), 0,
5107 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005108 break;
5109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005111 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005112 if (!AmbigDiag.getDiagID())
5113 return Owned(From);
5114
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005115 Diag(Loc, AmbigDiag)
5116 << T << From->getSourceRange();
5117 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5118 CXXConversionDecl *Conv
5119 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5120 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5121 Diag(Conv->getLocation(), AmbigNote)
5122 << ConvTy->isEnumeralType() << ConvTy;
5123 }
John McCallb268a282010-08-23 23:25:46 +00005124 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126
Richard Smithf4c51d92012-02-04 09:53:13 +00005127 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5128 NotIntDiag.getDiagID())
5129 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005130
Eli Friedman1da70392012-01-26 00:26:18 +00005131 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132}
5133
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005134/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005135/// candidate functions, using the given function call arguments. If
5136/// @p SuppressUserConversions, then don't allow user-defined
5137/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005138///
5139/// \para PartialOverloading true if we are performing "partial" overloading
5140/// based on an incomplete set of function arguments. This feature is used by
5141/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005142void
5143Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005144 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005145 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005146 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005147 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005148 bool PartialOverloading,
5149 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005150 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005151 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005152 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005153 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005154 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005155
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005156 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005157 if (!isa<CXXConstructorDecl>(Method)) {
5158 // If we get here, it's because we're calling a member function
5159 // that is named without a member access expression (e.g.,
5160 // "this->f") that was either written explicitly or created
5161 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005162 // function, e.g., X::f(). We use an empty type for the implied
5163 // object argument (C++ [over.call.func]p3), and the acting context
5164 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005165 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005167 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005168 return;
5169 }
5170 // We treat a constructor like a non-member function, since its object
5171 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005172 }
5173
Douglas Gregorff7028a2009-11-13 23:59:09 +00005174 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005175 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005176
Douglas Gregor27381f32009-11-23 12:27:39 +00005177 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005178 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005179
Douglas Gregorffe14e32009-11-14 01:20:54 +00005180 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5181 // C++ [class.copy]p3:
5182 // A member function template is never instantiated to perform the copy
5183 // of a class object to an object of its class type.
5184 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005185 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005186 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005187 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5188 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005189 return;
5190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005192 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005193 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005194 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005195 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005196 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005197 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005198 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005199 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005201 unsigned NumArgsInProto = Proto->getNumArgs();
5202
5203 // (C++ 13.3.2p2): A candidate function having fewer than m
5204 // parameters is viable only if it has an ellipsis in its parameter
5205 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005206 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005207 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005208 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005209 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005210 return;
5211 }
5212
5213 // (C++ 13.3.2p2): A candidate function having more than m parameters
5214 // is viable only if the (m+1)st parameter has a default argument
5215 // (8.3.6). For the purposes of overload resolution, the
5216 // parameter list is truncated on the right, so that there are
5217 // exactly m parameters.
5218 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005219 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005220 // Not enough arguments.
5221 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005222 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005223 return;
5224 }
5225
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005226 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005227 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005228 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5229 if (CheckCUDATarget(Caller, Function)) {
5230 Candidate.Viable = false;
5231 Candidate.FailureKind = ovl_fail_bad_target;
5232 return;
5233 }
5234
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005235 // Determine the implicit conversion sequences for each of the
5236 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005237 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005238 if (ArgIdx < NumArgsInProto) {
5239 // (C++ 13.3.2p3): for F to be a viable function, there shall
5240 // exist for each argument an implicit conversion sequence
5241 // (13.3.3.1) that converts that argument to the corresponding
5242 // parameter of F.
5243 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005244 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005245 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005246 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005247 /*InOverloadResolution=*/true,
5248 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005249 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005250 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005251 if (Candidate.Conversions[ArgIdx].isBad()) {
5252 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005253 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005254 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005255 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005256 } else {
5257 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5258 // argument for which there is no corresponding parameter is
5259 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005260 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005261 }
5262 }
5263}
5264
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005265/// \brief Add all of the function declarations in the given function set to
5266/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005267void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005268 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005269 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005270 bool SuppressUserConversions,
5271 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005272 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005273 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5274 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005275 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005276 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005277 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005278 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005279 Args.slice(1), CandidateSet,
5280 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005281 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005282 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005283 SuppressUserConversions);
5284 } else {
John McCalla0296f72010-03-19 07:35:19 +00005285 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005286 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5287 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005288 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005289 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005290 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005292 Args[0]->Classify(Context), Args.slice(1),
5293 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005294 else
John McCalla0296f72010-03-19 07:35:19 +00005295 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005296 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005297 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005298 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005299 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005300}
5301
John McCallf0f1cf02009-11-17 07:50:12 +00005302/// AddMethodCandidate - Adds a named decl (which is some kind of
5303/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005304void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005305 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005306 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005307 Expr **Args, unsigned NumArgs,
5308 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005309 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005310 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005311 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005312
5313 if (isa<UsingShadowDecl>(Decl))
5314 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005315
John McCallf0f1cf02009-11-17 07:50:12 +00005316 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5317 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5318 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005319 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5320 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005321 ObjectType, ObjectClassification,
5322 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005323 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005324 } else {
John McCalla0296f72010-03-19 07:35:19 +00005325 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005326 ObjectType, ObjectClassification,
5327 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005328 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005329 }
5330}
5331
Douglas Gregor436424c2008-11-18 23:14:02 +00005332/// AddMethodCandidate - Adds the given C++ member function to the set
5333/// of candidate functions, using the given function call arguments
5334/// and the object argument (@c Object). For example, in a call
5335/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5336/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5337/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005338/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005339void
John McCalla0296f72010-03-19 07:35:19 +00005340Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005341 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005342 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005343 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005344 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005345 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005346 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005347 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005348 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005349 assert(!isa<CXXConstructorDecl>(Method) &&
5350 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005351
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005352 if (!CandidateSet.isNewCandidate(Method))
5353 return;
5354
Douglas Gregor27381f32009-11-23 12:27:39 +00005355 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005356 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005357
Douglas Gregor436424c2008-11-18 23:14:02 +00005358 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005359 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005360 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005361 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005362 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005363 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005364 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005365
5366 unsigned NumArgsInProto = Proto->getNumArgs();
5367
5368 // (C++ 13.3.2p2): A candidate function having fewer than m
5369 // parameters is viable only if it has an ellipsis in its parameter
5370 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005371 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005372 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005373 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005374 return;
5375 }
5376
5377 // (C++ 13.3.2p2): A candidate function having more than m parameters
5378 // is viable only if the (m+1)st parameter has a default argument
5379 // (8.3.6). For the purposes of overload resolution, the
5380 // parameter list is truncated on the right, so that there are
5381 // exactly m parameters.
5382 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005383 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005384 // Not enough arguments.
5385 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005386 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005387 return;
5388 }
5389
5390 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005391
John McCall6e9f8f62009-12-03 04:06:58 +00005392 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005393 // The implicit object argument is ignored.
5394 Candidate.IgnoreObjectArgument = true;
5395 else {
5396 // Determine the implicit conversion sequence for the object
5397 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005398 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005399 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5400 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005401 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005402 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005403 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005404 return;
5405 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005406 }
5407
5408 // Determine the implicit conversion sequences for each of the
5409 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005410 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005411 if (ArgIdx < NumArgsInProto) {
5412 // (C++ 13.3.2p3): for F to be a viable function, there shall
5413 // exist for each argument an implicit conversion sequence
5414 // (13.3.3.1) that converts that argument to the corresponding
5415 // parameter of F.
5416 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005417 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005418 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005420 /*InOverloadResolution=*/true,
5421 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005422 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005423 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005424 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005425 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005426 break;
5427 }
5428 } else {
5429 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5430 // argument for which there is no corresponding parameter is
5431 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005432 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005433 }
5434 }
5435}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436
Douglas Gregor97628d62009-08-21 00:16:32 +00005437/// \brief Add a C++ member function template as a candidate to the candidate
5438/// set, using template argument deduction to produce an appropriate member
5439/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005440void
Douglas Gregor97628d62009-08-21 00:16:32 +00005441Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005442 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005443 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005444 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005445 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005446 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005447 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005448 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005449 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005450 if (!CandidateSet.isNewCandidate(MethodTmpl))
5451 return;
5452
Douglas Gregor97628d62009-08-21 00:16:32 +00005453 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005454 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005455 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005456 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005457 // candidate functions in the usual way.113) A given name can refer to one
5458 // or more function templates and also to a set of overloaded non-template
5459 // functions. In such a case, the candidate functions generated from each
5460 // function template are combined with the set of non-template candidate
5461 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005462 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005463 FunctionDecl *Specialization = 0;
5464 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005465 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5466 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005467 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005468 Candidate.FoundDecl = FoundDecl;
5469 Candidate.Function = MethodTmpl->getTemplatedDecl();
5470 Candidate.Viable = false;
5471 Candidate.FailureKind = ovl_fail_bad_deduction;
5472 Candidate.IsSurrogate = false;
5473 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005474 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005476 Info);
5477 return;
5478 }
Mike Stump11289f42009-09-09 15:08:12 +00005479
Douglas Gregor97628d62009-08-21 00:16:32 +00005480 // Add the function template specialization produced by template argument
5481 // deduction as a candidate.
5482 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005483 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005484 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005485 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005486 ActingContext, ObjectType, ObjectClassification, Args,
5487 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005488}
5489
Douglas Gregor05155d82009-08-21 23:19:43 +00005490/// \brief Add a C++ function template specialization as a candidate
5491/// in the candidate set, using template argument deduction to produce
5492/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005493void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005494Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005495 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005496 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005497 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005498 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005499 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005500 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5501 return;
5502
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005503 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005504 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005505 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005506 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005507 // candidate functions in the usual way.113) A given name can refer to one
5508 // or more function templates and also to a set of overloaded non-template
5509 // functions. In such a case, the candidate functions generated from each
5510 // function template are combined with the set of non-template candidate
5511 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005512 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005513 FunctionDecl *Specialization = 0;
5514 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005515 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5516 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005517 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005518 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005519 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5520 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005521 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005522 Candidate.IsSurrogate = false;
5523 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005524 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005526 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005527 return;
5528 }
Mike Stump11289f42009-09-09 15:08:12 +00005529
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005530 // Add the function template specialization produced by template argument
5531 // deduction as a candidate.
5532 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005533 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005534 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005535}
Mike Stump11289f42009-09-09 15:08:12 +00005536
Douglas Gregora1f013e2008-11-07 22:36:19 +00005537/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005538/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005539/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005540/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005541/// (which may or may not be the same type as the type that the
5542/// conversion function produces).
5543void
5544Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005545 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005546 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005547 Expr *From, QualType ToType,
5548 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005549 assert(!Conversion->getDescribedFunctionTemplate() &&
5550 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005551 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005552 if (!CandidateSet.isNewCandidate(Conversion))
5553 return;
5554
Douglas Gregor27381f32009-11-23 12:27:39 +00005555 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005556 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005557
Douglas Gregora1f013e2008-11-07 22:36:19 +00005558 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005559 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005560 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005561 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005562 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005563 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005564 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005565 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005566 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005567 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005568 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005569
Douglas Gregor6affc782010-08-19 15:37:02 +00005570 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005571 // For conversion functions, the function is considered to be a member of
5572 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005573 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005574 //
5575 // Determine the implicit conversion sequence for the implicit
5576 // object parameter.
5577 QualType ImplicitParamType = From->getType();
5578 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5579 ImplicitParamType = FromPtrType->getPointeeType();
5580 CXXRecordDecl *ConversionContext
5581 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005582
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005583 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584 = TryObjectArgumentInitialization(*this, From->getType(),
5585 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005586 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587
John McCall0d1da222010-01-12 00:44:57 +00005588 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005589 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005590 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005591 return;
5592 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005595 // derived to base as such conversions are given Conversion Rank. They only
5596 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5597 QualType FromCanon
5598 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5599 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5600 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5601 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005602 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005603 return;
5604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregora1f013e2008-11-07 22:36:19 +00005606 // To determine what the conversion from the result of calling the
5607 // conversion function to the type we're eventually trying to
5608 // convert to (ToType), we need to synthesize a call to the
5609 // conversion function and attempt copy initialization from it. This
5610 // makes sure that we get the right semantics with respect to
5611 // lvalues/rvalues and the type. Fortunately, we can allocate this
5612 // call on the stack and we don't need its arguments to be
5613 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005614 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005615 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005616 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5617 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005618 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005619 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005620
Richard Smith48d24642011-07-13 22:53:21 +00005621 QualType ConversionType = Conversion->getConversionType();
5622 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005623 Candidate.Viable = false;
5624 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5625 return;
5626 }
5627
Richard Smith48d24642011-07-13 22:53:21 +00005628 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005629
Mike Stump11289f42009-09-09 15:08:12 +00005630 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005631 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5632 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005633 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005634 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005635 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005636 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005637 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005638 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005639 /*InOverloadResolution=*/false,
5640 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005641
John McCall0d1da222010-01-12 00:44:57 +00005642 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005643 case ImplicitConversionSequence::StandardConversion:
5644 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005646 // C++ [over.ics.user]p3:
5647 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005649 // shall have exact match rank.
5650 if (Conversion->getPrimaryTemplate() &&
5651 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5652 Candidate.Viable = false;
5653 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005655
Douglas Gregorcba72b12011-01-21 05:18:22 +00005656 // C++0x [dcl.init.ref]p5:
5657 // In the second case, if the reference is an rvalue reference and
5658 // the second standard conversion sequence of the user-defined
5659 // conversion sequence includes an lvalue-to-rvalue conversion, the
5660 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005662 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5663 Candidate.Viable = false;
5664 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5665 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005666 break;
5667
5668 case ImplicitConversionSequence::BadConversion:
5669 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005670 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005671 break;
5672
5673 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005674 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005675 "Can only end up with a standard conversion sequence or failure");
5676 }
5677}
5678
Douglas Gregor05155d82009-08-21 23:19:43 +00005679/// \brief Adds a conversion function template specialization
5680/// candidate to the overload set, using template argument deduction
5681/// to deduce the template arguments of the conversion function
5682/// template from the type that we are converting to (C++
5683/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005684void
Douglas Gregor05155d82009-08-21 23:19:43 +00005685Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005686 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005687 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005688 Expr *From, QualType ToType,
5689 OverloadCandidateSet &CandidateSet) {
5690 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5691 "Only conversion function templates permitted here");
5692
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005693 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5694 return;
5695
John McCallbc077cf2010-02-08 23:07:23 +00005696 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005697 CXXConversionDecl *Specialization = 0;
5698 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005699 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005700 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005701 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005702 Candidate.FoundDecl = FoundDecl;
5703 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5704 Candidate.Viable = false;
5705 Candidate.FailureKind = ovl_fail_bad_deduction;
5706 Candidate.IsSurrogate = false;
5707 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005708 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005710 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005711 return;
5712 }
Mike Stump11289f42009-09-09 15:08:12 +00005713
Douglas Gregor05155d82009-08-21 23:19:43 +00005714 // Add the conversion function template specialization produced by
5715 // template argument deduction as a candidate.
5716 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005717 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005718 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005719}
5720
Douglas Gregorab7897a2008-11-19 22:57:39 +00005721/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5722/// converts the given @c Object to a function pointer via the
5723/// conversion function @c Conversion, and then attempts to call it
5724/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5725/// the type of function that we'll eventually be calling.
5726void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005727 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005728 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005729 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005730 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005731 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005732 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005733 if (!CandidateSet.isNewCandidate(Conversion))
5734 return;
5735
Douglas Gregor27381f32009-11-23 12:27:39 +00005736 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005737 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005738
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005739 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005740 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005741 Candidate.Function = 0;
5742 Candidate.Surrogate = Conversion;
5743 Candidate.Viable = true;
5744 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005745 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005746 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005747
5748 // Determine the implicit conversion sequence for the implicit
5749 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005750 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005752 Object->Classify(Context),
5753 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005754 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005755 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005756 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005757 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005758 return;
5759 }
5760
5761 // The first conversion is actually a user-defined conversion whose
5762 // first conversion is ObjectInit's standard conversion (which is
5763 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005764 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005765 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005766 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005767 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005768 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005769 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005770 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005771 = Candidate.Conversions[0].UserDefined.Before;
5772 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5773
Mike Stump11289f42009-09-09 15:08:12 +00005774 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005775 unsigned NumArgsInProto = Proto->getNumArgs();
5776
5777 // (C++ 13.3.2p2): A candidate function having fewer than m
5778 // parameters is viable only if it has an ellipsis in its parameter
5779 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005780 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005781 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005782 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005783 return;
5784 }
5785
5786 // Function types don't have any default arguments, so just check if
5787 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005788 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005789 // Not enough arguments.
5790 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005791 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005792 return;
5793 }
5794
5795 // Determine the implicit conversion sequences for each of the
5796 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005797 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005798 if (ArgIdx < NumArgsInProto) {
5799 // (C++ 13.3.2p3): for F to be a viable function, there shall
5800 // exist for each argument an implicit conversion sequence
5801 // (13.3.3.1) that converts that argument to the corresponding
5802 // parameter of F.
5803 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005804 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005805 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005806 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005807 /*InOverloadResolution=*/false,
5808 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005809 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005810 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005811 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005812 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005813 break;
5814 }
5815 } else {
5816 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5817 // argument for which there is no corresponding parameter is
5818 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005819 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005820 }
5821 }
5822}
5823
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005824/// \brief Add overload candidates for overloaded operators that are
5825/// member functions.
5826///
5827/// Add the overloaded operator candidates that are member functions
5828/// for the operator Op that was used in an operator expression such
5829/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5830/// CandidateSet will store the added overload candidates. (C++
5831/// [over.match.oper]).
5832void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5833 SourceLocation OpLoc,
5834 Expr **Args, unsigned NumArgs,
5835 OverloadCandidateSet& CandidateSet,
5836 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5838
5839 // C++ [over.match.oper]p3:
5840 // For a unary operator @ with an operand of a type whose
5841 // cv-unqualified version is T1, and for a binary operator @ with
5842 // a left operand of a type whose cv-unqualified version is T1 and
5843 // a right operand of a type whose cv-unqualified version is T2,
5844 // three sets of candidate functions, designated member
5845 // candidates, non-member candidates and built-in candidates, are
5846 // constructed as follows:
5847 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005848
5849 // -- If T1 is a class type, the set of member candidates is the
5850 // result of the qualified lookup of T1::operator@
5851 // (13.3.1.1.1); otherwise, the set of member candidates is
5852 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005853 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005854 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005855 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005856 return;
Mike Stump11289f42009-09-09 15:08:12 +00005857
John McCall27b18f82009-11-17 02:14:36 +00005858 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5859 LookupQualifiedName(Operators, T1Rec->getDecl());
5860 Operators.suppressDiagnostics();
5861
Mike Stump11289f42009-09-09 15:08:12 +00005862 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005863 OperEnd = Operators.end();
5864 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005865 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005866 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005868 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005869 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005870 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005871}
5872
Douglas Gregora11693b2008-11-12 17:17:38 +00005873/// AddBuiltinCandidate - Add a candidate for a built-in
5874/// operator. ResultTy and ParamTys are the result and parameter types
5875/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005876/// arguments being passed to the candidate. IsAssignmentOperator
5877/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005878/// operator. NumContextualBoolArguments is the number of arguments
5879/// (at the beginning of the argument list) that will be contextually
5880/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005881void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005882 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005883 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005884 bool IsAssignmentOperator,
5885 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005886 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005887 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005888
Douglas Gregora11693b2008-11-12 17:17:38 +00005889 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005890 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005891 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005892 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005893 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005894 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005895 Candidate.BuiltinTypes.ResultTy = ResultTy;
5896 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5897 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5898
5899 // Determine the implicit conversion sequences for each of the
5900 // arguments.
5901 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005902 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005903 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005904 // C++ [over.match.oper]p4:
5905 // For the built-in assignment operators, conversions of the
5906 // left operand are restricted as follows:
5907 // -- no temporaries are introduced to hold the left operand, and
5908 // -- no user-defined conversions are applied to the left
5909 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005910 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005911 //
5912 // We block these conversions by turning off user-defined
5913 // conversions, since that is the only way that initialization of
5914 // a reference to a non-class type can occur from something that
5915 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005916 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005917 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005918 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005919 Candidate.Conversions[ArgIdx]
5920 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005921 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005922 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005923 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005924 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005925 /*InOverloadResolution=*/false,
5926 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005927 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005928 }
John McCall0d1da222010-01-12 00:44:57 +00005929 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005930 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005931 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005932 break;
5933 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005934 }
5935}
5936
5937/// BuiltinCandidateTypeSet - A set of types that will be used for the
5938/// candidate operator functions for built-in operators (C++
5939/// [over.built]). The types are separated into pointer types and
5940/// enumeration types.
5941class BuiltinCandidateTypeSet {
5942 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005943 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005944
5945 /// PointerTypes - The set of pointer types that will be used in the
5946 /// built-in candidates.
5947 TypeSet PointerTypes;
5948
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005949 /// MemberPointerTypes - The set of member pointer types that will be
5950 /// used in the built-in candidates.
5951 TypeSet MemberPointerTypes;
5952
Douglas Gregora11693b2008-11-12 17:17:38 +00005953 /// EnumerationTypes - The set of enumeration types that will be
5954 /// used in the built-in candidates.
5955 TypeSet EnumerationTypes;
5956
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005958 /// candidates.
5959 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005960
5961 /// \brief A flag indicating non-record types are viable candidates
5962 bool HasNonRecordTypes;
5963
5964 /// \brief A flag indicating whether either arithmetic or enumeration types
5965 /// were present in the candidate set.
5966 bool HasArithmeticOrEnumeralTypes;
5967
Douglas Gregor80af3132011-05-21 23:15:46 +00005968 /// \brief A flag indicating whether the nullptr type was present in the
5969 /// candidate set.
5970 bool HasNullPtrType;
5971
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005972 /// Sema - The semantic analysis instance where we are building the
5973 /// candidate type set.
5974 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005975
Douglas Gregora11693b2008-11-12 17:17:38 +00005976 /// Context - The AST context in which we will build the type sets.
5977 ASTContext &Context;
5978
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005979 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5980 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005981 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005982
5983public:
5984 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005985 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005986
Mike Stump11289f42009-09-09 15:08:12 +00005987 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005988 : HasNonRecordTypes(false),
5989 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005990 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005991 SemaRef(SemaRef),
5992 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005994 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005995 SourceLocation Loc,
5996 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005997 bool AllowExplicitConversions,
5998 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005999
6000 /// pointer_begin - First pointer type found;
6001 iterator pointer_begin() { return PointerTypes.begin(); }
6002
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006003 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006004 iterator pointer_end() { return PointerTypes.end(); }
6005
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006006 /// member_pointer_begin - First member pointer type found;
6007 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6008
6009 /// member_pointer_end - Past the last member pointer type found;
6010 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6011
Douglas Gregora11693b2008-11-12 17:17:38 +00006012 /// enumeration_begin - First enumeration type found;
6013 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6014
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006015 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006016 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006017
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006018 iterator vector_begin() { return VectorTypes.begin(); }
6019 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006020
6021 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6022 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006023 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006024};
6025
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006026/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006027/// the set of pointer types along with any more-qualified variants of
6028/// that type. For example, if @p Ty is "int const *", this routine
6029/// will add "int const *", "int const volatile *", "int const
6030/// restrict *", and "int const volatile restrict *" to the set of
6031/// pointer types. Returns true if the add of @p Ty itself succeeded,
6032/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006033///
6034/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006035bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006036BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6037 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006038
Douglas Gregora11693b2008-11-12 17:17:38 +00006039 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006040 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006041 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006042
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006043 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006044 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006045 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006046 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006047 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006048 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006049 buildObjCPtr = true;
6050 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006051 else
David Blaikie83d382b2011-09-23 05:06:16 +00006052 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006053 }
6054 else
6055 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Sebastian Redl4990a632009-11-18 20:39:26 +00006057 // Don't add qualified variants of arrays. For one, they're not allowed
6058 // (the qualifier would sink to the element type), and for another, the
6059 // only overload situation where it matters is subscript or pointer +- int,
6060 // and those shouldn't have qualifier variants anyway.
6061 if (PointeeTy->isArrayType())
6062 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006063 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006064 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006065 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006066 bool hasVolatile = VisibleQuals.hasVolatile();
6067 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006068
John McCall8ccfcb52009-09-24 19:53:00 +00006069 // Iterate through all strict supersets of BaseCVR.
6070 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6071 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006072 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6073 // in the types.
6074 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6075 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006076 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006077 if (!buildObjCPtr)
6078 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6079 else
6080 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006081 }
6082
6083 return true;
6084}
6085
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006086/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6087/// to the set of pointer types along with any more-qualified variants of
6088/// that type. For example, if @p Ty is "int const *", this routine
6089/// will add "int const *", "int const volatile *", "int const
6090/// restrict *", and "int const volatile restrict *" to the set of
6091/// pointer types. Returns true if the add of @p Ty itself succeeded,
6092/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006093///
6094/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006095bool
6096BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6097 QualType Ty) {
6098 // Insert this type.
6099 if (!MemberPointerTypes.insert(Ty))
6100 return false;
6101
John McCall8ccfcb52009-09-24 19:53:00 +00006102 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6103 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006104
John McCall8ccfcb52009-09-24 19:53:00 +00006105 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006106 // Don't add qualified variants of arrays. For one, they're not allowed
6107 // (the qualifier would sink to the element type), and for another, the
6108 // only overload situation where it matters is subscript or pointer +- int,
6109 // and those shouldn't have qualifier variants anyway.
6110 if (PointeeTy->isArrayType())
6111 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006112 const Type *ClassTy = PointerTy->getClass();
6113
6114 // Iterate through all strict supersets of the pointee type's CVR
6115 // qualifiers.
6116 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6117 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6118 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006119
John McCall8ccfcb52009-09-24 19:53:00 +00006120 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006121 MemberPointerTypes.insert(
6122 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006123 }
6124
6125 return true;
6126}
6127
Douglas Gregora11693b2008-11-12 17:17:38 +00006128/// AddTypesConvertedFrom - Add each of the types to which the type @p
6129/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006130/// primarily interested in pointer types and enumeration types. We also
6131/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006132/// AllowUserConversions is true if we should look at the conversion
6133/// functions of a class type, and AllowExplicitConversions if we
6134/// should also include the explicit conversion functions of a class
6135/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006136void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006137BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006138 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006139 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006140 bool AllowExplicitConversions,
6141 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006142 // Only deal with canonical types.
6143 Ty = Context.getCanonicalType(Ty);
6144
6145 // Look through reference types; they aren't part of the type of an
6146 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006147 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006148 Ty = RefTy->getPointeeType();
6149
John McCall33ddac02011-01-19 10:06:00 +00006150 // If we're dealing with an array type, decay to the pointer.
6151 if (Ty->isArrayType())
6152 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6153
6154 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006155 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006156
Chandler Carruth00a38332010-12-13 01:44:01 +00006157 // Flag if we ever add a non-record type.
6158 const RecordType *TyRec = Ty->getAs<RecordType>();
6159 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6160
Chandler Carruth00a38332010-12-13 01:44:01 +00006161 // Flag if we encounter an arithmetic type.
6162 HasArithmeticOrEnumeralTypes =
6163 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6164
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006165 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6166 PointerTypes.insert(Ty);
6167 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006168 // Insert our type, and its more-qualified variants, into the set
6169 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006170 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006171 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006172 } else if (Ty->isMemberPointerType()) {
6173 // Member pointers are far easier, since the pointee can't be converted.
6174 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6175 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006176 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006177 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006178 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006179 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006180 // We treat vector types as arithmetic types in many contexts as an
6181 // extension.
6182 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006183 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006184 } else if (Ty->isNullPtrType()) {
6185 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006186 } else if (AllowUserConversions && TyRec) {
6187 // No conversion functions in incomplete types.
6188 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6189 return;
Mike Stump11289f42009-09-09 15:08:12 +00006190
Chandler Carruth00a38332010-12-13 01:44:01 +00006191 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6192 const UnresolvedSetImpl *Conversions
6193 = ClassDecl->getVisibleConversionFunctions();
6194 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6195 E = Conversions->end(); I != E; ++I) {
6196 NamedDecl *D = I.getDecl();
6197 if (isa<UsingShadowDecl>(D))
6198 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006199
Chandler Carruth00a38332010-12-13 01:44:01 +00006200 // Skip conversion function templates; they don't tell us anything
6201 // about which builtin types we can convert to.
6202 if (isa<FunctionTemplateDecl>(D))
6203 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006204
Chandler Carruth00a38332010-12-13 01:44:01 +00006205 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6206 if (AllowExplicitConversions || !Conv->isExplicit()) {
6207 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6208 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006209 }
6210 }
6211 }
6212}
6213
Douglas Gregor84605ae2009-08-24 13:43:27 +00006214/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6215/// the volatile- and non-volatile-qualified assignment operators for the
6216/// given type to the candidate set.
6217static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6218 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006219 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006220 unsigned NumArgs,
6221 OverloadCandidateSet &CandidateSet) {
6222 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006223
Douglas Gregor84605ae2009-08-24 13:43:27 +00006224 // T& operator=(T&, T)
6225 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6226 ParamTypes[1] = T;
6227 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6228 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006229
Douglas Gregor84605ae2009-08-24 13:43:27 +00006230 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6231 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006232 ParamTypes[0]
6233 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006234 ParamTypes[1] = T;
6235 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006236 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006237 }
6238}
Mike Stump11289f42009-09-09 15:08:12 +00006239
Sebastian Redl1054fae2009-10-25 17:03:50 +00006240/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6241/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006242static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6243 Qualifiers VRQuals;
6244 const RecordType *TyRec;
6245 if (const MemberPointerType *RHSMPType =
6246 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006247 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006248 else
6249 TyRec = ArgExpr->getType()->getAs<RecordType>();
6250 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006251 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006252 VRQuals.addVolatile();
6253 VRQuals.addRestrict();
6254 return VRQuals;
6255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006257 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006258 if (!ClassDecl->hasDefinition())
6259 return VRQuals;
6260
John McCallad371252010-01-20 00:46:10 +00006261 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006262 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263
John McCallad371252010-01-20 00:46:10 +00006264 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006265 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006266 NamedDecl *D = I.getDecl();
6267 if (isa<UsingShadowDecl>(D))
6268 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6269 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006270 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6271 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6272 CanTy = ResTypeRef->getPointeeType();
6273 // Need to go down the pointer/mempointer chain and add qualifiers
6274 // as see them.
6275 bool done = false;
6276 while (!done) {
6277 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6278 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006279 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006280 CanTy->getAs<MemberPointerType>())
6281 CanTy = ResTypeMPtr->getPointeeType();
6282 else
6283 done = true;
6284 if (CanTy.isVolatileQualified())
6285 VRQuals.addVolatile();
6286 if (CanTy.isRestrictQualified())
6287 VRQuals.addRestrict();
6288 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6289 return VRQuals;
6290 }
6291 }
6292 }
6293 return VRQuals;
6294}
John McCall52872982010-11-13 05:51:15 +00006295
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006296namespace {
John McCall52872982010-11-13 05:51:15 +00006297
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006298/// \brief Helper class to manage the addition of builtin operator overload
6299/// candidates. It provides shared state and utility methods used throughout
6300/// the process, as well as a helper method to add each group of builtin
6301/// operator overloads from the standard to a candidate set.
6302class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006303 // Common instance state available to all overload candidate addition methods.
6304 Sema &S;
6305 Expr **Args;
6306 unsigned NumArgs;
6307 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006308 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006309 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006310 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006311
Chandler Carruthc6586e52010-12-12 10:35:00 +00006312 // Define some constants used to index and iterate over the arithemetic types
6313 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006314 // The "promoted arithmetic types" are the arithmetic
6315 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006316 static const unsigned FirstIntegralType = 3;
6317 static const unsigned LastIntegralType = 18;
6318 static const unsigned FirstPromotedIntegralType = 3,
6319 LastPromotedIntegralType = 9;
6320 static const unsigned FirstPromotedArithmeticType = 0,
6321 LastPromotedArithmeticType = 9;
6322 static const unsigned NumArithmeticTypes = 18;
6323
Chandler Carruthc6586e52010-12-12 10:35:00 +00006324 /// \brief Get the canonical type for a given arithmetic type index.
6325 CanQualType getArithmeticType(unsigned index) {
6326 assert(index < NumArithmeticTypes);
6327 static CanQualType ASTContext::* const
6328 ArithmeticTypes[NumArithmeticTypes] = {
6329 // Start of promoted types.
6330 &ASTContext::FloatTy,
6331 &ASTContext::DoubleTy,
6332 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006333
Chandler Carruthc6586e52010-12-12 10:35:00 +00006334 // Start of integral types.
6335 &ASTContext::IntTy,
6336 &ASTContext::LongTy,
6337 &ASTContext::LongLongTy,
6338 &ASTContext::UnsignedIntTy,
6339 &ASTContext::UnsignedLongTy,
6340 &ASTContext::UnsignedLongLongTy,
6341 // End of promoted types.
6342
6343 &ASTContext::BoolTy,
6344 &ASTContext::CharTy,
6345 &ASTContext::WCharTy,
6346 &ASTContext::Char16Ty,
6347 &ASTContext::Char32Ty,
6348 &ASTContext::SignedCharTy,
6349 &ASTContext::ShortTy,
6350 &ASTContext::UnsignedCharTy,
6351 &ASTContext::UnsignedShortTy,
6352 // End of integral types.
6353 // FIXME: What about complex?
6354 };
6355 return S.Context.*ArithmeticTypes[index];
6356 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006357
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006358 /// \brief Gets the canonical type resulting from the usual arithemetic
6359 /// converions for the given arithmetic types.
6360 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6361 // Accelerator table for performing the usual arithmetic conversions.
6362 // The rules are basically:
6363 // - if either is floating-point, use the wider floating-point
6364 // - if same signedness, use the higher rank
6365 // - if same size, use unsigned of the higher rank
6366 // - use the larger type
6367 // These rules, together with the axiom that higher ranks are
6368 // never smaller, are sufficient to precompute all of these results
6369 // *except* when dealing with signed types of higher rank.
6370 // (we could precompute SLL x UI for all known platforms, but it's
6371 // better not to make any assumptions).
6372 enum PromotedType {
6373 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6374 };
6375 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6376 [LastPromotedArithmeticType] = {
6377 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6378 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6379 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6380 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6381 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6382 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6383 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6384 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6385 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6386 };
6387
6388 assert(L < LastPromotedArithmeticType);
6389 assert(R < LastPromotedArithmeticType);
6390 int Idx = ConversionsTable[L][R];
6391
6392 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006393 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006394
6395 // Slow path: we need to compare widths.
6396 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006397 CanQualType LT = getArithmeticType(L),
6398 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006399 unsigned LW = S.Context.getIntWidth(LT),
6400 RW = S.Context.getIntWidth(RT);
6401
6402 // If they're different widths, use the signed type.
6403 if (LW > RW) return LT;
6404 else if (LW < RW) return RT;
6405
6406 // Otherwise, use the unsigned type of the signed type's rank.
6407 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6408 assert(L == SLL || R == SLL);
6409 return S.Context.UnsignedLongLongTy;
6410 }
6411
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006412 /// \brief Helper method to factor out the common pattern of adding overloads
6413 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006414 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6415 bool HasVolatile) {
6416 QualType ParamTypes[2] = {
6417 S.Context.getLValueReferenceType(CandidateTy),
6418 S.Context.IntTy
6419 };
6420
6421 // Non-volatile version.
6422 if (NumArgs == 1)
6423 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6424 else
6425 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6426
6427 // Use a heuristic to reduce number of builtin candidates in the set:
6428 // add volatile version only if there are conversions to a volatile type.
6429 if (HasVolatile) {
6430 ParamTypes[0] =
6431 S.Context.getLValueReferenceType(
6432 S.Context.getVolatileType(CandidateTy));
6433 if (NumArgs == 1)
6434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6435 else
6436 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6437 }
6438 }
6439
6440public:
6441 BuiltinOperatorOverloadBuilder(
6442 Sema &S, Expr **Args, unsigned NumArgs,
6443 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006444 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006445 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006446 OverloadCandidateSet &CandidateSet)
6447 : S(S), Args(Args), NumArgs(NumArgs),
6448 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006449 HasArithmeticOrEnumeralCandidateType(
6450 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006451 CandidateTypes(CandidateTypes),
6452 CandidateSet(CandidateSet) {
6453 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006454 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006455 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006456 assert(getArithmeticType(LastPromotedIntegralType - 1)
6457 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006458 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006459 assert(getArithmeticType(FirstPromotedArithmeticType)
6460 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006461 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006462 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6463 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006464 "Invalid last promoted arithmetic type");
6465 }
6466
6467 // C++ [over.built]p3:
6468 //
6469 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6470 // is either volatile or empty, there exist candidate operator
6471 // functions of the form
6472 //
6473 // VQ T& operator++(VQ T&);
6474 // T operator++(VQ T&, int);
6475 //
6476 // C++ [over.built]p4:
6477 //
6478 // For every pair (T, VQ), where T is an arithmetic type other
6479 // than bool, and VQ is either volatile or empty, there exist
6480 // candidate operator functions of the form
6481 //
6482 // VQ T& operator--(VQ T&);
6483 // T operator--(VQ T&, int);
6484 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006485 if (!HasArithmeticOrEnumeralCandidateType)
6486 return;
6487
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006488 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6489 Arith < NumArithmeticTypes; ++Arith) {
6490 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006491 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006492 VisibleTypeConversionsQuals.hasVolatile());
6493 }
6494 }
6495
6496 // C++ [over.built]p5:
6497 //
6498 // For every pair (T, VQ), where T is a cv-qualified or
6499 // cv-unqualified object type, and VQ is either volatile or
6500 // empty, there exist candidate operator functions of the form
6501 //
6502 // T*VQ& operator++(T*VQ&);
6503 // T*VQ& operator--(T*VQ&);
6504 // T* operator++(T*VQ&, int);
6505 // T* operator--(T*VQ&, int);
6506 void addPlusPlusMinusMinusPointerOverloads() {
6507 for (BuiltinCandidateTypeSet::iterator
6508 Ptr = CandidateTypes[0].pointer_begin(),
6509 PtrEnd = CandidateTypes[0].pointer_end();
6510 Ptr != PtrEnd; ++Ptr) {
6511 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006512 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006513 continue;
6514
6515 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6516 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6517 VisibleTypeConversionsQuals.hasVolatile()));
6518 }
6519 }
6520
6521 // C++ [over.built]p6:
6522 // For every cv-qualified or cv-unqualified object type T, there
6523 // exist candidate operator functions of the form
6524 //
6525 // T& operator*(T*);
6526 //
6527 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006528 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006529 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006530 // T& operator*(T*);
6531 void addUnaryStarPointerOverloads() {
6532 for (BuiltinCandidateTypeSet::iterator
6533 Ptr = CandidateTypes[0].pointer_begin(),
6534 PtrEnd = CandidateTypes[0].pointer_end();
6535 Ptr != PtrEnd; ++Ptr) {
6536 QualType ParamTy = *Ptr;
6537 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006538 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6539 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540
Douglas Gregor02824322011-01-26 19:30:28 +00006541 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6542 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6543 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006545 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6546 &ParamTy, Args, 1, CandidateSet);
6547 }
6548 }
6549
6550 // C++ [over.built]p9:
6551 // For every promoted arithmetic type T, there exist candidate
6552 // operator functions of the form
6553 //
6554 // T operator+(T);
6555 // T operator-(T);
6556 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006557 if (!HasArithmeticOrEnumeralCandidateType)
6558 return;
6559
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006560 for (unsigned Arith = FirstPromotedArithmeticType;
6561 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006562 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006563 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6564 }
6565
6566 // Extension: We also add these operators for vector types.
6567 for (BuiltinCandidateTypeSet::iterator
6568 Vec = CandidateTypes[0].vector_begin(),
6569 VecEnd = CandidateTypes[0].vector_end();
6570 Vec != VecEnd; ++Vec) {
6571 QualType VecTy = *Vec;
6572 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6573 }
6574 }
6575
6576 // C++ [over.built]p8:
6577 // For every type T, there exist candidate operator functions of
6578 // the form
6579 //
6580 // T* operator+(T*);
6581 void addUnaryPlusPointerOverloads() {
6582 for (BuiltinCandidateTypeSet::iterator
6583 Ptr = CandidateTypes[0].pointer_begin(),
6584 PtrEnd = CandidateTypes[0].pointer_end();
6585 Ptr != PtrEnd; ++Ptr) {
6586 QualType ParamTy = *Ptr;
6587 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6588 }
6589 }
6590
6591 // C++ [over.built]p10:
6592 // For every promoted integral type T, there exist candidate
6593 // operator functions of the form
6594 //
6595 // T operator~(T);
6596 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006597 if (!HasArithmeticOrEnumeralCandidateType)
6598 return;
6599
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006600 for (unsigned Int = FirstPromotedIntegralType;
6601 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006602 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006603 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6604 }
6605
6606 // Extension: We also add this operator for vector types.
6607 for (BuiltinCandidateTypeSet::iterator
6608 Vec = CandidateTypes[0].vector_begin(),
6609 VecEnd = CandidateTypes[0].vector_end();
6610 Vec != VecEnd; ++Vec) {
6611 QualType VecTy = *Vec;
6612 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6613 }
6614 }
6615
6616 // C++ [over.match.oper]p16:
6617 // For every pointer to member type T, there exist candidate operator
6618 // functions of the form
6619 //
6620 // bool operator==(T,T);
6621 // bool operator!=(T,T);
6622 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6623 /// Set of (canonical) types that we've already handled.
6624 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6625
6626 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6627 for (BuiltinCandidateTypeSet::iterator
6628 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6629 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6630 MemPtr != MemPtrEnd;
6631 ++MemPtr) {
6632 // Don't add the same builtin candidate twice.
6633 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6634 continue;
6635
6636 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6637 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6638 CandidateSet);
6639 }
6640 }
6641 }
6642
6643 // C++ [over.built]p15:
6644 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006645 // For every T, where T is an enumeration type, a pointer type, or
6646 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006647 //
6648 // bool operator<(T, T);
6649 // bool operator>(T, T);
6650 // bool operator<=(T, T);
6651 // bool operator>=(T, T);
6652 // bool operator==(T, T);
6653 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006654 void addRelationalPointerOrEnumeralOverloads() {
6655 // C++ [over.built]p1:
6656 // If there is a user-written candidate with the same name and parameter
6657 // types as a built-in candidate operator function, the built-in operator
6658 // function is hidden and is not included in the set of candidate
6659 // functions.
6660 //
6661 // The text is actually in a note, but if we don't implement it then we end
6662 // up with ambiguities when the user provides an overloaded operator for
6663 // an enumeration type. Note that only enumeration types have this problem,
6664 // so we track which enumeration types we've seen operators for. Also, the
6665 // only other overloaded operator with enumeration argumenst, operator=,
6666 // cannot be overloaded for enumeration types, so this is the only place
6667 // where we must suppress candidates like this.
6668 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6669 UserDefinedBinaryOperators;
6670
6671 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6672 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6673 CandidateTypes[ArgIdx].enumeration_end()) {
6674 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6675 CEnd = CandidateSet.end();
6676 C != CEnd; ++C) {
6677 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6678 continue;
6679
6680 QualType FirstParamType =
6681 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6682 QualType SecondParamType =
6683 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6684
6685 // Skip if either parameter isn't of enumeral type.
6686 if (!FirstParamType->isEnumeralType() ||
6687 !SecondParamType->isEnumeralType())
6688 continue;
6689
6690 // Add this operator to the set of known user-defined operators.
6691 UserDefinedBinaryOperators.insert(
6692 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6693 S.Context.getCanonicalType(SecondParamType)));
6694 }
6695 }
6696 }
6697
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006698 /// Set of (canonical) types that we've already handled.
6699 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6700
6701 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6702 for (BuiltinCandidateTypeSet::iterator
6703 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6704 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6705 Ptr != PtrEnd; ++Ptr) {
6706 // Don't add the same builtin candidate twice.
6707 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6708 continue;
6709
6710 QualType ParamTypes[2] = { *Ptr, *Ptr };
6711 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6712 CandidateSet);
6713 }
6714 for (BuiltinCandidateTypeSet::iterator
6715 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6716 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6717 Enum != EnumEnd; ++Enum) {
6718 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6719
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006720 // Don't add the same builtin candidate twice, or if a user defined
6721 // candidate exists.
6722 if (!AddedTypes.insert(CanonType) ||
6723 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6724 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006725 continue;
6726
6727 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006728 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6729 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006730 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006731
6732 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6733 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6734 if (AddedTypes.insert(NullPtrTy) &&
6735 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6736 NullPtrTy))) {
6737 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6738 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6739 CandidateSet);
6740 }
6741 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006742 }
6743 }
6744
6745 // C++ [over.built]p13:
6746 //
6747 // For every cv-qualified or cv-unqualified object type T
6748 // there exist candidate operator functions of the form
6749 //
6750 // T* operator+(T*, ptrdiff_t);
6751 // T& operator[](T*, ptrdiff_t); [BELOW]
6752 // T* operator-(T*, ptrdiff_t);
6753 // T* operator+(ptrdiff_t, T*);
6754 // T& operator[](ptrdiff_t, T*); [BELOW]
6755 //
6756 // C++ [over.built]p14:
6757 //
6758 // For every T, where T is a pointer to object type, there
6759 // exist candidate operator functions of the form
6760 //
6761 // ptrdiff_t operator-(T, T);
6762 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6763 /// Set of (canonical) types that we've already handled.
6764 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6765
6766 for (int Arg = 0; Arg < 2; ++Arg) {
6767 QualType AsymetricParamTypes[2] = {
6768 S.Context.getPointerDiffType(),
6769 S.Context.getPointerDiffType(),
6770 };
6771 for (BuiltinCandidateTypeSet::iterator
6772 Ptr = CandidateTypes[Arg].pointer_begin(),
6773 PtrEnd = CandidateTypes[Arg].pointer_end();
6774 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006775 QualType PointeeTy = (*Ptr)->getPointeeType();
6776 if (!PointeeTy->isObjectType())
6777 continue;
6778
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006779 AsymetricParamTypes[Arg] = *Ptr;
6780 if (Arg == 0 || Op == OO_Plus) {
6781 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6782 // T* operator+(ptrdiff_t, T*);
6783 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6784 CandidateSet);
6785 }
6786 if (Op == OO_Minus) {
6787 // ptrdiff_t operator-(T, T);
6788 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6789 continue;
6790
6791 QualType ParamTypes[2] = { *Ptr, *Ptr };
6792 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6793 Args, 2, CandidateSet);
6794 }
6795 }
6796 }
6797 }
6798
6799 // C++ [over.built]p12:
6800 //
6801 // For every pair of promoted arithmetic types L and R, there
6802 // exist candidate operator functions of the form
6803 //
6804 // LR operator*(L, R);
6805 // LR operator/(L, R);
6806 // LR operator+(L, R);
6807 // LR operator-(L, R);
6808 // bool operator<(L, R);
6809 // bool operator>(L, R);
6810 // bool operator<=(L, R);
6811 // bool operator>=(L, R);
6812 // bool operator==(L, R);
6813 // bool operator!=(L, R);
6814 //
6815 // where LR is the result of the usual arithmetic conversions
6816 // between types L and R.
6817 //
6818 // C++ [over.built]p24:
6819 //
6820 // For every pair of promoted arithmetic types L and R, there exist
6821 // candidate operator functions of the form
6822 //
6823 // LR operator?(bool, L, R);
6824 //
6825 // where LR is the result of the usual arithmetic conversions
6826 // between types L and R.
6827 // Our candidates ignore the first parameter.
6828 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006829 if (!HasArithmeticOrEnumeralCandidateType)
6830 return;
6831
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006832 for (unsigned Left = FirstPromotedArithmeticType;
6833 Left < LastPromotedArithmeticType; ++Left) {
6834 for (unsigned Right = FirstPromotedArithmeticType;
6835 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006836 QualType LandR[2] = { getArithmeticType(Left),
6837 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006838 QualType Result =
6839 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006840 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006841 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6842 }
6843 }
6844
6845 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6846 // conditional operator for vector types.
6847 for (BuiltinCandidateTypeSet::iterator
6848 Vec1 = CandidateTypes[0].vector_begin(),
6849 Vec1End = CandidateTypes[0].vector_end();
6850 Vec1 != Vec1End; ++Vec1) {
6851 for (BuiltinCandidateTypeSet::iterator
6852 Vec2 = CandidateTypes[1].vector_begin(),
6853 Vec2End = CandidateTypes[1].vector_end();
6854 Vec2 != Vec2End; ++Vec2) {
6855 QualType LandR[2] = { *Vec1, *Vec2 };
6856 QualType Result = S.Context.BoolTy;
6857 if (!isComparison) {
6858 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6859 Result = *Vec1;
6860 else
6861 Result = *Vec2;
6862 }
6863
6864 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6865 }
6866 }
6867 }
6868
6869 // C++ [over.built]p17:
6870 //
6871 // For every pair of promoted integral types L and R, there
6872 // exist candidate operator functions of the form
6873 //
6874 // LR operator%(L, R);
6875 // LR operator&(L, R);
6876 // LR operator^(L, R);
6877 // LR operator|(L, R);
6878 // L operator<<(L, R);
6879 // L operator>>(L, R);
6880 //
6881 // where LR is the result of the usual arithmetic conversions
6882 // between types L and R.
6883 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006884 if (!HasArithmeticOrEnumeralCandidateType)
6885 return;
6886
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006887 for (unsigned Left = FirstPromotedIntegralType;
6888 Left < LastPromotedIntegralType; ++Left) {
6889 for (unsigned Right = FirstPromotedIntegralType;
6890 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006891 QualType LandR[2] = { getArithmeticType(Left),
6892 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006893 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6894 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006895 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6897 }
6898 }
6899 }
6900
6901 // C++ [over.built]p20:
6902 //
6903 // For every pair (T, VQ), where T is an enumeration or
6904 // pointer to member type and VQ is either volatile or
6905 // empty, there exist candidate operator functions of the form
6906 //
6907 // VQ T& operator=(VQ T&, T);
6908 void addAssignmentMemberPointerOrEnumeralOverloads() {
6909 /// Set of (canonical) types that we've already handled.
6910 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6911
6912 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6913 for (BuiltinCandidateTypeSet::iterator
6914 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6915 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6916 Enum != EnumEnd; ++Enum) {
6917 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6918 continue;
6919
6920 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6921 CandidateSet);
6922 }
6923
6924 for (BuiltinCandidateTypeSet::iterator
6925 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6926 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6927 MemPtr != MemPtrEnd; ++MemPtr) {
6928 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6929 continue;
6930
6931 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6932 CandidateSet);
6933 }
6934 }
6935 }
6936
6937 // C++ [over.built]p19:
6938 //
6939 // For every pair (T, VQ), where T is any type and VQ is either
6940 // volatile or empty, there exist candidate operator functions
6941 // of the form
6942 //
6943 // T*VQ& operator=(T*VQ&, T*);
6944 //
6945 // C++ [over.built]p21:
6946 //
6947 // For every pair (T, VQ), where T is a cv-qualified or
6948 // cv-unqualified object type and VQ is either volatile or
6949 // empty, there exist candidate operator functions of the form
6950 //
6951 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6952 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6953 void addAssignmentPointerOverloads(bool isEqualOp) {
6954 /// Set of (canonical) types that we've already handled.
6955 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6956
6957 for (BuiltinCandidateTypeSet::iterator
6958 Ptr = CandidateTypes[0].pointer_begin(),
6959 PtrEnd = CandidateTypes[0].pointer_end();
6960 Ptr != PtrEnd; ++Ptr) {
6961 // If this is operator=, keep track of the builtin candidates we added.
6962 if (isEqualOp)
6963 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006964 else if (!(*Ptr)->getPointeeType()->isObjectType())
6965 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006966
6967 // non-volatile version
6968 QualType ParamTypes[2] = {
6969 S.Context.getLValueReferenceType(*Ptr),
6970 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6971 };
6972 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6973 /*IsAssigmentOperator=*/ isEqualOp);
6974
6975 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6976 VisibleTypeConversionsQuals.hasVolatile()) {
6977 // volatile version
6978 ParamTypes[0] =
6979 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6981 /*IsAssigmentOperator=*/isEqualOp);
6982 }
6983 }
6984
6985 if (isEqualOp) {
6986 for (BuiltinCandidateTypeSet::iterator
6987 Ptr = CandidateTypes[1].pointer_begin(),
6988 PtrEnd = CandidateTypes[1].pointer_end();
6989 Ptr != PtrEnd; ++Ptr) {
6990 // Make sure we don't add the same candidate twice.
6991 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6992 continue;
6993
Chandler Carruth8e543b32010-12-12 08:17:55 +00006994 QualType ParamTypes[2] = {
6995 S.Context.getLValueReferenceType(*Ptr),
6996 *Ptr,
6997 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006998
6999 // non-volatile version
7000 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7001 /*IsAssigmentOperator=*/true);
7002
7003 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7004 VisibleTypeConversionsQuals.hasVolatile()) {
7005 // volatile version
7006 ParamTypes[0] =
7007 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7009 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007010 }
7011 }
7012 }
7013 }
7014
7015 // C++ [over.built]p18:
7016 //
7017 // For every triple (L, VQ, R), where L is an arithmetic type,
7018 // VQ is either volatile or empty, and R is a promoted
7019 // arithmetic type, there exist candidate operator functions of
7020 // the form
7021 //
7022 // VQ L& operator=(VQ L&, R);
7023 // VQ L& operator*=(VQ L&, R);
7024 // VQ L& operator/=(VQ L&, R);
7025 // VQ L& operator+=(VQ L&, R);
7026 // VQ L& operator-=(VQ L&, R);
7027 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007028 if (!HasArithmeticOrEnumeralCandidateType)
7029 return;
7030
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007031 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7032 for (unsigned Right = FirstPromotedArithmeticType;
7033 Right < LastPromotedArithmeticType; ++Right) {
7034 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007035 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007036
7037 // Add this built-in operator as a candidate (VQ is empty).
7038 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007039 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007040 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7041 /*IsAssigmentOperator=*/isEqualOp);
7042
7043 // Add this built-in operator as a candidate (VQ is 'volatile').
7044 if (VisibleTypeConversionsQuals.hasVolatile()) {
7045 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007046 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007047 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7049 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007050 /*IsAssigmentOperator=*/isEqualOp);
7051 }
7052 }
7053 }
7054
7055 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7056 for (BuiltinCandidateTypeSet::iterator
7057 Vec1 = CandidateTypes[0].vector_begin(),
7058 Vec1End = CandidateTypes[0].vector_end();
7059 Vec1 != Vec1End; ++Vec1) {
7060 for (BuiltinCandidateTypeSet::iterator
7061 Vec2 = CandidateTypes[1].vector_begin(),
7062 Vec2End = CandidateTypes[1].vector_end();
7063 Vec2 != Vec2End; ++Vec2) {
7064 QualType ParamTypes[2];
7065 ParamTypes[1] = *Vec2;
7066 // Add this built-in operator as a candidate (VQ is empty).
7067 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7068 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7069 /*IsAssigmentOperator=*/isEqualOp);
7070
7071 // Add this built-in operator as a candidate (VQ is 'volatile').
7072 if (VisibleTypeConversionsQuals.hasVolatile()) {
7073 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7074 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007075 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7076 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007077 /*IsAssigmentOperator=*/isEqualOp);
7078 }
7079 }
7080 }
7081 }
7082
7083 // C++ [over.built]p22:
7084 //
7085 // For every triple (L, VQ, R), where L is an integral type, VQ
7086 // is either volatile or empty, and R is a promoted integral
7087 // type, there exist candidate operator functions of the form
7088 //
7089 // VQ L& operator%=(VQ L&, R);
7090 // VQ L& operator<<=(VQ L&, R);
7091 // VQ L& operator>>=(VQ L&, R);
7092 // VQ L& operator&=(VQ L&, R);
7093 // VQ L& operator^=(VQ L&, R);
7094 // VQ L& operator|=(VQ L&, R);
7095 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007096 if (!HasArithmeticOrEnumeralCandidateType)
7097 return;
7098
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007099 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7100 for (unsigned Right = FirstPromotedIntegralType;
7101 Right < LastPromotedIntegralType; ++Right) {
7102 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007103 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007104
7105 // Add this built-in operator as a candidate (VQ is empty).
7106 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007107 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7109 if (VisibleTypeConversionsQuals.hasVolatile()) {
7110 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007111 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007112 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7113 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7114 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7115 CandidateSet);
7116 }
7117 }
7118 }
7119 }
7120
7121 // C++ [over.operator]p23:
7122 //
7123 // There also exist candidate operator functions of the form
7124 //
7125 // bool operator!(bool);
7126 // bool operator&&(bool, bool);
7127 // bool operator||(bool, bool);
7128 void addExclaimOverload() {
7129 QualType ParamTy = S.Context.BoolTy;
7130 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7131 /*IsAssignmentOperator=*/false,
7132 /*NumContextualBoolArguments=*/1);
7133 }
7134 void addAmpAmpOrPipePipeOverload() {
7135 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7136 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7137 /*IsAssignmentOperator=*/false,
7138 /*NumContextualBoolArguments=*/2);
7139 }
7140
7141 // C++ [over.built]p13:
7142 //
7143 // For every cv-qualified or cv-unqualified object type T there
7144 // exist candidate operator functions of the form
7145 //
7146 // T* operator+(T*, ptrdiff_t); [ABOVE]
7147 // T& operator[](T*, ptrdiff_t);
7148 // T* operator-(T*, ptrdiff_t); [ABOVE]
7149 // T* operator+(ptrdiff_t, T*); [ABOVE]
7150 // T& operator[](ptrdiff_t, T*);
7151 void addSubscriptOverloads() {
7152 for (BuiltinCandidateTypeSet::iterator
7153 Ptr = CandidateTypes[0].pointer_begin(),
7154 PtrEnd = CandidateTypes[0].pointer_end();
7155 Ptr != PtrEnd; ++Ptr) {
7156 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7157 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007158 if (!PointeeType->isObjectType())
7159 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007160
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7162
7163 // T& operator[](T*, ptrdiff_t)
7164 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7165 }
7166
7167 for (BuiltinCandidateTypeSet::iterator
7168 Ptr = CandidateTypes[1].pointer_begin(),
7169 PtrEnd = CandidateTypes[1].pointer_end();
7170 Ptr != PtrEnd; ++Ptr) {
7171 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7172 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007173 if (!PointeeType->isObjectType())
7174 continue;
7175
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7177
7178 // T& operator[](ptrdiff_t, T*)
7179 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7180 }
7181 }
7182
7183 // C++ [over.built]p11:
7184 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7185 // C1 is the same type as C2 or is a derived class of C2, T is an object
7186 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7187 // there exist candidate operator functions of the form
7188 //
7189 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7190 //
7191 // where CV12 is the union of CV1 and CV2.
7192 void addArrowStarOverloads() {
7193 for (BuiltinCandidateTypeSet::iterator
7194 Ptr = CandidateTypes[0].pointer_begin(),
7195 PtrEnd = CandidateTypes[0].pointer_end();
7196 Ptr != PtrEnd; ++Ptr) {
7197 QualType C1Ty = (*Ptr);
7198 QualType C1;
7199 QualifierCollector Q1;
7200 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7201 if (!isa<RecordType>(C1))
7202 continue;
7203 // heuristic to reduce number of builtin candidates in the set.
7204 // Add volatile/restrict version only if there are conversions to a
7205 // volatile/restrict type.
7206 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7207 continue;
7208 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7209 continue;
7210 for (BuiltinCandidateTypeSet::iterator
7211 MemPtr = CandidateTypes[1].member_pointer_begin(),
7212 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7213 MemPtr != MemPtrEnd; ++MemPtr) {
7214 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7215 QualType C2 = QualType(mptr->getClass(), 0);
7216 C2 = C2.getUnqualifiedType();
7217 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7218 break;
7219 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7220 // build CV12 T&
7221 QualType T = mptr->getPointeeType();
7222 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7223 T.isVolatileQualified())
7224 continue;
7225 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7226 T.isRestrictQualified())
7227 continue;
7228 T = Q1.apply(S.Context, T);
7229 QualType ResultTy = S.Context.getLValueReferenceType(T);
7230 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7231 }
7232 }
7233 }
7234
7235 // Note that we don't consider the first argument, since it has been
7236 // contextually converted to bool long ago. The candidates below are
7237 // therefore added as binary.
7238 //
7239 // C++ [over.built]p25:
7240 // For every type T, where T is a pointer, pointer-to-member, or scoped
7241 // enumeration type, there exist candidate operator functions of the form
7242 //
7243 // T operator?(bool, T, T);
7244 //
7245 void addConditionalOperatorOverloads() {
7246 /// Set of (canonical) types that we've already handled.
7247 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7248
7249 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7250 for (BuiltinCandidateTypeSet::iterator
7251 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7252 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7253 Ptr != PtrEnd; ++Ptr) {
7254 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7255 continue;
7256
7257 QualType ParamTypes[2] = { *Ptr, *Ptr };
7258 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7259 }
7260
7261 for (BuiltinCandidateTypeSet::iterator
7262 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7263 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7264 MemPtr != MemPtrEnd; ++MemPtr) {
7265 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7266 continue;
7267
7268 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7269 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7270 }
7271
David Blaikiebbafb8a2012-03-11 07:00:24 +00007272 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007273 for (BuiltinCandidateTypeSet::iterator
7274 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7275 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7276 Enum != EnumEnd; ++Enum) {
7277 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7278 continue;
7279
7280 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7281 continue;
7282
7283 QualType ParamTypes[2] = { *Enum, *Enum };
7284 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7285 }
7286 }
7287 }
7288 }
7289};
7290
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007291} // end anonymous namespace
7292
7293/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7294/// operator overloads to the candidate set (C++ [over.built]), based
7295/// on the operator @p Op and the arguments given. For example, if the
7296/// operator is a binary '+', this routine might add "int
7297/// operator+(int, int)" to cover integer addition.
7298void
7299Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7300 SourceLocation OpLoc,
7301 Expr **Args, unsigned NumArgs,
7302 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007303 // Find all of the types that the arguments can convert to, but only
7304 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007305 // that make use of these types. Also record whether we encounter non-record
7306 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007307 Qualifiers VisibleTypeConversionsQuals;
7308 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007309 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7310 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007311
7312 bool HasNonRecordCandidateType = false;
7313 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007314 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007315 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7316 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7317 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7318 OpLoc,
7319 true,
7320 (Op == OO_Exclaim ||
7321 Op == OO_AmpAmp ||
7322 Op == OO_PipePipe),
7323 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007324 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7325 CandidateTypes[ArgIdx].hasNonRecordTypes();
7326 HasArithmeticOrEnumeralCandidateType =
7327 HasArithmeticOrEnumeralCandidateType ||
7328 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007329 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007330
Chandler Carruth00a38332010-12-13 01:44:01 +00007331 // Exit early when no non-record types have been added to the candidate set
7332 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007333 //
7334 // We can't exit early for !, ||, or &&, since there we have always have
7335 // 'bool' overloads.
7336 if (!HasNonRecordCandidateType &&
7337 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007338 return;
7339
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007340 // Setup an object to manage the common state for building overloads.
7341 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7342 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007343 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007344 CandidateTypes, CandidateSet);
7345
7346 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007347 switch (Op) {
7348 case OO_None:
7349 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007350 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007351
Chandler Carruth5184de02010-12-12 08:51:33 +00007352 case OO_New:
7353 case OO_Delete:
7354 case OO_Array_New:
7355 case OO_Array_Delete:
7356 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007357 llvm_unreachable(
7358 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007359
7360 case OO_Comma:
7361 case OO_Arrow:
7362 // C++ [over.match.oper]p3:
7363 // -- For the operator ',', the unary operator '&', or the
7364 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007365 break;
7366
7367 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007368 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007369 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007370 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007371
7372 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007373 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007374 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007375 } else {
7376 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7377 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7378 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007379 break;
7380
Chandler Carruth5184de02010-12-12 08:51:33 +00007381 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007382 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007383 OpBuilder.addUnaryStarPointerOverloads();
7384 else
7385 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7386 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007387
Chandler Carruth5184de02010-12-12 08:51:33 +00007388 case OO_Slash:
7389 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007390 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007391
7392 case OO_PlusPlus:
7393 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007394 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7395 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007396 break;
7397
Douglas Gregor84605ae2009-08-24 13:43:27 +00007398 case OO_EqualEqual:
7399 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007400 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007401 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007402
Douglas Gregora11693b2008-11-12 17:17:38 +00007403 case OO_Less:
7404 case OO_Greater:
7405 case OO_LessEqual:
7406 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007407 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007408 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7409 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007410
Douglas Gregora11693b2008-11-12 17:17:38 +00007411 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007412 case OO_Caret:
7413 case OO_Pipe:
7414 case OO_LessLess:
7415 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007417 break;
7418
Chandler Carruth5184de02010-12-12 08:51:33 +00007419 case OO_Amp: // '&' is either unary or binary
7420 if (NumArgs == 1)
7421 // C++ [over.match.oper]p3:
7422 // -- For the operator ',', the unary operator '&', or the
7423 // operator '->', the built-in candidates set is empty.
7424 break;
7425
7426 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7427 break;
7428
7429 case OO_Tilde:
7430 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7431 break;
7432
Douglas Gregora11693b2008-11-12 17:17:38 +00007433 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007434 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007435 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007436
7437 case OO_PlusEqual:
7438 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007439 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007440 // Fall through.
7441
7442 case OO_StarEqual:
7443 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007444 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007445 break;
7446
7447 case OO_PercentEqual:
7448 case OO_LessLessEqual:
7449 case OO_GreaterGreaterEqual:
7450 case OO_AmpEqual:
7451 case OO_CaretEqual:
7452 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007453 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007454 break;
7455
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007456 case OO_Exclaim:
7457 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007458 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007459
Douglas Gregora11693b2008-11-12 17:17:38 +00007460 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 case OO_PipePipe:
7462 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007463 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007464
7465 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007466 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007467 break;
7468
7469 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007471 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007472
7473 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007475 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7476 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007477 }
7478}
7479
Douglas Gregore254f902009-02-04 00:32:51 +00007480/// \brief Add function candidates found via argument-dependent lookup
7481/// to the set of overloading candidates.
7482///
7483/// This routine performs argument-dependent name lookup based on the
7484/// given function name (which may also be an operator name) and adds
7485/// all of the overload candidates found by ADL to the overload
7486/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007487void
Douglas Gregore254f902009-02-04 00:32:51 +00007488Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007489 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007490 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007491 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007492 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007493 bool PartialOverloading,
7494 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007495 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007496
John McCall91f61fc2010-01-26 06:04:06 +00007497 // FIXME: This approach for uniquing ADL results (and removing
7498 // redundant candidates from the set) relies on pointer-equality,
7499 // which means we need to key off the canonical decl. However,
7500 // always going back to the canonical decl might not get us the
7501 // right set of default arguments. What default arguments are
7502 // we supposed to consider on ADL candidates, anyway?
7503
Douglas Gregorcabea402009-09-22 15:41:20 +00007504 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007505 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007506 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007507
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007508 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007509 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7510 CandEnd = CandidateSet.end();
7511 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007512 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007513 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007514 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007515 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007516 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007517
7518 // For each of the ADL candidates we found, add it to the overload
7519 // set.
John McCall8fe68082010-01-26 07:16:45 +00007520 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007521 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007522 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007523 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007524 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007525
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007526 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7527 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007528 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007529 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007530 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007531 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007532 }
Douglas Gregore254f902009-02-04 00:32:51 +00007533}
7534
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007535/// isBetterOverloadCandidate - Determines whether the first overload
7536/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007537bool
John McCall5c32be02010-08-24 20:38:10 +00007538isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007539 const OverloadCandidate &Cand1,
7540 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007541 SourceLocation Loc,
7542 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007543 // Define viable functions to be better candidates than non-viable
7544 // functions.
7545 if (!Cand2.Viable)
7546 return Cand1.Viable;
7547 else if (!Cand1.Viable)
7548 return false;
7549
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007550 // C++ [over.match.best]p1:
7551 //
7552 // -- if F is a static member function, ICS1(F) is defined such
7553 // that ICS1(F) is neither better nor worse than ICS1(G) for
7554 // any function G, and, symmetrically, ICS1(G) is neither
7555 // better nor worse than ICS1(F).
7556 unsigned StartArg = 0;
7557 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7558 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007559
Douglas Gregord3cb3562009-07-07 23:38:56 +00007560 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007561 // A viable function F1 is defined to be a better function than another
7562 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007563 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007564 unsigned NumArgs = Cand1.NumConversions;
7565 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007566 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007567 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007568 switch (CompareImplicitConversionSequences(S,
7569 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007570 Cand2.Conversions[ArgIdx])) {
7571 case ImplicitConversionSequence::Better:
7572 // Cand1 has a better conversion sequence.
7573 HasBetterConversion = true;
7574 break;
7575
7576 case ImplicitConversionSequence::Worse:
7577 // Cand1 can't be better than Cand2.
7578 return false;
7579
7580 case ImplicitConversionSequence::Indistinguishable:
7581 // Do nothing.
7582 break;
7583 }
7584 }
7585
Mike Stump11289f42009-09-09 15:08:12 +00007586 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007587 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007588 if (HasBetterConversion)
7589 return true;
7590
Mike Stump11289f42009-09-09 15:08:12 +00007591 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007592 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007593 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007594 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7595 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007596
7597 // -- F1 and F2 are function template specializations, and the function
7598 // template for F1 is more specialized than the template for F2
7599 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007600 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007601 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007602 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007603 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007604 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7605 Cand2.Function->getPrimaryTemplate(),
7606 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007608 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007609 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007610 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612
Douglas Gregora1f013e2008-11-07 22:36:19 +00007613 // -- the context is an initialization by user-defined conversion
7614 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7615 // from the return type of F1 to the destination type (i.e.,
7616 // the type of the entity being initialized) is a better
7617 // conversion sequence than the standard conversion sequence
7618 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007619 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007620 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007621 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007622 // First check whether we prefer one of the conversion functions over the
7623 // other. This only distinguishes the results in non-standard, extension
7624 // cases such as the conversion from a lambda closure type to a function
7625 // pointer or block.
7626 ImplicitConversionSequence::CompareKind FuncResult
7627 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7628 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7629 return FuncResult;
7630
John McCall5c32be02010-08-24 20:38:10 +00007631 switch (CompareStandardConversionSequences(S,
7632 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007633 Cand2.FinalConversion)) {
7634 case ImplicitConversionSequence::Better:
7635 // Cand1 has a better conversion sequence.
7636 return true;
7637
7638 case ImplicitConversionSequence::Worse:
7639 // Cand1 can't be better than Cand2.
7640 return false;
7641
7642 case ImplicitConversionSequence::Indistinguishable:
7643 // Do nothing
7644 break;
7645 }
7646 }
7647
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007648 return false;
7649}
7650
Mike Stump11289f42009-09-09 15:08:12 +00007651/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007652/// within an overload candidate set.
7653///
7654/// \param CandidateSet the set of candidate functions.
7655///
7656/// \param Loc the location of the function name (or operator symbol) for
7657/// which overload resolution occurs.
7658///
Mike Stump11289f42009-09-09 15:08:12 +00007659/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007660/// function, Best points to the candidate function found.
7661///
7662/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007663OverloadingResult
7664OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007665 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007666 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007667 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007668 Best = end();
7669 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7670 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007671 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007672 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007673 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007674 }
7675
7676 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007677 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007678 return OR_No_Viable_Function;
7679
7680 // Make sure that this function is better than every other viable
7681 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007682 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007683 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007684 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007685 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007686 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007687 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007688 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007689 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007690 }
Mike Stump11289f42009-09-09 15:08:12 +00007691
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007692 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007693 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007694 (Best->Function->isDeleted() ||
7695 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007696 return OR_Deleted;
7697
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007698 return OR_Success;
7699}
7700
John McCall53262c92010-01-12 02:15:36 +00007701namespace {
7702
7703enum OverloadCandidateKind {
7704 oc_function,
7705 oc_method,
7706 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007707 oc_function_template,
7708 oc_method_template,
7709 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007710 oc_implicit_default_constructor,
7711 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007712 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007713 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007714 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007715 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007716};
7717
John McCalle1ac8d12010-01-13 00:25:19 +00007718OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7719 FunctionDecl *Fn,
7720 std::string &Description) {
7721 bool isTemplate = false;
7722
7723 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7724 isTemplate = true;
7725 Description = S.getTemplateArgumentBindingsText(
7726 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7727 }
John McCallfd0b2f82010-01-06 09:43:14 +00007728
7729 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007730 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007731 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007732
Sebastian Redl08905022011-02-05 19:23:19 +00007733 if (Ctor->getInheritedConstructor())
7734 return oc_implicit_inherited_constructor;
7735
Alexis Hunt119c10e2011-05-25 23:16:36 +00007736 if (Ctor->isDefaultConstructor())
7737 return oc_implicit_default_constructor;
7738
7739 if (Ctor->isMoveConstructor())
7740 return oc_implicit_move_constructor;
7741
7742 assert(Ctor->isCopyConstructor() &&
7743 "unexpected sort of implicit constructor");
7744 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007745 }
7746
7747 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7748 // This actually gets spelled 'candidate function' for now, but
7749 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007750 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007751 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007752
Alexis Hunt119c10e2011-05-25 23:16:36 +00007753 if (Meth->isMoveAssignmentOperator())
7754 return oc_implicit_move_assignment;
7755
Douglas Gregor12695102012-02-10 08:36:38 +00007756 if (Meth->isCopyAssignmentOperator())
7757 return oc_implicit_copy_assignment;
7758
7759 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7760 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007761 }
7762
John McCalle1ac8d12010-01-13 00:25:19 +00007763 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007764}
7765
Sebastian Redl08905022011-02-05 19:23:19 +00007766void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7767 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7768 if (!Ctor) return;
7769
7770 Ctor = Ctor->getInheritedConstructor();
7771 if (!Ctor) return;
7772
7773 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7774}
7775
John McCall53262c92010-01-12 02:15:36 +00007776} // end anonymous namespace
7777
7778// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007779void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007780 std::string FnDesc;
7781 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007782 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7783 << (unsigned) K << FnDesc;
7784 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7785 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007786 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007787}
7788
Douglas Gregorb491ed32011-02-19 21:32:49 +00007789//Notes the location of all overload candidates designated through
7790// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007791void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007792 assert(OverloadedExpr->getType() == Context.OverloadTy);
7793
7794 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7795 OverloadExpr *OvlExpr = Ovl.Expression;
7796
7797 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7798 IEnd = OvlExpr->decls_end();
7799 I != IEnd; ++I) {
7800 if (FunctionTemplateDecl *FunTmpl =
7801 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007802 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007803 } else if (FunctionDecl *Fun
7804 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007805 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007806 }
7807 }
7808}
7809
John McCall0d1da222010-01-12 00:44:57 +00007810/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7811/// "lead" diagnostic; it will be given two arguments, the source and
7812/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007813void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7814 Sema &S,
7815 SourceLocation CaretLoc,
7816 const PartialDiagnostic &PDiag) const {
7817 S.Diag(CaretLoc, PDiag)
7818 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007819 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007820 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7821 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007822 }
John McCall12f97bc2010-01-08 04:41:39 +00007823}
7824
John McCall0d1da222010-01-12 00:44:57 +00007825namespace {
7826
John McCall6a61b522010-01-13 09:16:55 +00007827void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7828 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7829 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007830 assert(Cand->Function && "for now, candidate must be a function");
7831 FunctionDecl *Fn = Cand->Function;
7832
7833 // There's a conversion slot for the object argument if this is a
7834 // non-constructor method. Note that 'I' corresponds the
7835 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007836 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007837 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007838 if (I == 0)
7839 isObjectArgument = true;
7840 else
7841 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007842 }
7843
John McCalle1ac8d12010-01-13 00:25:19 +00007844 std::string FnDesc;
7845 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7846
John McCall6a61b522010-01-13 09:16:55 +00007847 Expr *FromExpr = Conv.Bad.FromExpr;
7848 QualType FromTy = Conv.Bad.getFromType();
7849 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007850
John McCallfb7ad0f2010-02-02 02:42:52 +00007851 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007852 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007853 Expr *E = FromExpr->IgnoreParens();
7854 if (isa<UnaryOperator>(E))
7855 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007856 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007857
7858 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7859 << (unsigned) FnKind << FnDesc
7860 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7861 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007862 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007863 return;
7864 }
7865
John McCall6d174642010-01-23 08:10:49 +00007866 // Do some hand-waving analysis to see if the non-viability is due
7867 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007868 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7869 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7870 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7871 CToTy = RT->getPointeeType();
7872 else {
7873 // TODO: detect and diagnose the full richness of const mismatches.
7874 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7875 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7876 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7877 }
7878
7879 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7880 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007881 Qualifiers FromQs = CFromTy.getQualifiers();
7882 Qualifiers ToQs = CToTy.getQualifiers();
7883
7884 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7886 << (unsigned) FnKind << FnDesc
7887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7888 << FromTy
7889 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7890 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007891 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007892 return;
7893 }
7894
John McCall31168b02011-06-15 23:02:42 +00007895 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007896 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007897 << (unsigned) FnKind << FnDesc
7898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7899 << FromTy
7900 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7901 << (unsigned) isObjectArgument << I+1;
7902 MaybeEmitInheritedConstructorNote(S, Fn);
7903 return;
7904 }
7905
Douglas Gregoraec25842011-04-26 23:16:46 +00007906 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7908 << (unsigned) FnKind << FnDesc
7909 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7910 << FromTy
7911 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7912 << (unsigned) isObjectArgument << I+1;
7913 MaybeEmitInheritedConstructorNote(S, Fn);
7914 return;
7915 }
7916
John McCall47000992010-01-14 03:28:57 +00007917 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7918 assert(CVR && "unexpected qualifiers mismatch");
7919
7920 if (isObjectArgument) {
7921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7922 << (unsigned) FnKind << FnDesc
7923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7924 << FromTy << (CVR - 1);
7925 } else {
7926 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7927 << (unsigned) FnKind << FnDesc
7928 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7929 << FromTy << (CVR - 1) << I+1;
7930 }
Sebastian Redl08905022011-02-05 19:23:19 +00007931 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007932 return;
7933 }
7934
Sebastian Redla72462c2011-09-24 17:48:32 +00007935 // Special diagnostic for failure to convert an initializer list, since
7936 // telling the user that it has type void is not useful.
7937 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7939 << (unsigned) FnKind << FnDesc
7940 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7941 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7942 MaybeEmitInheritedConstructorNote(S, Fn);
7943 return;
7944 }
7945
John McCall6d174642010-01-23 08:10:49 +00007946 // Diagnose references or pointers to incomplete types differently,
7947 // since it's far from impossible that the incompleteness triggered
7948 // the failure.
7949 QualType TempFromTy = FromTy.getNonReferenceType();
7950 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7951 TempFromTy = PTy->getPointeeType();
7952 if (TempFromTy->isIncompleteType()) {
7953 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7954 << (unsigned) FnKind << FnDesc
7955 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7956 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007957 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007958 return;
7959 }
7960
Douglas Gregor56f2e342010-06-30 23:01:39 +00007961 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007962 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007963 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7964 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7965 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7966 FromPtrTy->getPointeeType()) &&
7967 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7968 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007970 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007971 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007972 }
7973 } else if (const ObjCObjectPointerType *FromPtrTy
7974 = FromTy->getAs<ObjCObjectPointerType>()) {
7975 if (const ObjCObjectPointerType *ToPtrTy
7976 = ToTy->getAs<ObjCObjectPointerType>())
7977 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7978 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7979 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7980 FromPtrTy->getPointeeType()) &&
7981 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007982 BaseToDerivedConversion = 2;
7983 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7984 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7985 !FromTy->isIncompleteType() &&
7986 !ToRefTy->getPointeeType()->isIncompleteType() &&
7987 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7988 BaseToDerivedConversion = 3;
7989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007990
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007991 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007993 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007994 << (unsigned) FnKind << FnDesc
7995 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007996 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007997 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007998 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007999 return;
8000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008002 if (isa<ObjCObjectPointerType>(CFromTy) &&
8003 isa<PointerType>(CToTy)) {
8004 Qualifiers FromQs = CFromTy.getQualifiers();
8005 Qualifiers ToQs = CToTy.getQualifiers();
8006 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8008 << (unsigned) FnKind << FnDesc
8009 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8010 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8011 MaybeEmitInheritedConstructorNote(S, Fn);
8012 return;
8013 }
8014 }
8015
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008016 // Emit the generic diagnostic and, optionally, add the hints to it.
8017 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8018 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008019 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008020 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8021 << (unsigned) (Cand->Fix.Kind);
8022
8023 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008024 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8025 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008026 FDiag << *HI;
8027 S.Diag(Fn->getLocation(), FDiag);
8028
Sebastian Redl08905022011-02-05 19:23:19 +00008029 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008030}
8031
8032void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8033 unsigned NumFormalArgs) {
8034 // TODO: treat calls to a missing default constructor as a special case
8035
8036 FunctionDecl *Fn = Cand->Function;
8037 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8038
8039 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008040
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008041 // With invalid overloaded operators, it's possible that we think we
8042 // have an arity mismatch when it fact it looks like we have the
8043 // right number of arguments, because only overloaded operators have
8044 // the weird behavior of overloading member and non-member functions.
8045 // Just don't report anything.
8046 if (Fn->isInvalidDecl() &&
8047 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8048 return;
8049
John McCall6a61b522010-01-13 09:16:55 +00008050 // at least / at most / exactly
8051 unsigned mode, modeCount;
8052 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008053 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8054 (Cand->FailureKind == ovl_fail_bad_deduction &&
8055 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008056 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008057 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008058 mode = 0; // "at least"
8059 else
8060 mode = 2; // "exactly"
8061 modeCount = MinParams;
8062 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008063 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8064 (Cand->FailureKind == ovl_fail_bad_deduction &&
8065 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008066 if (MinParams != FnTy->getNumArgs())
8067 mode = 1; // "at most"
8068 else
8069 mode = 2; // "exactly"
8070 modeCount = FnTy->getNumArgs();
8071 }
8072
8073 std::string Description;
8074 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8075
8076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008078 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008079 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008080}
8081
John McCall8b9ed552010-02-01 18:53:26 +00008082/// Diagnose a failed template-argument deduction.
8083void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008084 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008085 FunctionDecl *Fn = Cand->Function; // pattern
8086
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008087 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008088 NamedDecl *ParamD;
8089 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8090 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8091 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008092 switch (Cand->DeductionFailure.Result) {
8093 case Sema::TDK_Success:
8094 llvm_unreachable("TDK_success while diagnosing bad deduction");
8095
8096 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008097 assert(ParamD && "no parameter found for incomplete deduction result");
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8099 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008100 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008101 return;
8102 }
8103
John McCall42d7d192010-08-05 09:05:08 +00008104 case Sema::TDK_Underqualified: {
8105 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8106 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8107
8108 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8109
8110 // Param will have been canonicalized, but it should just be a
8111 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008112 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008113 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008114 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008115 assert(S.Context.hasSameType(Param, NonCanonParam));
8116
8117 // Arg has also been canonicalized, but there's nothing we can do
8118 // about that. It also doesn't matter as much, because it won't
8119 // have any template parameters in it (because deduction isn't
8120 // done on dependent types).
8121 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8122
8123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8124 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008125 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008126 return;
8127 }
8128
8129 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008130 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008131 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008132 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008133 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008134 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008135 which = 1;
8136 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008137 which = 2;
8138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008139
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008142 << *Cand->DeductionFailure.getFirstArg()
8143 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008144 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008145 return;
8146 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008147
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008148 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008149 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008150 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008151 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008152 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8153 << ParamD->getDeclName();
8154 else {
8155 int index = 0;
8156 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8157 index = TTP->getIndex();
8158 else if (NonTypeTemplateParmDecl *NTTP
8159 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8160 index = NTTP->getIndex();
8161 else
8162 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008163 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008164 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8165 << (index + 1);
8166 }
Sebastian Redl08905022011-02-05 19:23:19 +00008167 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008168 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008169
Douglas Gregor02eb4832010-05-08 18:13:28 +00008170 case Sema::TDK_TooManyArguments:
8171 case Sema::TDK_TooFewArguments:
8172 DiagnoseArityMismatch(S, Cand, NumArgs);
8173 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008174
8175 case Sema::TDK_InstantiationDepth:
8176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008177 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008178 return;
8179
8180 case Sema::TDK_SubstitutionFailure: {
8181 std::string ArgString;
8182 if (TemplateArgumentList *Args
8183 = Cand->DeductionFailure.getTemplateArgumentList())
8184 ArgString = S.getTemplateArgumentBindingsText(
8185 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8186 *Args);
8187 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8188 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008189 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008190 return;
8191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008192
John McCall8b9ed552010-02-01 18:53:26 +00008193 // TODO: diagnose these individually, then kill off
8194 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008195 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008196 case Sema::TDK_FailedOverloadResolution:
8197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008198 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008199 return;
8200 }
8201}
8202
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008203/// CUDA: diagnose an invalid call across targets.
8204void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8205 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8206 FunctionDecl *Callee = Cand->Function;
8207
8208 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8209 CalleeTarget = S.IdentifyCUDATarget(Callee);
8210
8211 std::string FnDesc;
8212 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8213
8214 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8215 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8216}
8217
John McCall8b9ed552010-02-01 18:53:26 +00008218/// Generates a 'note' diagnostic for an overload candidate. We've
8219/// already generated a primary error at the call site.
8220///
8221/// It really does need to be a single diagnostic with its caret
8222/// pointed at the candidate declaration. Yes, this creates some
8223/// major challenges of technical writing. Yes, this makes pointing
8224/// out problems with specific arguments quite awkward. It's still
8225/// better than generating twenty screens of text for every failed
8226/// overload.
8227///
8228/// It would be great to be able to express per-candidate problems
8229/// more richly for those diagnostic clients that cared, but we'd
8230/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008231void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008232 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008233 FunctionDecl *Fn = Cand->Function;
8234
John McCall12f97bc2010-01-08 04:41:39 +00008235 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008236 if (Cand->Viable && (Fn->isDeleted() ||
8237 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008238 std::string FnDesc;
8239 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008240
8241 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008242 << FnKind << FnDesc
8243 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008244 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008245 return;
John McCall12f97bc2010-01-08 04:41:39 +00008246 }
8247
John McCalle1ac8d12010-01-13 00:25:19 +00008248 // We don't really have anything else to say about viable candidates.
8249 if (Cand->Viable) {
8250 S.NoteOverloadCandidate(Fn);
8251 return;
8252 }
John McCall0d1da222010-01-12 00:44:57 +00008253
John McCall6a61b522010-01-13 09:16:55 +00008254 switch (Cand->FailureKind) {
8255 case ovl_fail_too_many_arguments:
8256 case ovl_fail_too_few_arguments:
8257 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008258
John McCall6a61b522010-01-13 09:16:55 +00008259 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008260 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008261
John McCallfe796dd2010-01-23 05:17:32 +00008262 case ovl_fail_trivial_conversion:
8263 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008264 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008265 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008266
John McCall65eb8792010-02-25 01:37:24 +00008267 case ovl_fail_bad_conversion: {
8268 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008269 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008270 if (Cand->Conversions[I].isBad())
8271 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008272
John McCall6a61b522010-01-13 09:16:55 +00008273 // FIXME: this currently happens when we're called from SemaInit
8274 // when user-conversion overload fails. Figure out how to handle
8275 // those conditions and diagnose them well.
8276 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008277 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008278
8279 case ovl_fail_bad_target:
8280 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008281 }
John McCalld3224162010-01-08 00:58:21 +00008282}
8283
8284void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8285 // Desugar the type of the surrogate down to a function type,
8286 // retaining as many typedefs as possible while still showing
8287 // the function type (and, therefore, its parameter types).
8288 QualType FnType = Cand->Surrogate->getConversionType();
8289 bool isLValueReference = false;
8290 bool isRValueReference = false;
8291 bool isPointer = false;
8292 if (const LValueReferenceType *FnTypeRef =
8293 FnType->getAs<LValueReferenceType>()) {
8294 FnType = FnTypeRef->getPointeeType();
8295 isLValueReference = true;
8296 } else if (const RValueReferenceType *FnTypeRef =
8297 FnType->getAs<RValueReferenceType>()) {
8298 FnType = FnTypeRef->getPointeeType();
8299 isRValueReference = true;
8300 }
8301 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8302 FnType = FnTypePtr->getPointeeType();
8303 isPointer = true;
8304 }
8305 // Desugar down to a function type.
8306 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8307 // Reconstruct the pointer/reference as appropriate.
8308 if (isPointer) FnType = S.Context.getPointerType(FnType);
8309 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8310 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8311
8312 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8313 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008314 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008315}
8316
8317void NoteBuiltinOperatorCandidate(Sema &S,
8318 const char *Opc,
8319 SourceLocation OpLoc,
8320 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008321 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008322 std::string TypeStr("operator");
8323 TypeStr += Opc;
8324 TypeStr += "(";
8325 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008326 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008327 TypeStr += ")";
8328 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8329 } else {
8330 TypeStr += ", ";
8331 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8332 TypeStr += ")";
8333 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8334 }
8335}
8336
8337void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8338 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008339 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008340 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8341 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008342 if (ICS.isBad()) break; // all meaningless after first invalid
8343 if (!ICS.isAmbiguous()) continue;
8344
John McCall5c32be02010-08-24 20:38:10 +00008345 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008346 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008347 }
8348}
8349
John McCall3712d9e2010-01-15 23:32:50 +00008350SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8351 if (Cand->Function)
8352 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008353 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008354 return Cand->Surrogate->getLocation();
8355 return SourceLocation();
8356}
8357
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008358static unsigned
8359RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008360 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008361 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008362 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008363
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008364 case Sema::TDK_Incomplete:
8365 return 1;
8366
8367 case Sema::TDK_Underqualified:
8368 case Sema::TDK_Inconsistent:
8369 return 2;
8370
8371 case Sema::TDK_SubstitutionFailure:
8372 case Sema::TDK_NonDeducedMismatch:
8373 return 3;
8374
8375 case Sema::TDK_InstantiationDepth:
8376 case Sema::TDK_FailedOverloadResolution:
8377 return 4;
8378
8379 case Sema::TDK_InvalidExplicitArguments:
8380 return 5;
8381
8382 case Sema::TDK_TooManyArguments:
8383 case Sema::TDK_TooFewArguments:
8384 return 6;
8385 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008386 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008387}
8388
John McCallad2587a2010-01-12 00:48:53 +00008389struct CompareOverloadCandidatesForDisplay {
8390 Sema &S;
8391 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008392
8393 bool operator()(const OverloadCandidate *L,
8394 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008395 // Fast-path this check.
8396 if (L == R) return false;
8397
John McCall12f97bc2010-01-08 04:41:39 +00008398 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008399 if (L->Viable) {
8400 if (!R->Viable) return true;
8401
8402 // TODO: introduce a tri-valued comparison for overload
8403 // candidates. Would be more worthwhile if we had a sort
8404 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008405 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8406 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008407 } else if (R->Viable)
8408 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008409
John McCall3712d9e2010-01-15 23:32:50 +00008410 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008411
John McCall3712d9e2010-01-15 23:32:50 +00008412 // Criteria by which we can sort non-viable candidates:
8413 if (!L->Viable) {
8414 // 1. Arity mismatches come after other candidates.
8415 if (L->FailureKind == ovl_fail_too_many_arguments ||
8416 L->FailureKind == ovl_fail_too_few_arguments)
8417 return false;
8418 if (R->FailureKind == ovl_fail_too_many_arguments ||
8419 R->FailureKind == ovl_fail_too_few_arguments)
8420 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008421
John McCallfe796dd2010-01-23 05:17:32 +00008422 // 2. Bad conversions come first and are ordered by the number
8423 // of bad conversions and quality of good conversions.
8424 if (L->FailureKind == ovl_fail_bad_conversion) {
8425 if (R->FailureKind != ovl_fail_bad_conversion)
8426 return true;
8427
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008428 // The conversion that can be fixed with a smaller number of changes,
8429 // comes first.
8430 unsigned numLFixes = L->Fix.NumConversionsFixed;
8431 unsigned numRFixes = R->Fix.NumConversionsFixed;
8432 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8433 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008434 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008435 if (numLFixes < numRFixes)
8436 return true;
8437 else
8438 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008439 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008440
John McCallfe796dd2010-01-23 05:17:32 +00008441 // If there's any ordering between the defined conversions...
8442 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008443 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008444
8445 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008446 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008447 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008448 switch (CompareImplicitConversionSequences(S,
8449 L->Conversions[I],
8450 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008451 case ImplicitConversionSequence::Better:
8452 leftBetter++;
8453 break;
8454
8455 case ImplicitConversionSequence::Worse:
8456 leftBetter--;
8457 break;
8458
8459 case ImplicitConversionSequence::Indistinguishable:
8460 break;
8461 }
8462 }
8463 if (leftBetter > 0) return true;
8464 if (leftBetter < 0) return false;
8465
8466 } else if (R->FailureKind == ovl_fail_bad_conversion)
8467 return false;
8468
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008469 if (L->FailureKind == ovl_fail_bad_deduction) {
8470 if (R->FailureKind != ovl_fail_bad_deduction)
8471 return true;
8472
8473 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8474 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008475 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008476 } else if (R->FailureKind == ovl_fail_bad_deduction)
8477 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008478
John McCall3712d9e2010-01-15 23:32:50 +00008479 // TODO: others?
8480 }
8481
8482 // Sort everything else by location.
8483 SourceLocation LLoc = GetLocationForCandidate(L);
8484 SourceLocation RLoc = GetLocationForCandidate(R);
8485
8486 // Put candidates without locations (e.g. builtins) at the end.
8487 if (LLoc.isInvalid()) return false;
8488 if (RLoc.isInvalid()) return true;
8489
8490 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008491 }
8492};
8493
John McCallfe796dd2010-01-23 05:17:32 +00008494/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008495/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008496void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008497 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008498 assert(!Cand->Viable);
8499
8500 // Don't do anything on failures other than bad conversion.
8501 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8502
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008503 // We only want the FixIts if all the arguments can be corrected.
8504 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008505 // Use a implicit copy initialization to check conversion fixes.
8506 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008507
John McCallfe796dd2010-01-23 05:17:32 +00008508 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008509 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008510 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008511 while (true) {
8512 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8513 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008514 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008515 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008516 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008517 }
John McCallfe796dd2010-01-23 05:17:32 +00008518 }
8519
8520 if (ConvIdx == ConvCount)
8521 return;
8522
John McCall65eb8792010-02-25 01:37:24 +00008523 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8524 "remaining conversion is initialized?");
8525
Douglas Gregoradc7a702010-04-16 17:45:54 +00008526 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008527 // operation somehow.
8528 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008529
8530 const FunctionProtoType* Proto;
8531 unsigned ArgIdx = ConvIdx;
8532
8533 if (Cand->IsSurrogate) {
8534 QualType ConvType
8535 = Cand->Surrogate->getConversionType().getNonReferenceType();
8536 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8537 ConvType = ConvPtrType->getPointeeType();
8538 Proto = ConvType->getAs<FunctionProtoType>();
8539 ArgIdx--;
8540 } else if (Cand->Function) {
8541 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8542 if (isa<CXXMethodDecl>(Cand->Function) &&
8543 !isa<CXXConstructorDecl>(Cand->Function))
8544 ArgIdx--;
8545 } else {
8546 // Builtin binary operator with a bad first conversion.
8547 assert(ConvCount <= 3);
8548 for (; ConvIdx != ConvCount; ++ConvIdx)
8549 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008550 = TryCopyInitialization(S, Args[ConvIdx],
8551 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008553 /*InOverloadResolution*/ true,
8554 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008555 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008556 return;
8557 }
8558
8559 // Fill in the rest of the conversions.
8560 unsigned NumArgsInProto = Proto->getNumArgs();
8561 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008562 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008563 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008564 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008565 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008566 /*InOverloadResolution=*/true,
8567 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008568 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008569 // Store the FixIt in the candidate if it exists.
8570 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008571 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008572 }
John McCallfe796dd2010-01-23 05:17:32 +00008573 else
8574 Cand->Conversions[ConvIdx].setEllipsis();
8575 }
8576}
8577
John McCalld3224162010-01-08 00:58:21 +00008578} // end anonymous namespace
8579
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008580/// PrintOverloadCandidates - When overload resolution fails, prints
8581/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008582/// set.
John McCall5c32be02010-08-24 20:38:10 +00008583void OverloadCandidateSet::NoteCandidates(Sema &S,
8584 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008585 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008586 const char *Opc,
8587 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008588 // Sort the candidates by viability and position. Sorting directly would
8589 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008590 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008591 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8592 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008593 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008594 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008595 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008596 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008597 if (Cand->Function || Cand->IsSurrogate)
8598 Cands.push_back(Cand);
8599 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8600 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008601 }
8602 }
8603
John McCallad2587a2010-01-12 00:48:53 +00008604 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008605 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008606
John McCall0d1da222010-01-12 00:44:57 +00008607 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008609 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008610 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8611 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008612 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008613 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8614 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008615
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008616 // Set an arbitrary limit on the number of candidate functions we'll spam
8617 // the user with. FIXME: This limit should depend on details of the
8618 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008619 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008620 break;
8621 }
8622 ++CandsShown;
8623
John McCalld3224162010-01-08 00:58:21 +00008624 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008625 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008626 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008627 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008628 else {
8629 assert(Cand->Viable &&
8630 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008631 // Generally we only see ambiguities including viable builtin
8632 // operators if overload resolution got screwed up by an
8633 // ambiguous user-defined conversion.
8634 //
8635 // FIXME: It's quite possible for different conversions to see
8636 // different ambiguities, though.
8637 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008638 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008639 ReportedAmbiguousConversions = true;
8640 }
John McCalld3224162010-01-08 00:58:21 +00008641
John McCall0d1da222010-01-12 00:44:57 +00008642 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008643 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008644 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008645 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008646
8647 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008648 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008649}
8650
Douglas Gregorb491ed32011-02-19 21:32:49 +00008651// [PossiblyAFunctionType] --> [Return]
8652// NonFunctionType --> NonFunctionType
8653// R (A) --> R(A)
8654// R (*)(A) --> R (A)
8655// R (&)(A) --> R (A)
8656// R (S::*)(A) --> R (A)
8657QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8658 QualType Ret = PossiblyAFunctionType;
8659 if (const PointerType *ToTypePtr =
8660 PossiblyAFunctionType->getAs<PointerType>())
8661 Ret = ToTypePtr->getPointeeType();
8662 else if (const ReferenceType *ToTypeRef =
8663 PossiblyAFunctionType->getAs<ReferenceType>())
8664 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008665 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008666 PossiblyAFunctionType->getAs<MemberPointerType>())
8667 Ret = MemTypePtr->getPointeeType();
8668 Ret =
8669 Context.getCanonicalType(Ret).getUnqualifiedType();
8670 return Ret;
8671}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008672
Douglas Gregorb491ed32011-02-19 21:32:49 +00008673// A helper class to help with address of function resolution
8674// - allows us to avoid passing around all those ugly parameters
8675class AddressOfFunctionResolver
8676{
8677 Sema& S;
8678 Expr* SourceExpr;
8679 const QualType& TargetType;
8680 QualType TargetFunctionType; // Extracted function type from target type
8681
8682 bool Complain;
8683 //DeclAccessPair& ResultFunctionAccessPair;
8684 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008685
Douglas Gregorb491ed32011-02-19 21:32:49 +00008686 bool TargetTypeIsNonStaticMemberFunction;
8687 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008688
Douglas Gregorb491ed32011-02-19 21:32:49 +00008689 OverloadExpr::FindResult OvlExprInfo;
8690 OverloadExpr *OvlExpr;
8691 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008692 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008693
Douglas Gregorb491ed32011-02-19 21:32:49 +00008694public:
8695 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8696 const QualType& TargetType, bool Complain)
8697 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8698 Complain(Complain), Context(S.getASTContext()),
8699 TargetTypeIsNonStaticMemberFunction(
8700 !!TargetType->getAs<MemberPointerType>()),
8701 FoundNonTemplateFunction(false),
8702 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8703 OvlExpr(OvlExprInfo.Expression)
8704 {
8705 ExtractUnqualifiedFunctionTypeFromTargetType();
8706
8707 if (!TargetFunctionType->isFunctionType()) {
8708 if (OvlExpr->hasExplicitTemplateArgs()) {
8709 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008710 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008711 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008712
8713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8714 if (!Method->isStatic()) {
8715 // If the target type is a non-function type and the function
8716 // found is a non-static member function, pretend as if that was
8717 // the target, it's the only possible type to end up with.
8718 TargetTypeIsNonStaticMemberFunction = true;
8719
8720 // And skip adding the function if its not in the proper form.
8721 // We'll diagnose this due to an empty set of functions.
8722 if (!OvlExprInfo.HasFormOfMemberPointer)
8723 return;
8724 }
8725 }
8726
Douglas Gregorb491ed32011-02-19 21:32:49 +00008727 Matches.push_back(std::make_pair(dap,Fn));
8728 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008729 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008730 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008731 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008732
8733 if (OvlExpr->hasExplicitTemplateArgs())
8734 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008735
Douglas Gregorb491ed32011-02-19 21:32:49 +00008736 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8737 // C++ [over.over]p4:
8738 // If more than one function is selected, [...]
8739 if (Matches.size() > 1) {
8740 if (FoundNonTemplateFunction)
8741 EliminateAllTemplateMatches();
8742 else
8743 EliminateAllExceptMostSpecializedTemplate();
8744 }
8745 }
8746 }
8747
8748private:
8749 bool isTargetTypeAFunction() const {
8750 return TargetFunctionType->isFunctionType();
8751 }
8752
8753 // [ToType] [Return]
8754
8755 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8756 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8757 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8758 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8759 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8760 }
8761
8762 // return true if any matching specializations were found
8763 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8764 const DeclAccessPair& CurAccessFunPair) {
8765 if (CXXMethodDecl *Method
8766 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8767 // Skip non-static function templates when converting to pointer, and
8768 // static when converting to member pointer.
8769 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8770 return false;
8771 }
8772 else if (TargetTypeIsNonStaticMemberFunction)
8773 return false;
8774
8775 // C++ [over.over]p2:
8776 // If the name is a function template, template argument deduction is
8777 // done (14.8.2.2), and if the argument deduction succeeds, the
8778 // resulting template argument list is used to generate a single
8779 // function template specialization, which is added to the set of
8780 // overloaded functions considered.
8781 FunctionDecl *Specialization = 0;
8782 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8783 if (Sema::TemplateDeductionResult Result
8784 = S.DeduceTemplateArguments(FunctionTemplate,
8785 &OvlExplicitTemplateArgs,
8786 TargetFunctionType, Specialization,
8787 Info)) {
8788 // FIXME: make a note of the failed deduction for diagnostics.
8789 (void)Result;
8790 return false;
8791 }
8792
8793 // Template argument deduction ensures that we have an exact match.
8794 // This function template specicalization works.
8795 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8796 assert(TargetFunctionType
8797 == Context.getCanonicalType(Specialization->getType()));
8798 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8799 return true;
8800 }
8801
8802 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8803 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008804 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008805 // Skip non-static functions when converting to pointer, and static
8806 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008807 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8808 return false;
8809 }
8810 else if (TargetTypeIsNonStaticMemberFunction)
8811 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008812
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008813 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008814 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008815 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8816 if (S.CheckCUDATarget(Caller, FunDecl))
8817 return false;
8818
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008819 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008820 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8821 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008822 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8823 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008824 Matches.push_back(std::make_pair(CurAccessFunPair,
8825 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008826 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008827 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008828 }
Mike Stump11289f42009-09-09 15:08:12 +00008829 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008830
8831 return false;
8832 }
8833
8834 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8835 bool Ret = false;
8836
8837 // If the overload expression doesn't have the form of a pointer to
8838 // member, don't try to convert it to a pointer-to-member type.
8839 if (IsInvalidFormOfPointerToMemberFunction())
8840 return false;
8841
8842 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8843 E = OvlExpr->decls_end();
8844 I != E; ++I) {
8845 // Look through any using declarations to find the underlying function.
8846 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8847
8848 // C++ [over.over]p3:
8849 // Non-member functions and static member functions match
8850 // targets of type "pointer-to-function" or "reference-to-function."
8851 // Nonstatic member functions match targets of
8852 // type "pointer-to-member-function."
8853 // Note that according to DR 247, the containing class does not matter.
8854 if (FunctionTemplateDecl *FunctionTemplate
8855 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8856 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8857 Ret = true;
8858 }
8859 // If we have explicit template arguments supplied, skip non-templates.
8860 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8861 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8862 Ret = true;
8863 }
8864 assert(Ret || Matches.empty());
8865 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008866 }
8867
Douglas Gregorb491ed32011-02-19 21:32:49 +00008868 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008869 // [...] and any given function template specialization F1 is
8870 // eliminated if the set contains a second function template
8871 // specialization whose function template is more specialized
8872 // than the function template of F1 according to the partial
8873 // ordering rules of 14.5.5.2.
8874
8875 // The algorithm specified above is quadratic. We instead use a
8876 // two-pass algorithm (similar to the one used to identify the
8877 // best viable function in an overload set) that identifies the
8878 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008879
8880 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8881 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8882 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008883
John McCall58cc69d2010-01-27 01:50:18 +00008884 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008885 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8886 TPOC_Other, 0, SourceExpr->getLocStart(),
8887 S.PDiag(),
8888 S.PDiag(diag::err_addr_ovl_ambiguous)
8889 << Matches[0].second->getDeclName(),
8890 S.PDiag(diag::note_ovl_candidate)
8891 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008892 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008893
Douglas Gregorb491ed32011-02-19 21:32:49 +00008894 if (Result != MatchesCopy.end()) {
8895 // Make it the first and only element
8896 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8897 Matches[0].second = cast<FunctionDecl>(*Result);
8898 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008899 }
8900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008901
Douglas Gregorb491ed32011-02-19 21:32:49 +00008902 void EliminateAllTemplateMatches() {
8903 // [...] any function template specializations in the set are
8904 // eliminated if the set also contains a non-template function, [...]
8905 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8906 if (Matches[I].second->getPrimaryTemplate() == 0)
8907 ++I;
8908 else {
8909 Matches[I] = Matches[--N];
8910 Matches.set_size(N);
8911 }
8912 }
8913 }
8914
8915public:
8916 void ComplainNoMatchesFound() const {
8917 assert(Matches.empty());
8918 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8919 << OvlExpr->getName() << TargetFunctionType
8920 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008921 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008922 }
8923
8924 bool IsInvalidFormOfPointerToMemberFunction() const {
8925 return TargetTypeIsNonStaticMemberFunction &&
8926 !OvlExprInfo.HasFormOfMemberPointer;
8927 }
8928
8929 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8930 // TODO: Should we condition this on whether any functions might
8931 // have matched, or is it more appropriate to do that in callers?
8932 // TODO: a fixit wouldn't hurt.
8933 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8934 << TargetType << OvlExpr->getSourceRange();
8935 }
8936
8937 void ComplainOfInvalidConversion() const {
8938 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8939 << OvlExpr->getName() << TargetType;
8940 }
8941
8942 void ComplainMultipleMatchesFound() const {
8943 assert(Matches.size() > 1);
8944 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8945 << OvlExpr->getName()
8946 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008947 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008948 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008949
8950 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8951
Douglas Gregorb491ed32011-02-19 21:32:49 +00008952 int getNumMatches() const { return Matches.size(); }
8953
8954 FunctionDecl* getMatchingFunctionDecl() const {
8955 if (Matches.size() != 1) return 0;
8956 return Matches[0].second;
8957 }
8958
8959 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8960 if (Matches.size() != 1) return 0;
8961 return &Matches[0].first;
8962 }
8963};
8964
8965/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8966/// an overloaded function (C++ [over.over]), where @p From is an
8967/// expression with overloaded function type and @p ToType is the type
8968/// we're trying to resolve to. For example:
8969///
8970/// @code
8971/// int f(double);
8972/// int f(int);
8973///
8974/// int (*pfd)(double) = f; // selects f(double)
8975/// @endcode
8976///
8977/// This routine returns the resulting FunctionDecl if it could be
8978/// resolved, and NULL otherwise. When @p Complain is true, this
8979/// routine will emit diagnostics if there is an error.
8980FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008981Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8982 QualType TargetType,
8983 bool Complain,
8984 DeclAccessPair &FoundResult,
8985 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008986 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008987
8988 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8989 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008990 int NumMatches = Resolver.getNumMatches();
8991 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008992 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008993 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8994 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8995 else
8996 Resolver.ComplainNoMatchesFound();
8997 }
8998 else if (NumMatches > 1 && Complain)
8999 Resolver.ComplainMultipleMatchesFound();
9000 else if (NumMatches == 1) {
9001 Fn = Resolver.getMatchingFunctionDecl();
9002 assert(Fn);
9003 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009004 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009005 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009006 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009007 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009008
9009 if (pHadMultipleCandidates)
9010 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009011 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009012}
9013
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009014/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009015/// resolve that overloaded function expression down to a single function.
9016///
9017/// This routine can only resolve template-ids that refer to a single function
9018/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009019/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009020/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009021FunctionDecl *
9022Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9023 bool Complain,
9024 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009025 // C++ [over.over]p1:
9026 // [...] [Note: any redundant set of parentheses surrounding the
9027 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009028 // C++ [over.over]p1:
9029 // [...] The overloaded function name can be preceded by the &
9030 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009031
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009032 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009033 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009034 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009035
9036 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009037 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009038
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009039 // Look through all of the overloaded functions, searching for one
9040 // whose type matches exactly.
9041 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009042 for (UnresolvedSetIterator I = ovl->decls_begin(),
9043 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009044 // C++0x [temp.arg.explicit]p3:
9045 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009046 // where deduction is not done, if a template argument list is
9047 // specified and it, along with any default template arguments,
9048 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009049 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009050 FunctionTemplateDecl *FunctionTemplate
9051 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009052
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009053 // C++ [over.over]p2:
9054 // If the name is a function template, template argument deduction is
9055 // done (14.8.2.2), and if the argument deduction succeeds, the
9056 // resulting template argument list is used to generate a single
9057 // function template specialization, which is added to the set of
9058 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009059 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009060 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009061 if (TemplateDeductionResult Result
9062 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9063 Specialization, Info)) {
9064 // FIXME: make a note of the failed deduction for diagnostics.
9065 (void)Result;
9066 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067 }
9068
John McCall0009fcc2011-04-26 20:42:42 +00009069 assert(Specialization && "no specialization and no error?");
9070
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009071 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009072 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009073 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009074 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9075 << ovl->getName();
9076 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009077 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009078 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009079 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009080
John McCall0009fcc2011-04-26 20:42:42 +00009081 Matched = Specialization;
9082 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009085 return Matched;
9086}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009087
Douglas Gregor1beec452011-03-12 01:48:56 +00009088
9089
9090
John McCall50a2c2c2011-10-11 23:14:30 +00009091// Resolve and fix an overloaded expression that can be resolved
9092// because it identifies a single function template specialization.
9093//
Douglas Gregor1beec452011-03-12 01:48:56 +00009094// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009095//
9096// Return true if it was logically possible to so resolve the
9097// expression, regardless of whether or not it succeeded. Always
9098// returns true if 'complain' is set.
9099bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9100 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9101 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009102 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009103 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009104 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009105
John McCall50a2c2c2011-10-11 23:14:30 +00009106 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009107
John McCall0009fcc2011-04-26 20:42:42 +00009108 DeclAccessPair found;
9109 ExprResult SingleFunctionExpression;
9110 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9111 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009112 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009113 SrcExpr = ExprError();
9114 return true;
9115 }
John McCall0009fcc2011-04-26 20:42:42 +00009116
9117 // It is only correct to resolve to an instance method if we're
9118 // resolving a form that's permitted to be a pointer to member.
9119 // Otherwise we'll end up making a bound member expression, which
9120 // is illegal in all the contexts we resolve like this.
9121 if (!ovl.HasFormOfMemberPointer &&
9122 isa<CXXMethodDecl>(fn) &&
9123 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009124 if (!complain) return false;
9125
9126 Diag(ovl.Expression->getExprLoc(),
9127 diag::err_bound_member_function)
9128 << 0 << ovl.Expression->getSourceRange();
9129
9130 // TODO: I believe we only end up here if there's a mix of
9131 // static and non-static candidates (otherwise the expression
9132 // would have 'bound member' type, not 'overload' type).
9133 // Ideally we would note which candidate was chosen and why
9134 // the static candidates were rejected.
9135 SrcExpr = ExprError();
9136 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009137 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009138
John McCall0009fcc2011-04-26 20:42:42 +00009139 // Fix the expresion to refer to 'fn'.
9140 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009141 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009142
9143 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009144 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009145 SingleFunctionExpression =
9146 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009147 if (SingleFunctionExpression.isInvalid()) {
9148 SrcExpr = ExprError();
9149 return true;
9150 }
9151 }
John McCall0009fcc2011-04-26 20:42:42 +00009152 }
9153
9154 if (!SingleFunctionExpression.isUsable()) {
9155 if (complain) {
9156 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9157 << ovl.Expression->getName()
9158 << DestTypeForComplaining
9159 << OpRangeForComplaining
9160 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009161 NoteAllOverloadCandidates(SrcExpr.get());
9162
9163 SrcExpr = ExprError();
9164 return true;
9165 }
9166
9167 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009168 }
9169
John McCall50a2c2c2011-10-11 23:14:30 +00009170 SrcExpr = SingleFunctionExpression;
9171 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009172}
9173
Douglas Gregorcabea402009-09-22 15:41:20 +00009174/// \brief Add a single candidate to the overload set.
9175static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009176 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009177 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009178 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009179 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009180 bool PartialOverloading,
9181 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009182 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009183 if (isa<UsingShadowDecl>(Callee))
9184 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9185
Douglas Gregorcabea402009-09-22 15:41:20 +00009186 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009187 if (ExplicitTemplateArgs) {
9188 assert(!KnownValid && "Explicit template arguments?");
9189 return;
9190 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009191 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9192 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009193 return;
John McCalld14a8642009-11-21 08:51:07 +00009194 }
9195
9196 if (FunctionTemplateDecl *FuncTemplate
9197 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009198 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009199 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009200 return;
9201 }
9202
Richard Smith95ce4f62011-06-26 22:19:54 +00009203 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009204}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009205
Douglas Gregorcabea402009-09-22 15:41:20 +00009206/// \brief Add the overload candidates named by callee and/or found by argument
9207/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009208void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009209 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009210 OverloadCandidateSet &CandidateSet,
9211 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009212
9213#ifndef NDEBUG
9214 // Verify that ArgumentDependentLookup is consistent with the rules
9215 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009216 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009217 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9218 // and let Y be the lookup set produced by argument dependent
9219 // lookup (defined as follows). If X contains
9220 //
9221 // -- a declaration of a class member, or
9222 //
9223 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009224 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009225 //
9226 // -- a declaration that is neither a function or a function
9227 // template
9228 //
9229 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009230
John McCall57500772009-12-16 12:17:52 +00009231 if (ULE->requiresADL()) {
9232 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9233 E = ULE->decls_end(); I != E; ++I) {
9234 assert(!(*I)->getDeclContext()->isRecord());
9235 assert(isa<UsingShadowDecl>(*I) ||
9236 !(*I)->getDeclContext()->isFunctionOrMethod());
9237 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009238 }
9239 }
9240#endif
9241
John McCall57500772009-12-16 12:17:52 +00009242 // It would be nice to avoid this copy.
9243 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009244 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009245 if (ULE->hasExplicitTemplateArgs()) {
9246 ULE->copyTemplateArgumentsInto(TABuffer);
9247 ExplicitTemplateArgs = &TABuffer;
9248 }
9249
9250 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9251 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009252 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9253 CandidateSet, PartialOverloading,
9254 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009255
John McCall57500772009-12-16 12:17:52 +00009256 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009257 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009258 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009259 Args, ExplicitTemplateArgs,
9260 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009261 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009262}
John McCalld681c392009-12-16 08:11:27 +00009263
Richard Smith998a5912011-06-05 22:42:48 +00009264/// Attempt to recover from an ill-formed use of a non-dependent name in a
9265/// template, where the non-dependent name was declared after the template
9266/// was defined. This is common in code written for a compilers which do not
9267/// correctly implement two-stage name lookup.
9268///
9269/// Returns true if a viable candidate was found and a diagnostic was issued.
9270static bool
9271DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9272 const CXXScopeSpec &SS, LookupResult &R,
9273 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009274 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009275 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9276 return false;
9277
9278 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009279 if (DC->isTransparentContext())
9280 continue;
9281
Richard Smith998a5912011-06-05 22:42:48 +00009282 SemaRef.LookupQualifiedName(R, DC);
9283
9284 if (!R.empty()) {
9285 R.suppressDiagnostics();
9286
9287 if (isa<CXXRecordDecl>(DC)) {
9288 // Don't diagnose names we find in classes; we get much better
9289 // diagnostics for these from DiagnoseEmptyLookup.
9290 R.clear();
9291 return false;
9292 }
9293
9294 OverloadCandidateSet Candidates(FnLoc);
9295 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9296 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009297 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009298 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009299
9300 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009301 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009302 // No viable functions. Don't bother the user with notes for functions
9303 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009304 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009305 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009306 }
Richard Smith998a5912011-06-05 22:42:48 +00009307
9308 // Find the namespaces where ADL would have looked, and suggest
9309 // declaring the function there instead.
9310 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9311 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009312 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009313 AssociatedNamespaces,
9314 AssociatedClasses);
9315 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009316 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009317 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009318 for (Sema::AssociatedNamespaceSet::iterator
9319 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009320 end = AssociatedNamespaces.end(); it != end; ++it) {
9321 if (!Std->Encloses(*it))
9322 SuggestedNamespaces.insert(*it);
9323 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009324 } else {
9325 // Lacking the 'std::' namespace, use all of the associated namespaces.
9326 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009327 }
9328
9329 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9330 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009331 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009332 SemaRef.Diag(Best->Function->getLocation(),
9333 diag::note_not_found_by_two_phase_lookup)
9334 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009335 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009336 SemaRef.Diag(Best->Function->getLocation(),
9337 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009338 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009339 } else {
9340 // FIXME: It would be useful to list the associated namespaces here,
9341 // but the diagnostics infrastructure doesn't provide a way to produce
9342 // a localized representation of a list of items.
9343 SemaRef.Diag(Best->Function->getLocation(),
9344 diag::note_not_found_by_two_phase_lookup)
9345 << R.getLookupName() << 2;
9346 }
9347
9348 // Try to recover by calling this function.
9349 return true;
9350 }
9351
9352 R.clear();
9353 }
9354
9355 return false;
9356}
9357
9358/// Attempt to recover from ill-formed use of a non-dependent operator in a
9359/// template, where the non-dependent operator was declared after the template
9360/// was defined.
9361///
9362/// Returns true if a viable candidate was found and a diagnostic was issued.
9363static bool
9364DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9365 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009366 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009367 DeclarationName OpName =
9368 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9369 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9370 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009371 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009372}
9373
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009374namespace {
9375// Callback to limit the allowed keywords and to only accept typo corrections
9376// that are keywords or whose decls refer to functions (or template functions)
9377// that accept the given number of arguments.
9378class RecoveryCallCCC : public CorrectionCandidateCallback {
9379 public:
9380 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9381 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009382 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009383 WantRemainingKeywords = false;
9384 }
9385
9386 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9387 if (!candidate.getCorrectionDecl())
9388 return candidate.isKeyword();
9389
9390 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9391 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9392 FunctionDecl *FD = 0;
9393 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9394 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9395 FD = FTD->getTemplatedDecl();
9396 if (!HasExplicitTemplateArgs && !FD) {
9397 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9398 // If the Decl is neither a function nor a template function,
9399 // determine if it is a pointer or reference to a function. If so,
9400 // check against the number of arguments expected for the pointee.
9401 QualType ValType = cast<ValueDecl>(ND)->getType();
9402 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9403 ValType = ValType->getPointeeType();
9404 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9405 if (FPT->getNumArgs() == NumArgs)
9406 return true;
9407 }
9408 }
9409 if (FD && FD->getNumParams() >= NumArgs &&
9410 FD->getMinRequiredArguments() <= NumArgs)
9411 return true;
9412 }
9413 return false;
9414 }
9415
9416 private:
9417 unsigned NumArgs;
9418 bool HasExplicitTemplateArgs;
9419};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009420
9421// Callback that effectively disabled typo correction
9422class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9423 public:
9424 NoTypoCorrectionCCC() {
9425 WantTypeSpecifiers = false;
9426 WantExpressionKeywords = false;
9427 WantCXXNamedCasts = false;
9428 WantRemainingKeywords = false;
9429 }
9430
9431 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9432 return false;
9433 }
9434};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009435}
9436
John McCalld681c392009-12-16 08:11:27 +00009437/// Attempts to recover from a call where no functions were found.
9438///
9439/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009440static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009441BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009442 UnresolvedLookupExpr *ULE,
9443 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009444 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009445 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009446 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009447
9448 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009449 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009450 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009451
John McCall57500772009-12-16 12:17:52 +00009452 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009453 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009454 if (ULE->hasExplicitTemplateArgs()) {
9455 ULE->copyTemplateArgumentsInto(TABuffer);
9456 ExplicitTemplateArgs = &TABuffer;
9457 }
9458
John McCalld681c392009-12-16 08:11:27 +00009459 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9460 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009461 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009462 NoTypoCorrectionCCC RejectAll;
9463 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9464 (CorrectionCandidateCallback*)&Validator :
9465 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009466 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009467 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009468 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009469 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009470 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009471 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009472
John McCall57500772009-12-16 12:17:52 +00009473 assert(!R.empty() && "lookup results empty despite recovery");
9474
9475 // Build an implicit member call if appropriate. Just drop the
9476 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009477 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009478 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009479 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9480 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009481 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009482 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009483 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009484 else
9485 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9486
9487 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009488 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009489
9490 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009491 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009492 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009493 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009494 MultiExprArg(Args.data(), Args.size()),
9495 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009496}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009497
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009498/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009499/// (which eventually refers to the declaration Func) and the call
9500/// arguments Args/NumArgs, attempt to resolve the function call down
9501/// to a specific function. If overload resolution succeeds, returns
9502/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009503/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009504/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009505ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009506Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009507 SourceLocation LParenLoc,
9508 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009509 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009510 Expr *ExecConfig,
9511 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009512#ifndef NDEBUG
9513 if (ULE->requiresADL()) {
9514 // To do ADL, we must have found an unqualified name.
9515 assert(!ULE->getQualifier() && "qualified name with ADL");
9516
9517 // We don't perform ADL for implicit declarations of builtins.
9518 // Verify that this was correctly set up.
9519 FunctionDecl *F;
9520 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9521 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9522 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009523 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009524
John McCall57500772009-12-16 12:17:52 +00009525 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009526 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009527 } else
9528 assert(!ULE->isStdAssociatedNamespace() &&
9529 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009530#endif
9531
John McCall4124c492011-10-17 18:40:02 +00009532 UnbridgedCastsSet UnbridgedCasts;
9533 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9534 return ExprError();
9535
John McCallbc077cf2010-02-08 23:07:23 +00009536 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009537
John McCall57500772009-12-16 12:17:52 +00009538 // Add the functions denoted by the callee to the set of candidate
9539 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009540 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9541 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009542
9543 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009544 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9545 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009546 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009547 // In Microsoft mode, if we are inside a template class member function then
9548 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009549 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009550 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009551 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009552 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009553 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9554 Context.DependentTy, VK_RValue,
9555 RParenLoc);
9556 CE->setTypeDependent(true);
9557 return Owned(CE);
9558 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009559 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9560 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009561 RParenLoc, /*EmptyLookup=*/true,
9562 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009563 }
John McCalld681c392009-12-16 08:11:27 +00009564
John McCall4124c492011-10-17 18:40:02 +00009565 UnbridgedCasts.restore();
9566
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009567 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009568 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009569 case OR_Success: {
9570 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009571 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009572 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009573 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009574 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009575 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9576 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009577 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009578
Richard Smith998a5912011-06-05 22:42:48 +00009579 case OR_No_Viable_Function: {
9580 // Try to recover by looking for viable functions which the user might
9581 // have meant to call.
9582 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009583 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9584 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009585 /*EmptyLookup=*/false,
9586 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009587 if (!Recovery.isInvalid())
9588 return Recovery;
9589
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009590 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009591 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009592 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009593 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9594 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009595 break;
Richard Smith998a5912011-06-05 22:42:48 +00009596 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009597
9598 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009599 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009600 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009601 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9602 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009603 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009604
9605 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009606 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009607 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009608 << Best->Function->isDeleted()
9609 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009610 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009611 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009612 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9613 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009614
9615 // We emitted an error for the unvailable/deleted function call but keep
9616 // the call in the AST.
9617 FunctionDecl *FDecl = Best->Function;
9618 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9619 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9620 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009621 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009622 }
9623
Douglas Gregorb412e172010-07-25 18:17:45 +00009624 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009625 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009626}
9627
John McCall4c4c1df2010-01-26 03:27:55 +00009628static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009629 return Functions.size() > 1 ||
9630 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9631}
9632
Douglas Gregor084d8552009-03-13 23:49:33 +00009633/// \brief Create a unary operation that may resolve to an overloaded
9634/// operator.
9635///
9636/// \param OpLoc The location of the operator itself (e.g., '*').
9637///
9638/// \param OpcIn The UnaryOperator::Opcode that describes this
9639/// operator.
9640///
9641/// \param Functions The set of non-member functions that will be
9642/// considered by overload resolution. The caller needs to build this
9643/// set based on the context using, e.g.,
9644/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9645/// set should not contain any member functions; those will be added
9646/// by CreateOverloadedUnaryOp().
9647///
9648/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009649ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009650Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9651 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009652 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009653 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009654
9655 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9656 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009658 // TODO: provide better source location info.
9659 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009660
John McCall4124c492011-10-17 18:40:02 +00009661 if (checkPlaceholderForOverload(*this, Input))
9662 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009663
Douglas Gregor084d8552009-03-13 23:49:33 +00009664 Expr *Args[2] = { Input, 0 };
9665 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009666
Douglas Gregor084d8552009-03-13 23:49:33 +00009667 // For post-increment and post-decrement, add the implicit '0' as
9668 // the second argument, so that we know this is a post-increment or
9669 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009670 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009671 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009672 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9673 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009674 NumArgs = 2;
9675 }
9676
9677 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009678 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009679 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009680 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009681 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009682 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009683 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009684
John McCall58cc69d2010-01-27 01:50:18 +00009685 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009686 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009687 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009688 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009689 /*ADL*/ true, IsOverloaded(Fns),
9690 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009691 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009692 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009693 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009694 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009695 OpLoc));
9696 }
9697
9698 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009699 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009700
9701 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009702 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9703 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009704
9705 // Add operator candidates that are member functions.
9706 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9707
John McCall4c4c1df2010-01-26 03:27:55 +00009708 // Add candidates from ADL.
9709 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009710 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009711 /*ExplicitTemplateArgs*/ 0,
9712 CandidateSet);
9713
Douglas Gregor084d8552009-03-13 23:49:33 +00009714 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009715 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009716
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009717 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9718
Douglas Gregor084d8552009-03-13 23:49:33 +00009719 // Perform overload resolution.
9720 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009721 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009722 case OR_Success: {
9723 // We found a built-in operator or an overloaded operator.
9724 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009725
Douglas Gregor084d8552009-03-13 23:49:33 +00009726 if (FnDecl) {
9727 // We matched an overloaded operator. Build a call to that
9728 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009729
Eli Friedmanfa0df832012-02-02 03:46:19 +00009730 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009731
Douglas Gregor084d8552009-03-13 23:49:33 +00009732 // Convert the arguments.
9733 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009734 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009735
John Wiegley01296292011-04-08 18:41:53 +00009736 ExprResult InputRes =
9737 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9738 Best->FoundDecl, Method);
9739 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009740 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009741 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009742 } else {
9743 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009744 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009745 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009746 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009747 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009748 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009749 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009750 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009751 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009752 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009753 }
9754
John McCall4fa0d5f2010-05-06 18:15:07 +00009755 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9756
John McCall7decc9e2010-11-18 06:31:45 +00009757 // Determine the result type.
9758 QualType ResultTy = FnDecl->getResultType();
9759 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9760 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009761
Douglas Gregor084d8552009-03-13 23:49:33 +00009762 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009763 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009764 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009765 if (FnExpr.isInvalid())
9766 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009767
Eli Friedman030eee42009-11-18 03:58:17 +00009768 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009769 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009770 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009771 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009772
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009773 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009774 FnDecl))
9775 return ExprError();
9776
John McCallb268a282010-08-23 23:25:46 +00009777 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009778 } else {
9779 // We matched a built-in operator. Convert the arguments, then
9780 // break out so that we will build the appropriate built-in
9781 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009782 ExprResult InputRes =
9783 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9784 Best->Conversions[0], AA_Passing);
9785 if (InputRes.isInvalid())
9786 return ExprError();
9787 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009788 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009789 }
John Wiegley01296292011-04-08 18:41:53 +00009790 }
9791
9792 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009793 // This is an erroneous use of an operator which can be overloaded by
9794 // a non-member function. Check for non-member operators which were
9795 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009796 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9797 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009798 // FIXME: Recover by calling the found function.
9799 return ExprError();
9800
John Wiegley01296292011-04-08 18:41:53 +00009801 // No viable function; fall through to handling this as a
9802 // built-in operator, which will produce an error message for us.
9803 break;
9804
9805 case OR_Ambiguous:
9806 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9807 << UnaryOperator::getOpcodeStr(Opc)
9808 << Input->getType()
9809 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009810 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9811 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009812 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9813 return ExprError();
9814
9815 case OR_Deleted:
9816 Diag(OpLoc, diag::err_ovl_deleted_oper)
9817 << Best->Function->isDeleted()
9818 << UnaryOperator::getOpcodeStr(Opc)
9819 << getDeletedOrUnavailableSuffix(Best->Function)
9820 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009821 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9822 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009823 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009824 return ExprError();
9825 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009826
9827 // Either we found no viable overloaded operator or we matched a
9828 // built-in operator. In either case, fall through to trying to
9829 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009830 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009831}
9832
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009833/// \brief Create a binary operation that may resolve to an overloaded
9834/// operator.
9835///
9836/// \param OpLoc The location of the operator itself (e.g., '+').
9837///
9838/// \param OpcIn The BinaryOperator::Opcode that describes this
9839/// operator.
9840///
9841/// \param Functions The set of non-member functions that will be
9842/// considered by overload resolution. The caller needs to build this
9843/// set based on the context using, e.g.,
9844/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9845/// set should not contain any member functions; those will be added
9846/// by CreateOverloadedBinOp().
9847///
9848/// \param LHS Left-hand argument.
9849/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009850ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009851Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009852 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009853 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009854 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009855 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009856 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009857
9858 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9859 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9860 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9861
9862 // If either side is type-dependent, create an appropriate dependent
9863 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009864 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009865 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009866 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009867 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009868 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009869 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009870 Context.DependentTy,
9871 VK_RValue, OK_Ordinary,
9872 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009873
Douglas Gregor5287f092009-11-05 00:51:44 +00009874 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9875 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009876 VK_LValue,
9877 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009878 Context.DependentTy,
9879 Context.DependentTy,
9880 OpLoc));
9881 }
John McCall4c4c1df2010-01-26 03:27:55 +00009882
9883 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009884 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009885 // TODO: provide better source location info in DNLoc component.
9886 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009887 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009888 = UnresolvedLookupExpr::Create(Context, NamingClass,
9889 NestedNameSpecifierLoc(), OpNameInfo,
9890 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009891 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009892 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009893 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009894 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009895 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009896 OpLoc));
9897 }
9898
John McCall4124c492011-10-17 18:40:02 +00009899 // Always do placeholder-like conversions on the RHS.
9900 if (checkPlaceholderForOverload(*this, Args[1]))
9901 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009902
John McCall526ab472011-10-25 17:37:35 +00009903 // Do placeholder-like conversion on the LHS; note that we should
9904 // not get here with a PseudoObject LHS.
9905 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009906 if (checkPlaceholderForOverload(*this, Args[0]))
9907 return ExprError();
9908
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009909 // If this is the assignment operator, we only perform overload resolution
9910 // if the left-hand side is a class or enumeration type. This is actually
9911 // a hack. The standard requires that we do overload resolution between the
9912 // various built-in candidates, but as DR507 points out, this can lead to
9913 // problems. So we do it this way, which pretty much follows what GCC does.
9914 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009915 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009916 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009917
John McCalle26a8722010-12-04 08:14:53 +00009918 // If this is the .* operator, which is not overloadable, just
9919 // create a built-in binary operator.
9920 if (Opc == BO_PtrMemD)
9921 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9922
Douglas Gregor084d8552009-03-13 23:49:33 +00009923 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009924 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009925
9926 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009927 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009928
9929 // Add operator candidates that are member functions.
9930 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9931
John McCall4c4c1df2010-01-26 03:27:55 +00009932 // Add candidates from ADL.
9933 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009934 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +00009935 /*ExplicitTemplateArgs*/ 0,
9936 CandidateSet);
9937
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009938 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009939 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009940
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009941 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9942
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009943 // Perform overload resolution.
9944 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009945 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009946 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009947 // We found a built-in operator or an overloaded operator.
9948 FunctionDecl *FnDecl = Best->Function;
9949
9950 if (FnDecl) {
9951 // We matched an overloaded operator. Build a call to that
9952 // operator.
9953
Eli Friedmanfa0df832012-02-02 03:46:19 +00009954 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009955
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009956 // Convert the arguments.
9957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009958 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009959 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009960
Chandler Carruth8e543b32010-12-12 08:17:55 +00009961 ExprResult Arg1 =
9962 PerformCopyInitialization(
9963 InitializedEntity::InitializeParameter(Context,
9964 FnDecl->getParamDecl(0)),
9965 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009966 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009967 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009968
John Wiegley01296292011-04-08 18:41:53 +00009969 ExprResult Arg0 =
9970 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9971 Best->FoundDecl, Method);
9972 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009973 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009974 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009975 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009976 } else {
9977 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009978 ExprResult Arg0 = PerformCopyInitialization(
9979 InitializedEntity::InitializeParameter(Context,
9980 FnDecl->getParamDecl(0)),
9981 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009982 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009983 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009984
Chandler Carruth8e543b32010-12-12 08:17:55 +00009985 ExprResult Arg1 =
9986 PerformCopyInitialization(
9987 InitializedEntity::InitializeParameter(Context,
9988 FnDecl->getParamDecl(1)),
9989 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009990 if (Arg1.isInvalid())
9991 return ExprError();
9992 Args[0] = LHS = Arg0.takeAs<Expr>();
9993 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009994 }
9995
John McCall4fa0d5f2010-05-06 18:15:07 +00009996 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9997
John McCall7decc9e2010-11-18 06:31:45 +00009998 // Determine the result type.
9999 QualType ResultTy = FnDecl->getResultType();
10000 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10001 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010002
10003 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010004 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10005 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010006 if (FnExpr.isInvalid())
10007 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010008
John McCallb268a282010-08-23 23:25:46 +000010009 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010010 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010011 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010012
10013 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010014 FnDecl))
10015 return ExprError();
10016
John McCallb268a282010-08-23 23:25:46 +000010017 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010018 } else {
10019 // We matched a built-in operator. Convert the arguments, then
10020 // break out so that we will build the appropriate built-in
10021 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010022 ExprResult ArgsRes0 =
10023 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10024 Best->Conversions[0], AA_Passing);
10025 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010026 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010027 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010028
John Wiegley01296292011-04-08 18:41:53 +000010029 ExprResult ArgsRes1 =
10030 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10031 Best->Conversions[1], AA_Passing);
10032 if (ArgsRes1.isInvalid())
10033 return ExprError();
10034 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010035 break;
10036 }
10037 }
10038
Douglas Gregor66950a32009-09-30 21:46:01 +000010039 case OR_No_Viable_Function: {
10040 // C++ [over.match.oper]p9:
10041 // If the operator is the operator , [...] and there are no
10042 // viable functions, then the operator is assumed to be the
10043 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010044 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010045 break;
10046
Chandler Carruth8e543b32010-12-12 08:17:55 +000010047 // For class as left operand for assignment or compound assigment
10048 // operator do not fall through to handling in built-in, but report that
10049 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010050 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010051 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010052 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010053 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10054 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010055 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010056 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010057 // This is an erroneous use of an operator which can be overloaded by
10058 // a non-member function. Check for non-member operators which were
10059 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010060 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010061 // FIXME: Recover by calling the found function.
10062 return ExprError();
10063
Douglas Gregor66950a32009-09-30 21:46:01 +000010064 // No viable function; try to create a built-in operation, which will
10065 // produce an error. Then, show the non-viable candidates.
10066 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010067 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010068 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010069 "C++ binary operator overloading is missing candidates!");
10070 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010071 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010072 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010073 return move(Result);
10074 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010075
10076 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010077 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010078 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010079 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010080 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010081 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010082 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010083 return ExprError();
10084
10085 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010086 if (isImplicitlyDeleted(Best->Function)) {
10087 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10088 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10089 << getSpecialMember(Method)
10090 << BinaryOperator::getOpcodeStr(Opc)
10091 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010092
10093 if (getSpecialMember(Method) != CXXInvalid) {
10094 // The user probably meant to call this special member. Just
10095 // explain why it's deleted.
10096 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010097 return ExprError();
10098 }
10099 } else {
10100 Diag(OpLoc, diag::err_ovl_deleted_oper)
10101 << Best->Function->isDeleted()
10102 << BinaryOperator::getOpcodeStr(Opc)
10103 << getDeletedOrUnavailableSuffix(Best->Function)
10104 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10105 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010106 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010107 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010108 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010109 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010110
Douglas Gregor66950a32009-09-30 21:46:01 +000010111 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010113}
10114
John McCalldadc5752010-08-24 06:29:42 +000010115ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010116Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10117 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010118 Expr *Base, Expr *Idx) {
10119 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010120 DeclarationName OpName =
10121 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10122
10123 // If either side is type-dependent, create an appropriate dependent
10124 // expression.
10125 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10126
John McCall58cc69d2010-01-27 01:50:18 +000010127 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010128 // CHECKME: no 'operator' keyword?
10129 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10130 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010131 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010132 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010133 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010134 /*ADL*/ true, /*Overloaded*/ false,
10135 UnresolvedSetIterator(),
10136 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010137 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010138
Sebastian Redladba46e2009-10-29 20:17:01 +000010139 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10140 Args, 2,
10141 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010142 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010143 RLoc));
10144 }
10145
John McCall4124c492011-10-17 18:40:02 +000010146 // Handle placeholders on both operands.
10147 if (checkPlaceholderForOverload(*this, Args[0]))
10148 return ExprError();
10149 if (checkPlaceholderForOverload(*this, Args[1]))
10150 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010151
Sebastian Redladba46e2009-10-29 20:17:01 +000010152 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010153 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010154
10155 // Subscript can only be overloaded as a member function.
10156
10157 // Add operator candidates that are member functions.
10158 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10159
10160 // Add builtin operator candidates.
10161 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10162
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010163 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10164
Sebastian Redladba46e2009-10-29 20:17:01 +000010165 // Perform overload resolution.
10166 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010167 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010168 case OR_Success: {
10169 // We found a built-in operator or an overloaded operator.
10170 FunctionDecl *FnDecl = Best->Function;
10171
10172 if (FnDecl) {
10173 // We matched an overloaded operator. Build a call to that
10174 // operator.
10175
Eli Friedmanfa0df832012-02-02 03:46:19 +000010176 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010177
John McCalla0296f72010-03-19 07:35:19 +000010178 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010179 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010180
Sebastian Redladba46e2009-10-29 20:17:01 +000010181 // Convert the arguments.
10182 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010183 ExprResult Arg0 =
10184 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10185 Best->FoundDecl, Method);
10186 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010187 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010188 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010189
Anders Carlssona68e51e2010-01-29 18:37:50 +000010190 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010191 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010192 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010193 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010194 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010195 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010196 Owned(Args[1]));
10197 if (InputInit.isInvalid())
10198 return ExprError();
10199
10200 Args[1] = InputInit.takeAs<Expr>();
10201
Sebastian Redladba46e2009-10-29 20:17:01 +000010202 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010203 QualType ResultTy = FnDecl->getResultType();
10204 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10205 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010206
10207 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010208 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10209 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010210 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10211 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010212 OpLocInfo.getLoc(),
10213 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010214 if (FnExpr.isInvalid())
10215 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010216
John McCallb268a282010-08-23 23:25:46 +000010217 CXXOperatorCallExpr *TheCall =
10218 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010219 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010220 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010221
John McCallb268a282010-08-23 23:25:46 +000010222 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010223 FnDecl))
10224 return ExprError();
10225
John McCallb268a282010-08-23 23:25:46 +000010226 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010227 } else {
10228 // We matched a built-in operator. Convert the arguments, then
10229 // break out so that we will build the appropriate built-in
10230 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010231 ExprResult ArgsRes0 =
10232 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10233 Best->Conversions[0], AA_Passing);
10234 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010235 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010236 Args[0] = ArgsRes0.take();
10237
10238 ExprResult ArgsRes1 =
10239 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10240 Best->Conversions[1], AA_Passing);
10241 if (ArgsRes1.isInvalid())
10242 return ExprError();
10243 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010244
10245 break;
10246 }
10247 }
10248
10249 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010250 if (CandidateSet.empty())
10251 Diag(LLoc, diag::err_ovl_no_oper)
10252 << Args[0]->getType() << /*subscript*/ 0
10253 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10254 else
10255 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10256 << Args[0]->getType()
10257 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010258 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010259 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010260 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010261 }
10262
10263 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010264 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010265 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010266 << Args[0]->getType() << Args[1]->getType()
10267 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010268 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010269 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010270 return ExprError();
10271
10272 case OR_Deleted:
10273 Diag(LLoc, diag::err_ovl_deleted_oper)
10274 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010275 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010276 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010277 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010278 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010279 return ExprError();
10280 }
10281
10282 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010283 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010284}
10285
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010286/// BuildCallToMemberFunction - Build a call to a member
10287/// function. MemExpr is the expression that refers to the member
10288/// function (and includes the object parameter), Args/NumArgs are the
10289/// arguments to the function call (not including the object
10290/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010291/// expression refers to a non-static member function or an overloaded
10292/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010293ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010294Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10295 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010296 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010297 assert(MemExprE->getType() == Context.BoundMemberTy ||
10298 MemExprE->getType() == Context.OverloadTy);
10299
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010300 // Dig out the member expression. This holds both the object
10301 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010302 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010303
John McCall0009fcc2011-04-26 20:42:42 +000010304 // Determine whether this is a call to a pointer-to-member function.
10305 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10306 assert(op->getType() == Context.BoundMemberTy);
10307 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10308
10309 QualType fnType =
10310 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10311
10312 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10313 QualType resultType = proto->getCallResultType(Context);
10314 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10315
10316 // Check that the object type isn't more qualified than the
10317 // member function we're calling.
10318 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10319
10320 QualType objectType = op->getLHS()->getType();
10321 if (op->getOpcode() == BO_PtrMemI)
10322 objectType = objectType->castAs<PointerType>()->getPointeeType();
10323 Qualifiers objectQuals = objectType.getQualifiers();
10324
10325 Qualifiers difference = objectQuals - funcQuals;
10326 difference.removeObjCGCAttr();
10327 difference.removeAddressSpace();
10328 if (difference) {
10329 std::string qualsString = difference.getAsString();
10330 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10331 << fnType.getUnqualifiedType()
10332 << qualsString
10333 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10334 }
10335
10336 CXXMemberCallExpr *call
10337 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10338 resultType, valueKind, RParenLoc);
10339
10340 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010341 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010342 call, 0))
10343 return ExprError();
10344
10345 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10346 return ExprError();
10347
10348 return MaybeBindToTemporary(call);
10349 }
10350
John McCall4124c492011-10-17 18:40:02 +000010351 UnbridgedCastsSet UnbridgedCasts;
10352 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10353 return ExprError();
10354
John McCall10eae182009-11-30 22:42:35 +000010355 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010356 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010357 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010358 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010359 if (isa<MemberExpr>(NakedMemExpr)) {
10360 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010361 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010362 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010363 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010364 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010365 } else {
10366 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010367 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010368
John McCall6e9f8f62009-12-03 04:06:58 +000010369 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010370 Expr::Classification ObjectClassification
10371 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10372 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010373
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010374 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010375 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010376
John McCall2d74de92009-12-01 22:10:20 +000010377 // FIXME: avoid copy.
10378 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10379 if (UnresExpr->hasExplicitTemplateArgs()) {
10380 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10381 TemplateArgs = &TemplateArgsBuffer;
10382 }
10383
John McCall10eae182009-11-30 22:42:35 +000010384 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10385 E = UnresExpr->decls_end(); I != E; ++I) {
10386
John McCall6e9f8f62009-12-03 04:06:58 +000010387 NamedDecl *Func = *I;
10388 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10389 if (isa<UsingShadowDecl>(Func))
10390 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10391
Douglas Gregor02824322011-01-26 19:30:28 +000010392
Francois Pichet64225792011-01-18 05:04:39 +000010393 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010394 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010395 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10396 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010397 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010398 // If explicit template arguments were provided, we can't call a
10399 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010400 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010401 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010402
John McCalla0296f72010-03-19 07:35:19 +000010403 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010404 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010405 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010406 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010407 } else {
John McCall10eae182009-11-30 22:42:35 +000010408 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010409 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010410 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010411 llvm::makeArrayRef(Args, NumArgs),
10412 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010413 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010414 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010415 }
Mike Stump11289f42009-09-09 15:08:12 +000010416
John McCall10eae182009-11-30 22:42:35 +000010417 DeclarationName DeclName = UnresExpr->getMemberName();
10418
John McCall4124c492011-10-17 18:40:02 +000010419 UnbridgedCasts.restore();
10420
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010421 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010422 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010423 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010424 case OR_Success:
10425 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010426 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010427 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010428 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010429 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010430 break;
10431
10432 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010433 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010434 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010435 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010436 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10437 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010438 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010439 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010440
10441 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010442 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010443 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010444 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10445 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010446 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010447 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010448
10449 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010450 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010451 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010452 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010453 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010454 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10456 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010457 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010458 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010459 }
10460
John McCall16df1e52010-03-30 21:47:33 +000010461 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010462
John McCall2d74de92009-12-01 22:10:20 +000010463 // If overload resolution picked a static member, build a
10464 // non-member call based on that function.
10465 if (Method->isStatic()) {
10466 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10467 Args, NumArgs, RParenLoc);
10468 }
10469
John McCall10eae182009-11-30 22:42:35 +000010470 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010471 }
10472
John McCall7decc9e2010-11-18 06:31:45 +000010473 QualType ResultType = Method->getResultType();
10474 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10475 ResultType = ResultType.getNonLValueExprType(Context);
10476
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010477 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010478 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010479 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010480 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010481
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010482 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010483 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010484 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010485 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010486
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010487 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010488 // We only need to do this if there was actually an overload; otherwise
10489 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010490 if (!Method->isStatic()) {
10491 ExprResult ObjectArg =
10492 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10493 FoundDecl, Method);
10494 if (ObjectArg.isInvalid())
10495 return ExprError();
10496 MemExpr->setBase(ObjectArg.take());
10497 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010498
10499 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010500 const FunctionProtoType *Proto =
10501 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010502 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010503 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010504 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010505
Eli Friedmanff4b4072012-02-18 04:48:30 +000010506 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10507
John McCallb268a282010-08-23 23:25:46 +000010508 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010509 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010510
Anders Carlsson47061ee2011-05-06 14:25:31 +000010511 if ((isa<CXXConstructorDecl>(CurContext) ||
10512 isa<CXXDestructorDecl>(CurContext)) &&
10513 TheCall->getMethodDecl()->isPure()) {
10514 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10515
Chandler Carruth59259262011-06-27 08:31:58 +000010516 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010517 Diag(MemExpr->getLocStart(),
10518 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10519 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10520 << MD->getParent()->getDeclName();
10521
10522 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010523 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010524 }
John McCallb268a282010-08-23 23:25:46 +000010525 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010526}
10527
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010528/// BuildCallToObjectOfClassType - Build a call to an object of class
10529/// type (C++ [over.call.object]), which can end up invoking an
10530/// overloaded function call operator (@c operator()) or performing a
10531/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010532ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010533Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010534 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010535 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010536 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010537 if (checkPlaceholderForOverload(*this, Obj))
10538 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010539 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010540
10541 UnbridgedCastsSet UnbridgedCasts;
10542 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10543 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010544
John Wiegley01296292011-04-08 18:41:53 +000010545 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10546 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010547
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010548 // C++ [over.call.object]p1:
10549 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010550 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010551 // candidate functions includes at least the function call
10552 // operators of T. The function call operators of T are obtained by
10553 // ordinary lookup of the name operator() in the context of
10554 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010555 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010556 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010557
John Wiegley01296292011-04-08 18:41:53 +000010558 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010559 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010560 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010561 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010562
John McCall27b18f82009-11-17 02:14:36 +000010563 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10564 LookupQualifiedName(R, Record->getDecl());
10565 R.suppressDiagnostics();
10566
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010567 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010568 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010569 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10570 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010571 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010573
Douglas Gregorab7897a2008-11-19 22:57:39 +000010574 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010575 // In addition, for each (non-explicit in C++0x) conversion function
10576 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010577 //
10578 // operator conversion-type-id () cv-qualifier;
10579 //
10580 // where cv-qualifier is the same cv-qualification as, or a
10581 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010582 // denotes the type "pointer to function of (P1,...,Pn) returning
10583 // R", or the type "reference to pointer to function of
10584 // (P1,...,Pn) returning R", or the type "reference to function
10585 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010586 // is also considered as a candidate function. Similarly,
10587 // surrogate call functions are added to the set of candidate
10588 // functions for each conversion function declared in an
10589 // accessible base class provided the function is not hidden
10590 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010591 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010592 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010593 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010594 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010595 NamedDecl *D = *I;
10596 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10597 if (isa<UsingShadowDecl>(D))
10598 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010599
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010600 // Skip over templated conversion functions; they aren't
10601 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010602 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010603 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010604
John McCall6e9f8f62009-12-03 04:06:58 +000010605 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010606 if (!Conv->isExplicit()) {
10607 // Strip the reference type (if any) and then the pointer type (if
10608 // any) to get down to what might be a function type.
10609 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10610 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10611 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010612
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010613 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10614 {
10615 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010616 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10617 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010618 }
10619 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010620 }
Mike Stump11289f42009-09-09 15:08:12 +000010621
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010622 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10623
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010624 // Perform overload resolution.
10625 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010626 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010627 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010628 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010629 // Overload resolution succeeded; we'll build the appropriate call
10630 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010631 break;
10632
10633 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010634 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010635 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010636 << Object.get()->getType() << /*call*/ 1
10637 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010638 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010639 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010640 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010641 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010642 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10643 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010644 break;
10645
10646 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010647 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010648 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010649 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010650 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10651 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010652 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010653
10654 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010655 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010656 diag::err_ovl_deleted_object_call)
10657 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010658 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010659 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010660 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10662 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010663 break;
Mike Stump11289f42009-09-09 15:08:12 +000010664 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010665
Douglas Gregorb412e172010-07-25 18:17:45 +000010666 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010667 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010668
John McCall4124c492011-10-17 18:40:02 +000010669 UnbridgedCasts.restore();
10670
Douglas Gregorab7897a2008-11-19 22:57:39 +000010671 if (Best->Function == 0) {
10672 // Since there is no function declaration, this is one of the
10673 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010674 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010675 = cast<CXXConversionDecl>(
10676 Best->Conversions[0].UserDefined.ConversionFunction);
10677
John Wiegley01296292011-04-08 18:41:53 +000010678 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010679 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010680
Douglas Gregorab7897a2008-11-19 22:57:39 +000010681 // We selected one of the surrogate functions that converts the
10682 // object parameter to a function pointer. Perform the conversion
10683 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010684
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010685 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010686 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010687 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10688 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010689 if (Call.isInvalid())
10690 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010691 // Record usage of conversion in an implicit cast.
10692 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10693 CK_UserDefinedConversion,
10694 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010695
Douglas Gregor668443e2011-01-20 00:18:04 +000010696 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010697 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010698 }
10699
Eli Friedmanfa0df832012-02-02 03:46:19 +000010700 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010701 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010702 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010703
Douglas Gregorab7897a2008-11-19 22:57:39 +000010704 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10705 // that calls this method, using Object for the implicit object
10706 // parameter and passing along the remaining arguments.
10707 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010708 const FunctionProtoType *Proto =
10709 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010710
10711 unsigned NumArgsInProto = Proto->getNumArgs();
10712 unsigned NumArgsToCheck = NumArgs;
10713
10714 // Build the full argument list for the method call (the
10715 // implicit object parameter is placed at the beginning of the
10716 // list).
10717 Expr **MethodArgs;
10718 if (NumArgs < NumArgsInProto) {
10719 NumArgsToCheck = NumArgsInProto;
10720 MethodArgs = new Expr*[NumArgsInProto + 1];
10721 } else {
10722 MethodArgs = new Expr*[NumArgs + 1];
10723 }
John Wiegley01296292011-04-08 18:41:53 +000010724 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010725 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10726 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010727
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010728 DeclarationNameInfo OpLocInfo(
10729 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10730 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010731 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010732 HadMultipleCandidates,
10733 OpLocInfo.getLoc(),
10734 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010735 if (NewFn.isInvalid())
10736 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010737
10738 // Once we've built TheCall, all of the expressions are properly
10739 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010740 QualType ResultTy = Method->getResultType();
10741 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10742 ResultTy = ResultTy.getNonLValueExprType(Context);
10743
John McCallb268a282010-08-23 23:25:46 +000010744 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010745 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010746 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010747 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010748 delete [] MethodArgs;
10749
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010750 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010751 Method))
10752 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010753
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010754 // We may have default arguments. If so, we need to allocate more
10755 // slots in the call for them.
10756 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010757 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010758 else if (NumArgs > NumArgsInProto)
10759 NumArgsToCheck = NumArgsInProto;
10760
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010761 bool IsError = false;
10762
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010763 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010764 ExprResult ObjRes =
10765 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10766 Best->FoundDecl, Method);
10767 if (ObjRes.isInvalid())
10768 IsError = true;
10769 else
10770 Object = move(ObjRes);
10771 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010772
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010773 // Check the argument types.
10774 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010775 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010776 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010777 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010778
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010779 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010780
John McCalldadc5752010-08-24 06:29:42 +000010781 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010782 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010783 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010784 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010785 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010786
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010787 IsError |= InputInit.isInvalid();
10788 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010789 } else {
John McCalldadc5752010-08-24 06:29:42 +000010790 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010791 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10792 if (DefArg.isInvalid()) {
10793 IsError = true;
10794 break;
10795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010796
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010797 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010798 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010799
10800 TheCall->setArg(i + 1, Arg);
10801 }
10802
10803 // If this is a variadic call, handle args passed through "...".
10804 if (Proto->isVariadic()) {
10805 // Promote the arguments (C99 6.5.2.2p7).
10806 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010807 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10808 IsError |= Arg.isInvalid();
10809 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010810 }
10811 }
10812
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010813 if (IsError) return true;
10814
Eli Friedmanff4b4072012-02-18 04:48:30 +000010815 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10816
John McCallb268a282010-08-23 23:25:46 +000010817 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010818 return true;
10819
John McCalle172be52010-08-24 06:09:16 +000010820 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010821}
10822
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010823/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010824/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010825/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010826ExprResult
John McCallb268a282010-08-23 23:25:46 +000010827Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010828 assert(Base->getType()->isRecordType() &&
10829 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010830
John McCall4124c492011-10-17 18:40:02 +000010831 if (checkPlaceholderForOverload(*this, Base))
10832 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010833
John McCallbc077cf2010-02-08 23:07:23 +000010834 SourceLocation Loc = Base->getExprLoc();
10835
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010836 // C++ [over.ref]p1:
10837 //
10838 // [...] An expression x->m is interpreted as (x.operator->())->m
10839 // for a class object x of type T if T::operator->() exists and if
10840 // the operator is selected as the best match function by the
10841 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010842 DeclarationName OpName =
10843 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010844 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010845 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010846
John McCallbc077cf2010-02-08 23:07:23 +000010847 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010848 PDiag(diag::err_typecheck_incomplete_tag)
10849 << Base->getSourceRange()))
10850 return ExprError();
10851
John McCall27b18f82009-11-17 02:14:36 +000010852 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10853 LookupQualifiedName(R, BaseRecord->getDecl());
10854 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010855
10856 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010857 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010858 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10859 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010860 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010861
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010862 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10863
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010864 // Perform overload resolution.
10865 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010866 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010867 case OR_Success:
10868 // Overload resolution succeeded; we'll build the call below.
10869 break;
10870
10871 case OR_No_Viable_Function:
10872 if (CandidateSet.empty())
10873 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010874 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010875 else
10876 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010877 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010878 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010879 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010880
10881 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010882 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10883 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010884 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010885 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010886
10887 case OR_Deleted:
10888 Diag(OpLoc, diag::err_ovl_deleted_oper)
10889 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010890 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010891 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010892 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010893 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010894 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010895 }
10896
Eli Friedmanfa0df832012-02-02 03:46:19 +000010897 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010898 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010899 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010900
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010901 // Convert the object parameter.
10902 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010903 ExprResult BaseResult =
10904 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10905 Best->FoundDecl, Method);
10906 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010907 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010908 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010909
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010910 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010911 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010912 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010913 if (FnExpr.isInvalid())
10914 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010915
John McCall7decc9e2010-11-18 06:31:45 +000010916 QualType ResultTy = Method->getResultType();
10917 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10918 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010919 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010920 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010921 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010922
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010923 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010924 Method))
10925 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010926
10927 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010928}
10929
Richard Smithbcc22fc2012-03-09 08:00:36 +000010930/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10931/// a literal operator described by the provided lookup results.
10932ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10933 DeclarationNameInfo &SuffixInfo,
10934 ArrayRef<Expr*> Args,
10935 SourceLocation LitEndLoc,
10936 TemplateArgumentListInfo *TemplateArgs) {
10937 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000010938
Richard Smithbcc22fc2012-03-09 08:00:36 +000010939 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10940 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10941 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000010942
Richard Smithbcc22fc2012-03-09 08:00:36 +000010943 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10944
Richard Smithbcc22fc2012-03-09 08:00:36 +000010945 // Perform overload resolution. This will usually be trivial, but might need
10946 // to perform substitutions for a literal operator template.
10947 OverloadCandidateSet::iterator Best;
10948 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
10949 case OR_Success:
10950 case OR_Deleted:
10951 break;
10952
10953 case OR_No_Viable_Function:
10954 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
10955 << R.getLookupName();
10956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10957 return ExprError();
10958
10959 case OR_Ambiguous:
10960 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
10961 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
10962 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000010963 }
10964
Richard Smithbcc22fc2012-03-09 08:00:36 +000010965 FunctionDecl *FD = Best->Function;
10966 MarkFunctionReferenced(UDSuffixLoc, FD);
10967 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000010968
Richard Smithbcc22fc2012-03-09 08:00:36 +000010969 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
10970 SuffixInfo.getLoc(),
10971 SuffixInfo.getInfo());
10972 if (Fn.isInvalid())
10973 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000010974
10975 // Check the argument types. This should almost always be a no-op, except
10976 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000010977 Expr *ConvArgs[2];
10978 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
10979 ExprResult InputInit = PerformCopyInitialization(
10980 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
10981 SourceLocation(), Args[ArgIdx]);
10982 if (InputInit.isInvalid())
10983 return true;
10984 ConvArgs[ArgIdx] = InputInit.take();
10985 }
10986
Richard Smithc67fdd42012-03-07 08:35:16 +000010987 QualType ResultTy = FD->getResultType();
10988 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10989 ResultTy = ResultTy.getNonLValueExprType(Context);
10990
Richard Smithc67fdd42012-03-07 08:35:16 +000010991 UserDefinedLiteral *UDL =
10992 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
10993 ResultTy, VK, LitEndLoc, UDSuffixLoc);
10994
10995 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
10996 return ExprError();
10997
10998 if (CheckFunctionCall(FD, UDL))
10999 return ExprError();
11000
11001 return MaybeBindToTemporary(UDL);
11002}
11003
Douglas Gregorcd695e52008-11-10 20:40:00 +000011004/// FixOverloadedFunctionReference - E is an expression that refers to
11005/// a C++ overloaded function (possibly with some parentheses and
11006/// perhaps a '&' around it). We have resolved the overloaded function
11007/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011008/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011009Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011010 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011011 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011012 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11013 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011014 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011015 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011016
Douglas Gregor51c538b2009-11-20 19:42:02 +000011017 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011018 }
11019
Douglas Gregor51c538b2009-11-20 19:42:02 +000011020 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011021 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11022 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011023 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011024 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011025 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011026 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011027 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011028 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011029
11030 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011031 ICE->getCastKind(),
11032 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011033 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011034 }
11035
Douglas Gregor51c538b2009-11-20 19:42:02 +000011036 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011037 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011038 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11040 if (Method->isStatic()) {
11041 // Do nothing: static member functions aren't any different
11042 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011043 } else {
John McCalle66edc12009-11-24 19:00:30 +000011044 // Fix the sub expression, which really has to be an
11045 // UnresolvedLookupExpr holding an overloaded member function
11046 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011047 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11048 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011049 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011050 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011051
John McCalld14a8642009-11-21 08:51:07 +000011052 assert(isa<DeclRefExpr>(SubExpr)
11053 && "fixed to something other than a decl ref");
11054 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11055 && "fixed to a member ref with no nested name qualifier");
11056
11057 // We have taken the address of a pointer to member
11058 // function. Perform the computation here so that we get the
11059 // appropriate pointer to member type.
11060 QualType ClassType
11061 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11062 QualType MemPtrType
11063 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11064
John McCall7decc9e2010-11-18 06:31:45 +000011065 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11066 VK_RValue, OK_Ordinary,
11067 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011068 }
11069 }
John McCall16df1e52010-03-30 21:47:33 +000011070 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11071 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011072 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011073 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011074
John McCalle3027922010-08-25 11:45:40 +000011075 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011076 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011077 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011078 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011079 }
John McCalld14a8642009-11-21 08:51:07 +000011080
11081 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011082 // FIXME: avoid copy.
11083 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011084 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011085 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11086 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011087 }
11088
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011089 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11090 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011091 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011092 Fn,
John McCall113bee02012-03-10 09:33:50 +000011093 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011094 ULE->getNameLoc(),
11095 Fn->getType(),
11096 VK_LValue,
11097 Found.getDecl(),
11098 TemplateArgs);
11099 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11100 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011101 }
11102
John McCall10eae182009-11-30 22:42:35 +000011103 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011104 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011105 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11106 if (MemExpr->hasExplicitTemplateArgs()) {
11107 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11108 TemplateArgs = &TemplateArgsBuffer;
11109 }
John McCall6b51f282009-11-23 01:53:49 +000011110
John McCall2d74de92009-12-01 22:10:20 +000011111 Expr *Base;
11112
John McCall7decc9e2010-11-18 06:31:45 +000011113 // If we're filling in a static method where we used to have an
11114 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011115 if (MemExpr->isImplicitAccess()) {
11116 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011117 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11118 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011119 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011120 Fn,
John McCall113bee02012-03-10 09:33:50 +000011121 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011122 MemExpr->getMemberLoc(),
11123 Fn->getType(),
11124 VK_LValue,
11125 Found.getDecl(),
11126 TemplateArgs);
11127 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11128 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011129 } else {
11130 SourceLocation Loc = MemExpr->getMemberLoc();
11131 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011132 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011133 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011134 Base = new (Context) CXXThisExpr(Loc,
11135 MemExpr->getBaseType(),
11136 /*isImplicit=*/true);
11137 }
John McCall2d74de92009-12-01 22:10:20 +000011138 } else
John McCallc3007a22010-10-26 07:05:15 +000011139 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011140
John McCall4adb38c2011-04-27 00:36:17 +000011141 ExprValueKind valueKind;
11142 QualType type;
11143 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11144 valueKind = VK_LValue;
11145 type = Fn->getType();
11146 } else {
11147 valueKind = VK_RValue;
11148 type = Context.BoundMemberTy;
11149 }
11150
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011151 MemberExpr *ME = MemberExpr::Create(Context, Base,
11152 MemExpr->isArrow(),
11153 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011154 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011155 Fn,
11156 Found,
11157 MemExpr->getMemberNameInfo(),
11158 TemplateArgs,
11159 type, valueKind, OK_Ordinary);
11160 ME->setHadMultipleCandidates(true);
11161 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011163
John McCallc3007a22010-10-26 07:05:15 +000011164 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011165}
11166
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011167ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011168 DeclAccessPair Found,
11169 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011170 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011171}
11172
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011173} // end namespace clang