blob: 3708f6c9d0865854084c5036ad8301a949220ec8 [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()){
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 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.
291NarrowingKind
292StandardConversionSequence::isNarrowing(ASTContext &Ctx, const Expr *Converted,
293 APValue &ConstantValue) const {
294 assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
295
296 // C++11 [dcl.init.list]p7:
297 // A narrowing conversion is an implicit conversion ...
298 QualType FromType = getToType(0);
299 QualType ToType = getToType(1);
300 switch (Second) {
301 // -- from a floating-point type to an integer type, or
302 //
303 // -- from an integer type or unscoped enumeration type to a floating-point
304 // type, except where the source is a constant expression and the actual
305 // value after conversion will fit into the target type and will produce
306 // the original value when converted back to the original type, or
307 case ICK_Floating_Integral:
308 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
309 return NK_Type_Narrowing;
310 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
311 llvm::APSInt IntConstantValue;
312 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
313 if (Initializer &&
314 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
315 // Convert the integer to the floating type.
316 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
317 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
318 llvm::APFloat::rmNearestTiesToEven);
319 // And back.
320 llvm::APSInt ConvertedValue = IntConstantValue;
321 bool ignored;
322 Result.convertToInteger(ConvertedValue,
323 llvm::APFloat::rmTowardZero, &ignored);
324 // If the resulting value is different, this was a narrowing conversion.
325 if (IntConstantValue != ConvertedValue) {
326 ConstantValue = APValue(IntConstantValue);
327 return NK_Constant_Narrowing;
328 }
329 } else {
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
332 }
333 }
334 return NK_Not_Narrowing;
335
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346 // Constant!
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
350 bool ignored;
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
356 if (ConvertStatus & llvm::APFloat::opOverflow)
357 return NK_Constant_Narrowing;
358 } else {
359 return NK_Variable_Narrowing;
360 }
361 }
362 return NK_Not_Narrowing;
363
364 // -- from an integer type or unscoped enumeration type to an integer type
365 // that cannot represent all the values of the original type, except where
366 // the source is a constant expression and the actual value after
367 // conversion will fit into the target type and will produce the original
368 // value when converted back to the original type.
369 case ICK_Boolean_Conversion: // Bools are integers too.
370 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
371 // Boolean conversions can be from pointers and pointers to members
372 // [conv.bool], and those aren't considered narrowing conversions.
373 return NK_Not_Narrowing;
374 } // Otherwise, fall through to the integral case.
375 case ICK_Integral_Conversion: {
376 assert(FromType->isIntegralOrUnscopedEnumerationType());
377 assert(ToType->isIntegralOrUnscopedEnumerationType());
378 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
379 const unsigned FromWidth = Ctx.getIntWidth(FromType);
380 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
381 const unsigned ToWidth = Ctx.getIntWidth(ToType);
382
383 if (FromWidth > ToWidth ||
384 (FromWidth == ToWidth && FromSigned != ToSigned)) {
385 // Not all values of FromType can be represented in ToType.
386 llvm::APSInt InitializerValue;
387 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
388 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
389 ConstantValue = APValue(InitializerValue);
390
391 // Add a bit to the InitializerValue so we don't have to worry about
392 // signed vs. unsigned comparisons.
393 InitializerValue = InitializerValue.extend(
394 InitializerValue.getBitWidth() + 1);
395 // Convert the initializer to and from the target width and signed-ness.
396 llvm::APSInt ConvertedValue = InitializerValue;
397 ConvertedValue = ConvertedValue.trunc(ToWidth);
398 ConvertedValue.setIsSigned(ToSigned);
399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400 ConvertedValue.setIsSigned(InitializerValue.isSigned());
401 // If the result is different, this was a narrowing conversion.
402 if (ConvertedValue != InitializerValue)
403 return NK_Constant_Narrowing;
404 } else {
405 // Variables are always narrowings.
406 return NK_Variable_Narrowing;
407 }
408 }
409 return NK_Not_Narrowing;
410 }
411
412 default:
413 // Other kinds of conversions are not narrowings.
414 return NK_Not_Narrowing;
415 }
416}
417
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418/// DebugPrint - Print this standard conversion sequence to standard
419/// error. Useful for debugging overloading issues.
420void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000421 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000422 bool PrintedSomething = false;
423 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000424 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000425 PrintedSomething = true;
426 }
427
428 if (Second != ICK_Identity) {
429 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000430 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000433
434 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000435 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000436 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000437 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000438 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 PrintedSomething = true;
442 }
443
444 if (Third != ICK_Identity) {
445 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454 }
455}
456
457/// DebugPrint - Print this user-defined conversion sequence to standard
458/// error. Useful for debugging overloading issues.
459void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000460 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 if (Before.First || Before.Second || Before.Third) {
462 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000465 if (ConversionFunction)
466 OS << '\'' << *ConversionFunction << '\'';
467 else
468 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000470 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471 After.DebugPrint();
472 }
473}
474
475/// DebugPrint - Print this implicit conversion sequence to standard
476/// error. Useful for debugging overloading issues.
477void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000478 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 switch (ConversionKind) {
480 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 Standard.DebugPrint();
483 break;
484 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486 UserDefined.DebugPrint();
487 break;
488 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 break;
John McCall0d1da222010-01-12 00:44:57 +0000491 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000492 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000493 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 break;
497 }
498
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500}
501
John McCall0d1da222010-01-12 00:44:57 +0000502void AmbiguousConversionSequence::construct() {
503 new (&conversions()) ConversionSet();
504}
505
506void AmbiguousConversionSequence::destruct() {
507 conversions().~ConversionSet();
508}
509
510void
511AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
512 FromTypePtr = O.FromTypePtr;
513 ToTypePtr = O.ToTypePtr;
514 new (&conversions()) ConversionSet(O.conversions());
515}
516
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000517namespace {
518 // Structure used by OverloadCandidate::DeductionFailureInfo to store
519 // template parameter and template argument information.
520 struct DFIParamWithArguments {
521 TemplateParameter Param;
522 TemplateArgument FirstArg;
523 TemplateArgument SecondArg;
524 };
525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527/// \brief Convert from Sema's representation of template deduction information
528/// to the form used in overload-candidate information.
529OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000530static MakeDeductionFailureInfo(ASTContext &Context,
531 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000532 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533 OverloadCandidate::DeductionFailureInfo Result;
534 Result.Result = static_cast<unsigned>(TDK);
535 Result.Data = 0;
536 switch (TDK) {
537 case Sema::TDK_Success:
538 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000539 case Sema::TDK_TooManyArguments:
540 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000543 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000544 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545 Result.Data = Info.Param.getOpaqueValue();
546 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000549 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000550 // FIXME: Should allocate from normal heap so that we can free this later.
551 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 Saved->Param = Info.Param;
553 Saved->FirstArg = Info.FirstArg;
554 Saved->SecondArg = Info.SecondArg;
555 Result.Data = Saved;
556 break;
557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000560 Result.Data = Info.take();
561 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 return Result;
569}
John McCall0d1da222010-01-12 00:44:57 +0000570
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571void OverloadCandidate::DeductionFailureInfo::Destroy() {
572 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
573 case Sema::TDK_Success:
574 case Sema::TDK_InstantiationDepth:
575 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000576 case Sema::TDK_TooManyArguments:
577 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000578 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000582 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000583 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 Data = 0;
585 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000586
587 case Sema::TDK_SubstitutionFailure:
588 // FIXME: Destroy the template arugment list?
589 Data = 0;
590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor461761d2010-05-08 18:20:53 +0000592 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000593 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
595 break;
596 }
597}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
599TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
601 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
602 case Sema::TDK_Success:
603 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000604 case Sema::TDK_TooManyArguments:
605 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000606 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000610 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000612
613 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000614 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000618 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000619 case Sema::TDK_FailedOverloadResolution:
620 break;
621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 return TemplateParameter();
624}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregord09efd42010-05-08 20:07:26 +0000626TemplateArgumentList *
627OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
628 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
629 case Sema::TDK_Success:
630 case Sema::TDK_InstantiationDepth:
631 case Sema::TDK_TooManyArguments:
632 case Sema::TDK_TooFewArguments:
633 case Sema::TDK_Incomplete:
634 case Sema::TDK_InvalidExplicitArguments:
635 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000636 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000637 return 0;
638
639 case Sema::TDK_SubstitutionFailure:
640 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Douglas Gregord09efd42010-05-08 20:07:26 +0000642 // Unhandled
643 case Sema::TDK_NonDeducedMismatch:
644 case Sema::TDK_FailedOverloadResolution:
645 break;
646 }
647
648 return 0;
649}
650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
652 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
653 case Sema::TDK_Success:
654 case Sema::TDK_InstantiationDepth:
655 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000656 case Sema::TDK_TooManyArguments:
657 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000659 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 return 0;
661
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000663 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665
Douglas Gregor461761d2010-05-08 18:20:53 +0000666 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 case Sema::TDK_FailedOverloadResolution:
669 break;
670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674
675const TemplateArgument *
676OverloadCandidate::DeductionFailureInfo::getSecondArg() {
677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678 case Sema::TDK_Success:
679 case Sema::TDK_InstantiationDepth:
680 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000681 case Sema::TDK_TooManyArguments:
682 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000684 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685 return 0;
686
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000687 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
690
Douglas Gregor461761d2010-05-08 18:20:53 +0000691 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 case Sema::TDK_FailedOverloadResolution:
694 break;
695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 return 0;
698}
699
700void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000701 for (iterator i = begin(), e = end(); i != e; ++i)
702 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
703 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000704 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000705 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 Functions.clear();
707}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708
John McCall4124c492011-10-17 18:40:02 +0000709namespace {
710 class UnbridgedCastsSet {
711 struct Entry {
712 Expr **Addr;
713 Expr *Saved;
714 };
715 SmallVector<Entry, 2> Entries;
716
717 public:
718 void save(Sema &S, Expr *&E) {
719 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
720 Entry entry = { &E, E };
721 Entries.push_back(entry);
722 E = S.stripARCUnbridgedCast(E);
723 }
724
725 void restore() {
726 for (SmallVectorImpl<Entry>::iterator
727 i = Entries.begin(), e = Entries.end(); i != e; ++i)
728 *i->Addr = i->Saved;
729 }
730 };
731}
732
733/// checkPlaceholderForOverload - Do any interesting placeholder-like
734/// preprocessing on the given expression.
735///
736/// \param unbridgedCasts a collection to which to add unbridged casts;
737/// without this, they will be immediately diagnosed as errors
738///
739/// Return true on unrecoverable error.
740static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
741 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000742 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
743 // We can't handle overloaded expressions here because overload
744 // resolution might reasonably tweak them.
745 if (placeholder->getKind() == BuiltinType::Overload) return false;
746
747 // If the context potentially accepts unbridged ARC casts, strip
748 // the unbridged cast and add it to the collection for later restoration.
749 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
750 unbridgedCasts) {
751 unbridgedCasts->save(S, E);
752 return false;
753 }
754
755 // Go ahead and check everything else.
756 ExprResult result = S.CheckPlaceholderExpr(E);
757 if (result.isInvalid())
758 return true;
759
760 E = result.take();
761 return false;
762 }
763
764 // Nothing to do.
765 return false;
766}
767
768/// checkArgPlaceholdersForOverload - Check a set of call operands for
769/// placeholders.
770static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
771 unsigned numArgs,
772 UnbridgedCastsSet &unbridged) {
773 for (unsigned i = 0; i != numArgs; ++i)
774 if (checkPlaceholderForOverload(S, args[i], &unbridged))
775 return true;
776
777 return false;
778}
779
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000780// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000781// overload of the declarations in Old. This routine returns false if
782// New and Old cannot be overloaded, e.g., if New has the same
783// signature as some function in Old (C++ 1.3.10) or if the Old
784// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000785// it does return false, MatchedDecl will point to the decl that New
786// cannot be overloaded with. This decl may be a UsingShadowDecl on
787// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000788//
789// Example: Given the following input:
790//
791// void f(int, float); // #1
792// void f(int, int); // #2
793// int f(int, int); // #3
794//
795// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000796// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797//
John McCall3d988d92009-12-02 08:47:38 +0000798// When we process #2, Old contains only the FunctionDecl for #1. By
799// comparing the parameter types, we see that #1 and #2 are overloaded
800// (since they have different signatures), so this routine returns
801// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802//
John McCall3d988d92009-12-02 08:47:38 +0000803// When we process #3, Old is an overload set containing #1 and #2. We
804// compare the signatures of #3 to #1 (they're overloaded, so we do
805// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
806// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000807// signature), IsOverload returns false and MatchedDecl will be set to
808// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000809//
810// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
811// into a class by a using declaration. The rules for whether to hide
812// shadow declarations ignore some properties which otherwise figure
813// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000814Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000815Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
816 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000817 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000818 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000819 NamedDecl *OldD = *I;
820
821 bool OldIsUsingDecl = false;
822 if (isa<UsingShadowDecl>(OldD)) {
823 OldIsUsingDecl = true;
824
825 // We can always introduce two using declarations into the same
826 // context, even if they have identical signatures.
827 if (NewIsUsingDecl) continue;
828
829 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
830 }
831
832 // If either declaration was introduced by a using declaration,
833 // we'll need to use slightly different rules for matching.
834 // Essentially, these rules are the normal rules, except that
835 // function templates hide function templates with different
836 // return types or template parameter lists.
837 bool UseMemberUsingDeclRules =
838 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
839
John McCall3d988d92009-12-02 08:47:38 +0000840 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000841 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
842 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
843 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
844 continue;
845 }
846
John McCalldaa3d6b2009-12-09 03:35:25 +0000847 Match = *I;
848 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849 }
John McCall3d988d92009-12-02 08:47:38 +0000850 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000851 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
852 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
853 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
854 continue;
855 }
856
John McCalldaa3d6b2009-12-09 03:35:25 +0000857 Match = *I;
858 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000859 }
John McCalla8987a2942010-11-10 03:01:53 +0000860 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000861 // We can overload with these, which can show up when doing
862 // redeclaration checks for UsingDecls.
863 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000864 } else if (isa<TagDecl>(OldD)) {
865 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000866 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
867 // Optimistically assume that an unresolved using decl will
868 // overload; if it doesn't, we'll have to diagnose during
869 // template instantiation.
870 } else {
John McCall1f82f242009-11-18 22:49:29 +0000871 // (C++ 13p1):
872 // Only function declarations can be overloaded; object and type
873 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000874 Match = *I;
875 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000876 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877 }
John McCall1f82f242009-11-18 22:49:29 +0000878
John McCalldaa3d6b2009-12-09 03:35:25 +0000879 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000880}
881
John McCalle9cccd82010-06-16 08:42:20 +0000882bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
883 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000884 // If both of the functions are extern "C", then they are not
885 // overloads.
886 if (Old->isExternC() && New->isExternC())
887 return false;
888
John McCall1f82f242009-11-18 22:49:29 +0000889 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
890 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
891
892 // C++ [temp.fct]p2:
893 // A function template can be overloaded with other function templates
894 // and with normal (non-template) functions.
895 if ((OldTemplate == 0) != (NewTemplate == 0))
896 return true;
897
898 // Is the function New an overload of the function Old?
899 QualType OldQType = Context.getCanonicalType(Old->getType());
900 QualType NewQType = Context.getCanonicalType(New->getType());
901
902 // Compare the signatures (C++ 1.3.10) of the two functions to
903 // determine whether they are overloads. If we find any mismatch
904 // in the signature, they are overloads.
905
906 // If either of these functions is a K&R-style function (no
907 // prototype), then we consider them to have matching signatures.
908 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
909 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
910 return false;
911
John McCall424cec92011-01-19 06:33:43 +0000912 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
913 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000914
915 // The signature of a function includes the types of its
916 // parameters (C++ 1.3.10), which includes the presence or absence
917 // of the ellipsis; see C++ DR 357).
918 if (OldQType != NewQType &&
919 (OldType->getNumArgs() != NewType->getNumArgs() ||
920 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000921 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000922 return true;
923
924 // C++ [temp.over.link]p4:
925 // The signature of a function template consists of its function
926 // signature, its return type and its template parameter list. The names
927 // of the template parameters are significant only for establishing the
928 // relationship between the template parameters and the rest of the
929 // signature.
930 //
931 // We check the return type and template parameter lists for function
932 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000933 //
934 // However, we don't consider either of these when deciding whether
935 // a member introduced by a shadow declaration is hidden.
936 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000937 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
938 OldTemplate->getTemplateParameters(),
939 false, TPL_TemplateMatch) ||
940 OldType->getResultType() != NewType->getResultType()))
941 return true;
942
943 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000944 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000945 //
946 // As part of this, also check whether one of the member functions
947 // is static, in which case they are not overloads (C++
948 // 13.1p2). While not part of the definition of the signature,
949 // this check is important to determine whether these functions
950 // can be overloaded.
951 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
952 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
953 if (OldMethod && NewMethod &&
954 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000955 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000956 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
957 if (!UseUsingDeclRules &&
958 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
959 (OldMethod->getRefQualifier() == RQ_None ||
960 NewMethod->getRefQualifier() == RQ_None)) {
961 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962 // - Member function declarations with the same name and the same
963 // parameter-type-list as well as member function template
964 // declarations with the same name, the same parameter-type-list, and
965 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000966 // them, but not all, have a ref-qualifier (8.3.5).
967 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
968 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
969 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971
John McCall1f82f242009-11-18 22:49:29 +0000972 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
John McCall1f82f242009-11-18 22:49:29 +0000975 // The signatures match; this is not an overload.
976 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977}
978
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000979/// \brief Checks availability of the function depending on the current
980/// function context. Inside an unavailable function, unavailability is ignored.
981///
982/// \returns true if \arg FD is unavailable and current context is inside
983/// an available function, false otherwise.
984bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
985 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
986}
987
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000988/// \brief Tries a user-defined conversion from From to ToType.
989///
990/// Produces an implicit conversion sequence for when a standard conversion
991/// is not an option. See TryImplicitConversion for more information.
992static ImplicitConversionSequence
993TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
994 bool SuppressUserConversions,
995 bool AllowExplicit,
996 bool InOverloadResolution,
997 bool CStyle,
998 bool AllowObjCWritebackConversion) {
999 ImplicitConversionSequence ICS;
1000
1001 if (SuppressUserConversions) {
1002 // We're not in the case above, so there is no conversion that
1003 // we can perform.
1004 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1005 return ICS;
1006 }
1007
1008 // Attempt user-defined conversion.
1009 OverloadCandidateSet Conversions(From->getExprLoc());
1010 OverloadingResult UserDefResult
1011 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1012 AllowExplicit);
1013
1014 if (UserDefResult == OR_Success) {
1015 ICS.setUserDefined();
1016 // C++ [over.ics.user]p4:
1017 // A conversion of an expression of class type to the same class
1018 // type is given Exact Match rank, and a conversion of an
1019 // expression of class type to a base class of that type is
1020 // given Conversion rank, in spite of the fact that a copy
1021 // constructor (i.e., a user-defined conversion function) is
1022 // called for those cases.
1023 if (CXXConstructorDecl *Constructor
1024 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1025 QualType FromCanon
1026 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1027 QualType ToCanon
1028 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1029 if (Constructor->isCopyConstructor() &&
1030 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1031 // Turn this into a "standard" conversion sequence, so that it
1032 // gets ranked with standard conversion sequences.
1033 ICS.setStandard();
1034 ICS.Standard.setAsIdentityConversion();
1035 ICS.Standard.setFromType(From->getType());
1036 ICS.Standard.setAllToTypes(ToType);
1037 ICS.Standard.CopyConstructor = Constructor;
1038 if (ToCanon != FromCanon)
1039 ICS.Standard.Second = ICK_Derived_To_Base;
1040 }
1041 }
1042
1043 // C++ [over.best.ics]p4:
1044 // However, when considering the argument of a user-defined
1045 // conversion function that is a candidate by 13.3.1.3 when
1046 // invoked for the copying of the temporary in the second step
1047 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1048 // 13.3.1.6 in all cases, only standard conversion sequences and
1049 // ellipsis conversion sequences are allowed.
1050 if (SuppressUserConversions && ICS.isUserDefined()) {
1051 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1052 }
1053 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1054 ICS.setAmbiguous();
1055 ICS.Ambiguous.setFromType(From->getType());
1056 ICS.Ambiguous.setToType(ToType);
1057 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1058 Cand != Conversions.end(); ++Cand)
1059 if (Cand->Viable)
1060 ICS.Ambiguous.addConversion(Cand->Function);
1061 } else {
1062 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1063 }
1064
1065 return ICS;
1066}
1067
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001068/// TryImplicitConversion - Attempt to perform an implicit conversion
1069/// from the given expression (Expr) to the given type (ToType). This
1070/// function returns an implicit conversion sequence that can be used
1071/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072///
1073/// void f(float f);
1074/// void g(int i) { f(i); }
1075///
1076/// this routine would produce an implicit conversion sequence to
1077/// describe the initialization of f from i, which will be a standard
1078/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1079/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1080//
1081/// Note that this routine only determines how the conversion can be
1082/// performed; it does not actually perform the conversion. As such,
1083/// it will not produce any diagnostics if no conversion is available,
1084/// but will instead return an implicit conversion sequence of kind
1085/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001086///
1087/// If @p SuppressUserConversions, then user-defined conversions are
1088/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001089/// If @p AllowExplicit, then explicit user-defined conversions are
1090/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001091///
1092/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1093/// writeback conversion, which allows __autoreleasing id* parameters to
1094/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001095static ImplicitConversionSequence
1096TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1097 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001099 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001100 bool CStyle,
1101 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001103 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001104 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001105 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001106 return ICS;
1107 }
1108
John McCall5c32be02010-08-24 20:38:10 +00001109 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001110 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001111 return ICS;
1112 }
1113
Douglas Gregor836a7e82010-08-11 02:15:33 +00001114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy/move
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 QualType FromType = From->getType();
1122 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001123 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1124 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001125 ICS.setStandard();
1126 ICS.Standard.setAsIdentityConversion();
1127 ICS.Standard.setFromType(FromType);
1128 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
Douglas Gregor5ab11652010-04-17 22:01:05 +00001130 // We don't actually check at this point whether there is a valid
1131 // copy/move constructor, since overloading just assumes that it
1132 // exists. When we actually perform initialization, we'll find the
1133 // appropriate constructor to copy the returned object, if needed.
1134 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
Douglas Gregor5ab11652010-04-17 22:01:05 +00001136 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001137 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001138 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregor836a7e82010-08-11 02:15:33 +00001140 return ICS;
1141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001143 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1144 AllowExplicit, InOverloadResolution, CStyle,
1145 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001146}
1147
John McCall31168b02011-06-15 23:02:42 +00001148ImplicitConversionSequence
1149Sema::TryImplicitConversion(Expr *From, QualType ToType,
1150 bool SuppressUserConversions,
1151 bool AllowExplicit,
1152 bool InOverloadResolution,
1153 bool CStyle,
1154 bool AllowObjCWritebackConversion) {
1155 return clang::TryImplicitConversion(*this, From, ToType,
1156 SuppressUserConversions, AllowExplicit,
1157 InOverloadResolution, CStyle,
1158 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001159}
1160
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001161/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001162/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001163/// converted expression. Flavor is the kind of conversion we're
1164/// performing, used in the error message. If @p AllowExplicit,
1165/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001166ExprResult
1167Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001168 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001169 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001170 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001171}
1172
John Wiegley01296292011-04-08 18:41:53 +00001173ExprResult
1174Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001175 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001176 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001177 if (checkPlaceholderForOverload(*this, From))
1178 return ExprError();
1179
John McCall31168b02011-06-15 23:02:42 +00001180 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1181 bool AllowObjCWritebackConversion
1182 = getLangOptions().ObjCAutoRefCount &&
1183 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001184
John McCall5c32be02010-08-24 20:38:10 +00001185 ICS = clang::TryImplicitConversion(*this, From, ToType,
1186 /*SuppressUserConversions=*/false,
1187 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001188 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001189 /*CStyle=*/false,
1190 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001191 return PerformImplicitConversion(From, ToType, ICS, Action);
1192}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193
1194/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001195/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001196bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1197 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001198 if (Context.hasSameUnqualifiedType(FromType, ToType))
1199 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001200
John McCall991eb4b2010-12-21 00:44:39 +00001201 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1202 // where F adds one of the following at most once:
1203 // - a pointer
1204 // - a member pointer
1205 // - a block pointer
1206 CanQualType CanTo = Context.getCanonicalType(ToType);
1207 CanQualType CanFrom = Context.getCanonicalType(FromType);
1208 Type::TypeClass TyClass = CanTo->getTypeClass();
1209 if (TyClass != CanFrom->getTypeClass()) return false;
1210 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1211 if (TyClass == Type::Pointer) {
1212 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1213 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1214 } else if (TyClass == Type::BlockPointer) {
1215 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1216 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1217 } else if (TyClass == Type::MemberPointer) {
1218 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1219 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1220 } else {
1221 return false;
1222 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001223
John McCall991eb4b2010-12-21 00:44:39 +00001224 TyClass = CanTo->getTypeClass();
1225 if (TyClass != CanFrom->getTypeClass()) return false;
1226 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1227 return false;
1228 }
1229
1230 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1231 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1232 if (!EInfo.getNoReturn()) return false;
1233
1234 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1235 assert(QualType(FromFn, 0).isCanonical());
1236 if (QualType(FromFn, 0) != CanTo) return false;
1237
1238 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001239 return true;
1240}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
Douglas Gregor46188682010-05-18 22:42:18 +00001242/// \brief Determine whether the conversion from FromType to ToType is a valid
1243/// vector conversion.
1244///
1245/// \param ICK Will be set to the vector conversion kind, if this is a vector
1246/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001247static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1248 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001249 // We need at least one of these types to be a vector type to have a vector
1250 // conversion.
1251 if (!ToType->isVectorType() && !FromType->isVectorType())
1252 return false;
1253
1254 // Identical types require no conversions.
1255 if (Context.hasSameUnqualifiedType(FromType, ToType))
1256 return false;
1257
1258 // There are no conversions between extended vector types, only identity.
1259 if (ToType->isExtVectorType()) {
1260 // There are no conversions between extended vector types other than the
1261 // identity conversion.
1262 if (FromType->isExtVectorType())
1263 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
Douglas Gregor46188682010-05-18 22:42:18 +00001265 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001266 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001267 ICK = ICK_Vector_Splat;
1268 return true;
1269 }
1270 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001271
1272 // We can perform the conversion between vector types in the following cases:
1273 // 1)vector types are equivalent AltiVec and GCC vector types
1274 // 2)lax vector conversions are permitted and the vector types are of the
1275 // same size
1276 if (ToType->isVectorType() && FromType->isVectorType()) {
1277 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001278 (Context.getLangOptions().LaxVectorConversions &&
1279 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001280 ICK = ICK_Vector_Conversion;
1281 return true;
1282 }
Douglas Gregor46188682010-05-18 22:42:18 +00001283 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001284
Douglas Gregor46188682010-05-18 22:42:18 +00001285 return false;
1286}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001288/// IsStandardConversion - Determines whether there is a standard
1289/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1290/// expression From to the type ToType. Standard conversion sequences
1291/// only consider non-class types; for conversions that involve class
1292/// types, use TryImplicitConversion. If a conversion exists, SCS will
1293/// contain the standard conversion sequence required to perform this
1294/// conversion and this routine will return true. Otherwise, this
1295/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001296static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1297 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001298 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001299 bool CStyle,
1300 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001301 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001303 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001304 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001305 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001306 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001307 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001308 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001309
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001310 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001311 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001312 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001313 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001314 return false;
1315
Mike Stump11289f42009-09-09 15:08:12 +00001316 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001317 }
1318
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 // The first conversion can be an lvalue-to-rvalue conversion,
1320 // array-to-pointer conversion, or function-to-pointer conversion
1321 // (C++ 4p1).
1322
John McCall5c32be02010-08-24 20:38:10 +00001323 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001324 DeclAccessPair AccessPair;
1325 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001326 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001327 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001328 // We were able to resolve the address of the overloaded function,
1329 // so we can convert to the type of that function.
1330 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001331
1332 // we can sometimes resolve &foo<int> regardless of ToType, so check
1333 // if the type matches (identity) or we are converting to bool
1334 if (!S.Context.hasSameUnqualifiedType(
1335 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1336 QualType resultTy;
1337 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001338 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001339 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1340 // otherwise, only a boolean conversion is standard
1341 if (!ToType->isBooleanType())
1342 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Chandler Carruthffce2452011-03-29 08:08:18 +00001345 // Check if the "from" expression is taking the address of an overloaded
1346 // function and recompute the FromType accordingly. Take advantage of the
1347 // fact that non-static member functions *must* have such an address-of
1348 // expression.
1349 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1350 if (Method && !Method->isStatic()) {
1351 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1352 "Non-unary operator on non-static member address");
1353 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1354 == UO_AddrOf &&
1355 "Non-address-of operator on non-static member address");
1356 const Type *ClassType
1357 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1358 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001359 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1360 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1361 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001362 "Non-address-of operator for overloaded function expression");
1363 FromType = S.Context.getPointerType(FromType);
1364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365
Douglas Gregor980fb162010-04-29 18:24:40 +00001366 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001367 assert(S.Context.hasSameType(
1368 FromType,
1369 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001370 } else {
1371 return false;
1372 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001373 }
John McCall154a2fd2011-08-30 00:57:29 +00001374 // Lvalue-to-rvalue conversion (C++11 4.1):
1375 // A glvalue (3.10) of a non-function, non-array type T can
1376 // be converted to a prvalue.
1377 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001378 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001379 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001380 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001381 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001382
1383 // If T is a non-class type, the type of the rvalue is the
1384 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001385 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1386 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001387 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001388 } else if (FromType->isArrayType()) {
1389 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001390 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001391
1392 // An lvalue or rvalue of type "array of N T" or "array of unknown
1393 // bound of T" can be converted to an rvalue of type "pointer to
1394 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001395 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001396
John McCall5c32be02010-08-24 20:38:10 +00001397 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001399 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
1401 // For the purpose of ranking in overload resolution
1402 // (13.3.3.1.1), this conversion is considered an
1403 // array-to-pointer conversion followed by a qualification
1404 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001405 SCS.Second = ICK_Identity;
1406 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001407 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001408 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001409 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410 }
John McCall086a4642010-11-24 05:12:34 +00001411 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001412 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001413 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001414
1415 // An lvalue of function type T can be converted to an rvalue of
1416 // type "pointer to T." The result is a pointer to the
1417 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001418 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001419 } else {
1420 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001421 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001422 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001423 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424
1425 // The second conversion can be an integral promotion, floating
1426 // point promotion, integral conversion, floating point conversion,
1427 // floating-integral conversion, pointer conversion,
1428 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001429 // For overloading in C, this can also be a "compatible-type"
1430 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001431 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001432 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001433 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001434 // The unqualified versions of the types are the same: there's no
1435 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001436 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001437 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001438 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001439 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001441 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001442 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001443 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001444 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001445 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001446 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001447 SCS.Second = ICK_Complex_Promotion;
1448 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001449 } else if (ToType->isBooleanType() &&
1450 (FromType->isArithmeticType() ||
1451 FromType->isAnyPointerType() ||
1452 FromType->isBlockPointerType() ||
1453 FromType->isMemberPointerType() ||
1454 FromType->isNullPtrType())) {
1455 // Boolean conversions (C++ 4.12).
1456 SCS.Second = ICK_Boolean_Conversion;
1457 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001458 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001459 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001460 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001461 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001462 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001463 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001464 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001465 SCS.Second = ICK_Complex_Conversion;
1466 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001467 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1468 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001469 // Complex-real conversions (C99 6.3.1.7)
1470 SCS.Second = ICK_Complex_Real;
1471 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001472 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001473 // Floating point conversions (C++ 4.8).
1474 SCS.Second = ICK_Floating_Conversion;
1475 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001477 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001478 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001479 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001480 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001481 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001483 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001484 SCS.Second = ICK_Block_Pointer_Conversion;
1485 } else if (AllowObjCWritebackConversion &&
1486 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1487 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001488 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1489 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001490 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001491 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001492 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001493 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001495 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001496 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001497 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001498 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001499 SCS.Second = SecondICK;
1500 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001501 } else if (!S.getLangOptions().CPlusPlus &&
1502 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001503 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001504 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001505 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001506 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001507 // Treat a conversion that strips "noreturn" as an identity conversion.
1508 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001509 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1510 InOverloadResolution,
1511 SCS, CStyle)) {
1512 SCS.Second = ICK_TransparentUnionConversion;
1513 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001514 } else {
1515 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001516 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001517 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001518 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001520 QualType CanonFrom;
1521 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001523 bool ObjCLifetimeConversion;
1524 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1525 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001527 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001529 CanonFrom = S.Context.getCanonicalType(FromType);
1530 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 } else {
1532 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 SCS.Third = ICK_Identity;
1534
Mike Stump11289f42009-09-09 15:08:12 +00001535 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 // [...] Any difference in top-level cv-qualification is
1537 // subsumed by the initialization itself and does not constitute
1538 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001539 CanonFrom = S.Context.getCanonicalType(FromType);
1540 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001542 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001543 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001544 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1545 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001546 FromType = ToType;
1547 CanonFrom = CanonTo;
1548 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001550 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551
1552 // If we have not converted the argument type to the parameter type,
1553 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001554 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001557 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001559
1560static bool
1561IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1562 QualType &ToType,
1563 bool InOverloadResolution,
1564 StandardConversionSequence &SCS,
1565 bool CStyle) {
1566
1567 const RecordType *UT = ToType->getAsUnionType();
1568 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1569 return false;
1570 // The field to initialize within the transparent union.
1571 RecordDecl *UD = UT->getDecl();
1572 // It's compatible if the expression matches any of the fields.
1573 for (RecordDecl::field_iterator it = UD->field_begin(),
1574 itend = UD->field_end();
1575 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001576 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1577 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001578 ToType = it->getType();
1579 return true;
1580 }
1581 }
1582 return false;
1583}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584
1585/// IsIntegralPromotion - Determines whether the conversion from the
1586/// expression From (whose potentially-adjusted type is FromType) to
1587/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1588/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001589bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001590 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001591 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001592 if (!To) {
1593 return false;
1594 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595
1596 // An rvalue of type char, signed char, unsigned char, short int, or
1597 // unsigned short int can be converted to an rvalue of type int if
1598 // int can represent all the values of the source type; otherwise,
1599 // the source rvalue can be converted to an rvalue of type unsigned
1600 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001601 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1602 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603 if (// We can promote any signed, promotable integer type to an int
1604 (FromType->isSignedIntegerType() ||
1605 // We can promote any unsigned integer type whose size is
1606 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001607 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001608 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001610 }
1611
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 return To->getKind() == BuiltinType::UInt;
1613 }
1614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 // C++0x [conv.prom]p3:
1616 // A prvalue of an unscoped enumeration type whose underlying type is not
1617 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1618 // following types that can represent all the values of the enumeration
1619 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1620 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001621 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001623 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624 // with lowest integer conversion rank (4.13) greater than the rank of long
1625 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001626 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001627 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1628 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1629 // provided for a scoped enumeration.
1630 if (FromEnumType->getDecl()->isScoped())
1631 return false;
1632
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001633 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001635 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001636 return Context.hasSameUnqualifiedType(ToType,
1637 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001638 }
John McCall56774992009-12-09 09:09:27 +00001639
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001640 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1642 // to an rvalue a prvalue of the first of the following types that can
1643 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001644 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001645 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001646 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001647 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001648 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001650 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001651 // Determine whether the type we're converting from is signed or
1652 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001653 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656 // The types we'll try to promote to, in the appropriate
1657 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001658 QualType PromoteTypes[6] = {
1659 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001660 Context.LongTy, Context.UnsignedLongTy ,
1661 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001663 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1665 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001666 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1668 // We found the type that we can promote to. If this is the
1669 // type we wanted, we have a promotion. Otherwise, no
1670 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001671 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672 }
1673 }
1674 }
1675
1676 // An rvalue for an integral bit-field (9.6) can be converted to an
1677 // rvalue of type int if int can represent all the values of the
1678 // bit-field; otherwise, it can be converted to unsigned int if
1679 // unsigned int can represent all the values of the bit-field. If
1680 // the bit-field is larger yet, no integral promotion applies to
1681 // it. If the bit-field has an enumerated type, it is treated as any
1682 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001683 // FIXME: We should delay checking of bit-fields until we actually perform the
1684 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001685 using llvm::APSInt;
1686 if (From)
1687 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001688 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001689 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001690 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1691 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1692 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001693
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001694 // Are we promoting to an int from a bitfield that fits in an int?
1695 if (BitWidth < ToSize ||
1696 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1697 return To->getKind() == BuiltinType::Int;
1698 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001700 // Are we promoting to an unsigned int from an unsigned bitfield
1701 // that fits into an unsigned int?
1702 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1703 return To->getKind() == BuiltinType::UInt;
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001706 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001707 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710 // An rvalue of type bool can be converted to an rvalue of type int,
1711 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001712 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001714 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715
1716 return false;
1717}
1718
1719/// IsFloatingPointPromotion - Determines whether the conversion from
1720/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1721/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001722bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001723 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1724 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001725 /// An rvalue of type float can be converted to an rvalue of type
1726 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 if (FromBuiltin->getKind() == BuiltinType::Float &&
1728 ToBuiltin->getKind() == BuiltinType::Double)
1729 return true;
1730
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001731 // C99 6.3.1.5p1:
1732 // When a float is promoted to double or long double, or a
1733 // double is promoted to long double [...].
1734 if (!getLangOptions().CPlusPlus &&
1735 (FromBuiltin->getKind() == BuiltinType::Float ||
1736 FromBuiltin->getKind() == BuiltinType::Double) &&
1737 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1738 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001739
1740 // Half can be promoted to float.
1741 if (FromBuiltin->getKind() == BuiltinType::Half &&
1742 ToBuiltin->getKind() == BuiltinType::Float)
1743 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001744 }
1745
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 return false;
1747}
1748
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001749/// \brief Determine if a conversion is a complex promotion.
1750///
1751/// A complex promotion is defined as a complex -> complex conversion
1752/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001753/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001754bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001755 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001756 if (!FromComplex)
1757 return false;
1758
John McCall9dd450b2009-09-21 23:43:11 +00001759 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001760 if (!ToComplex)
1761 return false;
1762
1763 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001764 ToComplex->getElementType()) ||
1765 IsIntegralPromotion(0, FromComplex->getElementType(),
1766 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001767}
1768
Douglas Gregor237f96c2008-11-26 23:31:11 +00001769/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1770/// the pointer type FromPtr to a pointer to type ToPointee, with the
1771/// same type qualifiers as FromPtr has on its pointee type. ToType,
1772/// if non-empty, will be a pointer to ToType that may or may not have
1773/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001774///
Mike Stump11289f42009-09-09 15:08:12 +00001775static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001776BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001777 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001778 ASTContext &Context,
1779 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001780 assert((FromPtr->getTypeClass() == Type::Pointer ||
1781 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1782 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783
John McCall31168b02011-06-15 23:02:42 +00001784 /// Conversions to 'id' subsume cv-qualifier conversions.
1785 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001786 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787
1788 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001790 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001791 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall31168b02011-06-15 23:02:42 +00001793 if (StripObjCLifetime)
1794 Quals.removeObjCLifetime();
1795
Mike Stump11289f42009-09-09 15:08:12 +00001796 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001797 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001798 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001799 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001800 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001801
1802 // Build a pointer to ToPointee. It has the right qualifiers
1803 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001804 if (isa<ObjCObjectPointerType>(ToType))
1805 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001806 return Context.getPointerType(ToPointee);
1807 }
1808
1809 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001810 QualType QualifiedCanonToPointee
1811 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001813 if (isa<ObjCObjectPointerType>(ToType))
1814 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1815 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001816}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001817
Mike Stump11289f42009-09-09 15:08:12 +00001818static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001819 bool InOverloadResolution,
1820 ASTContext &Context) {
1821 // Handle value-dependent integral null pointer constants correctly.
1822 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1823 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001824 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001825 return !InOverloadResolution;
1826
Douglas Gregor56751b52009-09-25 04:25:58 +00001827 return Expr->isNullPointerConstant(Context,
1828 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1829 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001830}
Mike Stump11289f42009-09-09 15:08:12 +00001831
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832/// IsPointerConversion - Determines whether the conversion of the
1833/// expression From, which has the (possibly adjusted) type FromType,
1834/// can be converted to the type ToType via a pointer conversion (C++
1835/// 4.10). If so, returns true and places the converted type (that
1836/// might differ from ToType in its cv-qualifiers at some level) into
1837/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001838///
Douglas Gregora29dc052008-11-27 01:19:21 +00001839/// This routine also supports conversions to and from block pointers
1840/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1841/// pointers to interfaces. FIXME: Once we've determined the
1842/// appropriate overloading rules for Objective-C, we may want to
1843/// split the Objective-C checks into a different routine; however,
1844/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001845/// conversions, so for now they live here. IncompatibleObjC will be
1846/// set if the conversion is an allowed Objective-C conversion that
1847/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001849 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001850 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001851 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001852 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001853 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1854 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001855 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001856
Mike Stump11289f42009-09-09 15:08:12 +00001857 // Conversion from a null pointer constant to any Objective-C pointer type.
1858 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001859 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001860 ConvertedType = ToType;
1861 return true;
1862 }
1863
Douglas Gregor231d1c62008-11-27 00:15:41 +00001864 // Blocks: Block pointers can be converted to void*.
1865 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001866 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001867 ConvertedType = ToType;
1868 return true;
1869 }
1870 // Blocks: A null pointer constant can be converted to a block
1871 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001872 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001873 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001874 ConvertedType = ToType;
1875 return true;
1876 }
1877
Sebastian Redl576fd422009-05-10 18:38:11 +00001878 // If the left-hand-side is nullptr_t, the right side can be a null
1879 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001880 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001881 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001882 ConvertedType = ToType;
1883 return true;
1884 }
1885
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001886 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001887 if (!ToTypePtr)
1888 return false;
1889
1890 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001891 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001892 ConvertedType = ToType;
1893 return true;
1894 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001895
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001897 // , including objective-c pointers.
1898 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001899 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1900 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001901 ConvertedType = BuildSimilarlyQualifiedPointerType(
1902 FromType->getAs<ObjCObjectPointerType>(),
1903 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001904 ToType, Context);
1905 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001906 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001907 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001908 if (!FromTypePtr)
1909 return false;
1910
1911 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001914 // pointer conversion, so don't do all of the work below.
1915 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1916 return false;
1917
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001918 // An rvalue of type "pointer to cv T," where T is an object type,
1919 // can be converted to an rvalue of type "pointer to cv void" (C++
1920 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001921 if (FromPointeeType->isIncompleteOrObjectType() &&
1922 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001923 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001924 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001925 ToType, Context,
1926 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927 return true;
1928 }
1929
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001930 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001931 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001932 ToPointeeType->isVoidType()) {
1933 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1934 ToPointeeType,
1935 ToType, Context);
1936 return true;
1937 }
1938
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001939 // When we're overloading in C, we allow a special kind of pointer
1940 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001941 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001942 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001943 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001944 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001945 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001946 return true;
1947 }
1948
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001950 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001951 // An rvalue of type "pointer to cv D," where D is a class type,
1952 // can be converted to an rvalue of type "pointer to cv B," where
1953 // B is a base class (clause 10) of D. If B is an inaccessible
1954 // (clause 11) or ambiguous (10.2) base class of D, a program that
1955 // necessitates this conversion is ill-formed. The result of the
1956 // conversion is a pointer to the base class sub-object of the
1957 // derived class object. The null pointer value is converted to
1958 // the null pointer value of the destination type.
1959 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001960 // Note that we do not check for ambiguity or inaccessibility
1961 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001962 if (getLangOptions().CPlusPlus &&
1963 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001964 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001965 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001966 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001968 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001969 ToType, Context);
1970 return true;
1971 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001972
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001973 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1974 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1976 ToPointeeType,
1977 ToType, Context);
1978 return true;
1979 }
1980
Douglas Gregora119f102008-12-19 19:13:09 +00001981 return false;
1982}
Douglas Gregoraec25842011-04-26 23:16:46 +00001983
1984/// \brief Adopt the given qualifiers for the given type.
1985static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1986 Qualifiers TQs = T.getQualifiers();
1987
1988 // Check whether qualifiers already match.
1989 if (TQs == Qs)
1990 return T;
1991
1992 if (Qs.compatiblyIncludes(TQs))
1993 return Context.getQualifiedType(T, Qs);
1994
1995 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1996}
Douglas Gregora119f102008-12-19 19:13:09 +00001997
1998/// isObjCPointerConversion - Determines whether this is an
1999/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2000/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002001bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002002 QualType& ConvertedType,
2003 bool &IncompatibleObjC) {
2004 if (!getLangOptions().ObjC1)
2005 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Douglas Gregoraec25842011-04-26 23:16:46 +00002007 // The set of qualifiers on the type we're converting from.
2008 Qualifiers FromQualifiers = FromType.getQualifiers();
2009
Steve Naroff7cae42b2009-07-10 23:34:53 +00002010 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002011 const ObjCObjectPointerType* ToObjCPtr =
2012 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002013 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002014 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002015
Steve Naroff7cae42b2009-07-10 23:34:53 +00002016 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002017 // If the pointee types are the same (ignoring qualifications),
2018 // then this is not a pointer conversion.
2019 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2020 FromObjCPtr->getPointeeType()))
2021 return false;
2022
Douglas Gregoraec25842011-04-26 23:16:46 +00002023 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002024 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002025 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002026 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002027 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002028 return true;
2029 }
2030 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002031 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002032 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002033 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002034 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002035 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002036 return true;
2037 }
2038 // Objective C++: We're able to convert from a pointer to an
2039 // interface to a pointer to a different interface.
2040 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002041 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2042 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2043 if (getLangOptions().CPlusPlus && LHS && RHS &&
2044 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2045 FromObjCPtr->getPointeeType()))
2046 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002048 ToObjCPtr->getPointeeType(),
2049 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002050 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002051 return true;
2052 }
2053
2054 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2055 // Okay: this is some kind of implicit downcast of Objective-C
2056 // interfaces, which is permitted. However, we're going to
2057 // complain about it.
2058 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002060 ToObjCPtr->getPointeeType(),
2061 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002062 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002063 return true;
2064 }
Mike Stump11289f42009-09-09 15:08:12 +00002065 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002066 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002067 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002069 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002071 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002072 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002073 // to a block pointer type.
2074 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002075 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002076 return true;
2077 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002078 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002081 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002083 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002084 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002085 return true;
2086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002087 else
Douglas Gregora119f102008-12-19 19:13:09 +00002088 return false;
2089
Douglas Gregor033f56d2008-12-23 00:53:59 +00002090 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002091 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002092 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002093 else if (const BlockPointerType *FromBlockPtr =
2094 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002095 FromPointeeType = FromBlockPtr->getPointeeType();
2096 else
Douglas Gregora119f102008-12-19 19:13:09 +00002097 return false;
2098
Douglas Gregora119f102008-12-19 19:13:09 +00002099 // If we have pointers to pointers, recursively check whether this
2100 // is an Objective-C conversion.
2101 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2102 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2103 IncompatibleObjC)) {
2104 // We always complain about this conversion.
2105 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002106 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002107 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002108 return true;
2109 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002110 // Allow conversion of pointee being objective-c pointer to another one;
2111 // as in I* to id.
2112 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2113 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2114 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2115 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002116
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002117 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002118 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002119 return true;
2120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor033f56d2008-12-23 00:53:59 +00002122 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002123 // differences in the argument and result types are in Objective-C
2124 // pointer conversions. If so, we permit the conversion (but
2125 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002126 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002127 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002128 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002129 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002130 if (FromFunctionType && ToFunctionType) {
2131 // If the function types are exactly the same, this isn't an
2132 // Objective-C pointer conversion.
2133 if (Context.getCanonicalType(FromPointeeType)
2134 == Context.getCanonicalType(ToPointeeType))
2135 return false;
2136
2137 // Perform the quick checks that will tell us whether these
2138 // function types are obviously different.
2139 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2140 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2141 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2142 return false;
2143
2144 bool HasObjCConversion = false;
2145 if (Context.getCanonicalType(FromFunctionType->getResultType())
2146 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2147 // Okay, the types match exactly. Nothing to do.
2148 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2149 ToFunctionType->getResultType(),
2150 ConvertedType, IncompatibleObjC)) {
2151 // Okay, we have an Objective-C pointer conversion.
2152 HasObjCConversion = true;
2153 } else {
2154 // Function types are too different. Abort.
2155 return false;
2156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Douglas Gregora119f102008-12-19 19:13:09 +00002158 // Check argument types.
2159 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2160 ArgIdx != NumArgs; ++ArgIdx) {
2161 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2162 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2163 if (Context.getCanonicalType(FromArgType)
2164 == Context.getCanonicalType(ToArgType)) {
2165 // Okay, the types match exactly. Nothing to do.
2166 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2167 ConvertedType, IncompatibleObjC)) {
2168 // Okay, we have an Objective-C pointer conversion.
2169 HasObjCConversion = true;
2170 } else {
2171 // Argument types are too different. Abort.
2172 return false;
2173 }
2174 }
2175
2176 if (HasObjCConversion) {
2177 // We had an Objective-C conversion. Allow this pointer
2178 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002180 IncompatibleObjC = true;
2181 return true;
2182 }
2183 }
2184
Sebastian Redl72b597d2009-01-25 19:43:20 +00002185 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002186}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187
John McCall31168b02011-06-15 23:02:42 +00002188/// \brief Determine whether this is an Objective-C writeback conversion,
2189/// used for parameter passing when performing automatic reference counting.
2190///
2191/// \param FromType The type we're converting form.
2192///
2193/// \param ToType The type we're converting to.
2194///
2195/// \param ConvertedType The type that will be produced after applying
2196/// this conversion.
2197bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2198 QualType &ConvertedType) {
2199 if (!getLangOptions().ObjCAutoRefCount ||
2200 Context.hasSameUnqualifiedType(FromType, ToType))
2201 return false;
2202
2203 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2204 QualType ToPointee;
2205 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2206 ToPointee = ToPointer->getPointeeType();
2207 else
2208 return false;
2209
2210 Qualifiers ToQuals = ToPointee.getQualifiers();
2211 if (!ToPointee->isObjCLifetimeType() ||
2212 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2213 !ToQuals.withoutObjCGLifetime().empty())
2214 return false;
2215
2216 // Argument must be a pointer to __strong to __weak.
2217 QualType FromPointee;
2218 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2219 FromPointee = FromPointer->getPointeeType();
2220 else
2221 return false;
2222
2223 Qualifiers FromQuals = FromPointee.getQualifiers();
2224 if (!FromPointee->isObjCLifetimeType() ||
2225 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2226 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2227 return false;
2228
2229 // Make sure that we have compatible qualifiers.
2230 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2231 if (!ToQuals.compatiblyIncludes(FromQuals))
2232 return false;
2233
2234 // Remove qualifiers from the pointee type we're converting from; they
2235 // aren't used in the compatibility check belong, and we'll be adding back
2236 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2237 FromPointee = FromPointee.getUnqualifiedType();
2238
2239 // The unqualified form of the pointee types must be compatible.
2240 ToPointee = ToPointee.getUnqualifiedType();
2241 bool IncompatibleObjC;
2242 if (Context.typesAreCompatible(FromPointee, ToPointee))
2243 FromPointee = ToPointee;
2244 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2245 IncompatibleObjC))
2246 return false;
2247
2248 /// \brief Construct the type we're converting to, which is a pointer to
2249 /// __autoreleasing pointee.
2250 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2251 ConvertedType = Context.getPointerType(FromPointee);
2252 return true;
2253}
2254
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002255bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2256 QualType& ConvertedType) {
2257 QualType ToPointeeType;
2258 if (const BlockPointerType *ToBlockPtr =
2259 ToType->getAs<BlockPointerType>())
2260 ToPointeeType = ToBlockPtr->getPointeeType();
2261 else
2262 return false;
2263
2264 QualType FromPointeeType;
2265 if (const BlockPointerType *FromBlockPtr =
2266 FromType->getAs<BlockPointerType>())
2267 FromPointeeType = FromBlockPtr->getPointeeType();
2268 else
2269 return false;
2270 // We have pointer to blocks, check whether the only
2271 // differences in the argument and result types are in Objective-C
2272 // pointer conversions. If so, we permit the conversion.
2273
2274 const FunctionProtoType *FromFunctionType
2275 = FromPointeeType->getAs<FunctionProtoType>();
2276 const FunctionProtoType *ToFunctionType
2277 = ToPointeeType->getAs<FunctionProtoType>();
2278
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002279 if (!FromFunctionType || !ToFunctionType)
2280 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002281
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002282 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002283 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002284
2285 // Perform the quick checks that will tell us whether these
2286 // function types are obviously different.
2287 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2288 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2289 return false;
2290
2291 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2292 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2293 if (FromEInfo != ToEInfo)
2294 return false;
2295
2296 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002297 if (Context.hasSameType(FromFunctionType->getResultType(),
2298 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002299 // Okay, the types match exactly. Nothing to do.
2300 } else {
2301 QualType RHS = FromFunctionType->getResultType();
2302 QualType LHS = ToFunctionType->getResultType();
2303 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2304 !RHS.hasQualifiers() && LHS.hasQualifiers())
2305 LHS = LHS.getUnqualifiedType();
2306
2307 if (Context.hasSameType(RHS,LHS)) {
2308 // OK exact match.
2309 } else if (isObjCPointerConversion(RHS, LHS,
2310 ConvertedType, IncompatibleObjC)) {
2311 if (IncompatibleObjC)
2312 return false;
2313 // Okay, we have an Objective-C pointer conversion.
2314 }
2315 else
2316 return false;
2317 }
2318
2319 // Check argument types.
2320 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2321 ArgIdx != NumArgs; ++ArgIdx) {
2322 IncompatibleObjC = false;
2323 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2324 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2325 if (Context.hasSameType(FromArgType, ToArgType)) {
2326 // Okay, the types match exactly. Nothing to do.
2327 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2328 ConvertedType, IncompatibleObjC)) {
2329 if (IncompatibleObjC)
2330 return false;
2331 // Okay, we have an Objective-C pointer conversion.
2332 } else
2333 // Argument types are too different. Abort.
2334 return false;
2335 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002336 if (LangOpts.ObjCAutoRefCount &&
2337 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2338 ToFunctionType))
2339 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002340
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002341 ConvertedType = ToType;
2342 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002343}
2344
Richard Trieucaff2472011-11-23 22:32:32 +00002345enum {
2346 ft_default,
2347 ft_different_class,
2348 ft_parameter_arity,
2349 ft_parameter_mismatch,
2350 ft_return_type,
2351 ft_qualifer_mismatch
2352};
2353
2354/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2355/// function types. Catches different number of parameter, mismatch in
2356/// parameter types, and different return types.
2357void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2358 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002359 // If either type is not valid, include no extra info.
2360 if (FromType.isNull() || ToType.isNull()) {
2361 PDiag << ft_default;
2362 return;
2363 }
2364
Richard Trieucaff2472011-11-23 22:32:32 +00002365 // Get the function type from the pointers.
2366 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2367 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2368 *ToMember = ToType->getAs<MemberPointerType>();
2369 if (FromMember->getClass() != ToMember->getClass()) {
2370 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2371 << QualType(FromMember->getClass(), 0);
2372 return;
2373 }
2374 FromType = FromMember->getPointeeType();
2375 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002376 }
2377
Richard Trieu96ed5b62011-12-13 23:19:45 +00002378 if (FromType->isPointerType())
2379 FromType = FromType->getPointeeType();
2380 if (ToType->isPointerType())
2381 ToType = ToType->getPointeeType();
2382
2383 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002384 FromType = FromType.getNonReferenceType();
2385 ToType = ToType.getNonReferenceType();
2386
Richard Trieucaff2472011-11-23 22:32:32 +00002387 // Don't print extra info for non-specialized template functions.
2388 if (FromType->isInstantiationDependentType() &&
2389 !FromType->getAs<TemplateSpecializationType>()) {
2390 PDiag << ft_default;
2391 return;
2392 }
2393
Richard Trieu96ed5b62011-12-13 23:19:45 +00002394 // No extra info for same types.
2395 if (Context.hasSameType(FromType, ToType)) {
2396 PDiag << ft_default;
2397 return;
2398 }
2399
Richard Trieucaff2472011-11-23 22:32:32 +00002400 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2401 *ToFunction = ToType->getAs<FunctionProtoType>();
2402
2403 // Both types need to be function types.
2404 if (!FromFunction || !ToFunction) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
2409 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2410 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2411 << FromFunction->getNumArgs();
2412 return;
2413 }
2414
2415 // Handle different parameter types.
2416 unsigned ArgPos;
2417 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2418 PDiag << ft_parameter_mismatch << ArgPos + 1
2419 << ToFunction->getArgType(ArgPos)
2420 << FromFunction->getArgType(ArgPos);
2421 return;
2422 }
2423
2424 // Handle different return type.
2425 if (!Context.hasSameType(FromFunction->getResultType(),
2426 ToFunction->getResultType())) {
2427 PDiag << ft_return_type << ToFunction->getResultType()
2428 << FromFunction->getResultType();
2429 return;
2430 }
2431
2432 unsigned FromQuals = FromFunction->getTypeQuals(),
2433 ToQuals = ToFunction->getTypeQuals();
2434 if (FromQuals != ToQuals) {
2435 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2436 return;
2437 }
2438
2439 // Unable to find a difference, so add no extra info.
2440 PDiag << ft_default;
2441}
2442
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002443/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002444/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002445/// they have same number of arguments. This routine assumes that Objective-C
2446/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002447/// If the parameters are different, ArgPos will have the the parameter index
2448/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002450 const FunctionProtoType *NewType,
2451 unsigned *ArgPos) {
2452 if (!getLangOptions().ObjC1) {
2453 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2454 N = NewType->arg_type_begin(),
2455 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2456 if (!Context.hasSameType(*O, *N)) {
2457 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2458 return false;
2459 }
2460 }
2461 return true;
2462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002464 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2465 N = NewType->arg_type_begin(),
2466 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2467 QualType ToType = (*O);
2468 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002469 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002470 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2471 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002472 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2473 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2474 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2475 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002476 continue;
2477 }
John McCall8b07ec22010-05-15 11:32:37 +00002478 else if (const ObjCObjectPointerType *PTTo =
2479 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002481 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002482 if (Context.hasSameUnqualifiedType(
2483 PTTo->getObjectType()->getBaseType(),
2484 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002485 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002486 }
Richard Trieucaff2472011-11-23 22:32:32 +00002487 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002488 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002489 }
2490 }
2491 return true;
2492}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002493
Douglas Gregor39c16d42008-10-24 04:54:22 +00002494/// CheckPointerConversion - Check the pointer conversion from the
2495/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002496/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002497/// conversions for which IsPointerConversion has already returned
2498/// true. It returns true and produces a diagnostic if there was an
2499/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002500bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002501 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002502 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002503 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002504 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002505 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002506
John McCall8cb679e2010-11-15 09:13:47 +00002507 Kind = CK_BitCast;
2508
Chandler Carruthffab8732011-04-09 07:32:05 +00002509 if (!IsCStyleOrFunctionalCast &&
2510 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2511 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2512 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002513 PDiag(diag::warn_impcast_bool_to_null_pointer)
2514 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002515
John McCall9320b872011-09-09 05:25:32 +00002516 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2517 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002518 QualType FromPointeeType = FromPtrType->getPointeeType(),
2519 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002520
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002521 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2522 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002523 // We must have a derived-to-base conversion. Check an
2524 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002525 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2526 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002527 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002528 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002529 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002531 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002532 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002533 }
2534 }
John McCall9320b872011-09-09 05:25:32 +00002535 } else if (const ObjCObjectPointerType *ToPtrType =
2536 ToType->getAs<ObjCObjectPointerType>()) {
2537 if (const ObjCObjectPointerType *FromPtrType =
2538 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002539 // Objective-C++ conversions are always okay.
2540 // FIXME: We should have a different class of conversions for the
2541 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002542 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002543 return false;
John McCall9320b872011-09-09 05:25:32 +00002544 } else if (FromType->isBlockPointerType()) {
2545 Kind = CK_BlockPointerToObjCPointerCast;
2546 } else {
2547 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002548 }
John McCall9320b872011-09-09 05:25:32 +00002549 } else if (ToType->isBlockPointerType()) {
2550 if (!FromType->isBlockPointerType())
2551 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002552 }
John McCall8cb679e2010-11-15 09:13:47 +00002553
2554 // We shouldn't fall into this case unless it's valid for other
2555 // reasons.
2556 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2557 Kind = CK_NullToPointer;
2558
Douglas Gregor39c16d42008-10-24 04:54:22 +00002559 return false;
2560}
2561
Sebastian Redl72b597d2009-01-25 19:43:20 +00002562/// IsMemberPointerConversion - Determines whether the conversion of the
2563/// expression From, which has the (possibly adjusted) type FromType, can be
2564/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2565/// If so, returns true and places the converted type (that might differ from
2566/// ToType in its cv-qualifiers at some level) into ConvertedType.
2567bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002569 bool InOverloadResolution,
2570 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002571 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002572 if (!ToTypePtr)
2573 return false;
2574
2575 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002576 if (From->isNullPointerConstant(Context,
2577 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2578 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002579 ConvertedType = ToType;
2580 return true;
2581 }
2582
2583 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002584 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002585 if (!FromTypePtr)
2586 return false;
2587
2588 // A pointer to member of B can be converted to a pointer to member of D,
2589 // where D is derived from B (C++ 4.11p2).
2590 QualType FromClass(FromTypePtr->getClass(), 0);
2591 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002592
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002593 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2594 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2595 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002596 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2597 ToClass.getTypePtr());
2598 return true;
2599 }
2600
2601 return false;
2602}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603
Sebastian Redl72b597d2009-01-25 19:43:20 +00002604/// CheckMemberPointerConversion - Check the member pointer conversion from the
2605/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002606/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002607/// for which IsMemberPointerConversion has already returned true. It returns
2608/// true and produces a diagnostic if there was an error, or returns false
2609/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002610bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002611 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002612 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002613 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002614 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002615 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002616 if (!FromPtrType) {
2617 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002619 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002620 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002621 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002622 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002623 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002624
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002625 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002626 assert(ToPtrType && "No member pointer cast has a target type "
2627 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002628
Sebastian Redled8f2002009-01-28 18:33:18 +00002629 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2630 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002631
Sebastian Redled8f2002009-01-28 18:33:18 +00002632 // FIXME: What about dependent types?
2633 assert(FromClass->isRecordType() && "Pointer into non-class.");
2634 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002635
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002636 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002637 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002638 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2639 assert(DerivationOkay &&
2640 "Should not have been called if derivation isn't OK.");
2641 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002642
Sebastian Redled8f2002009-01-28 18:33:18 +00002643 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2644 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002645 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2646 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2647 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2648 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002649 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002650
Douglas Gregor89ee6822009-02-28 01:32:25 +00002651 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002652 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2653 << FromClass << ToClass << QualType(VBase, 0)
2654 << From->getSourceRange();
2655 return true;
2656 }
2657
John McCall5b0829a2010-02-10 09:31:12 +00002658 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002659 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2660 Paths.front(),
2661 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002662
Anders Carlssond7923c62009-08-22 23:33:40 +00002663 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002664 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002665 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002666 return false;
2667}
2668
Douglas Gregor9a657932008-10-21 23:43:52 +00002669/// IsQualificationConversion - Determines whether the conversion from
2670/// an rvalue of type FromType to ToType is a qualification conversion
2671/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002672///
2673/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2674/// when the qualification conversion involves a change in the Objective-C
2675/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002676bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002678 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002679 FromType = Context.getCanonicalType(FromType);
2680 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002681 ObjCLifetimeConversion = false;
2682
Douglas Gregor9a657932008-10-21 23:43:52 +00002683 // If FromType and ToType are the same type, this is not a
2684 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002685 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002686 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002687
Douglas Gregor9a657932008-10-21 23:43:52 +00002688 // (C++ 4.4p4):
2689 // A conversion can add cv-qualifiers at levels other than the first
2690 // in multi-level pointers, subject to the following rules: [...]
2691 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002692 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002693 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002694 // Within each iteration of the loop, we check the qualifiers to
2695 // determine if this still looks like a qualification
2696 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002697 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002698 // until there are no more pointers or pointers-to-members left to
2699 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002700 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002701
Douglas Gregor90609aa2011-04-25 18:40:17 +00002702 Qualifiers FromQuals = FromType.getQualifiers();
2703 Qualifiers ToQuals = ToType.getQualifiers();
2704
John McCall31168b02011-06-15 23:02:42 +00002705 // Objective-C ARC:
2706 // Check Objective-C lifetime conversions.
2707 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2708 UnwrappedAnyPointer) {
2709 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2710 ObjCLifetimeConversion = true;
2711 FromQuals.removeObjCLifetime();
2712 ToQuals.removeObjCLifetime();
2713 } else {
2714 // Qualification conversions cannot cast between different
2715 // Objective-C lifetime qualifiers.
2716 return false;
2717 }
2718 }
2719
Douglas Gregorf30053d2011-05-08 06:09:53 +00002720 // Allow addition/removal of GC attributes but not changing GC attributes.
2721 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2722 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2723 FromQuals.removeObjCGCAttr();
2724 ToQuals.removeObjCGCAttr();
2725 }
2726
Douglas Gregor9a657932008-10-21 23:43:52 +00002727 // -- for every j > 0, if const is in cv 1,j then const is in cv
2728 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002729 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002730 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002731
Douglas Gregor9a657932008-10-21 23:43:52 +00002732 // -- if the cv 1,j and cv 2,j are different, then const is in
2733 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002734 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002735 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002737
Douglas Gregor9a657932008-10-21 23:43:52 +00002738 // Keep track of whether all prior cv-qualifiers in the "to" type
2739 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002740 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002741 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002742 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002743
2744 // We are left with FromType and ToType being the pointee types
2745 // after unwrapping the original FromType and ToType the same number
2746 // of types. If we unwrapped any pointers, and if FromType and
2747 // ToType have the same unqualified type (since we checked
2748 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002749 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002750}
2751
Douglas Gregor576e98c2009-01-30 23:27:23 +00002752/// Determines whether there is a user-defined conversion sequence
2753/// (C++ [over.ics.user]) that converts expression From to the type
2754/// ToType. If such a conversion exists, User will contain the
2755/// user-defined conversion sequence that performs such a conversion
2756/// and this routine will return true. Otherwise, this routine returns
2757/// false and User is unspecified.
2758///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002759/// \param AllowExplicit true if the conversion should consider C++0x
2760/// "explicit" conversion functions as well as non-explicit conversion
2761/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002762static OverloadingResult
2763IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2764 UserDefinedConversionSequence& User,
2765 OverloadCandidateSet& CandidateSet,
2766 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002767 // Whether we will only visit constructors.
2768 bool ConstructorsOnly = false;
2769
2770 // If the type we are conversion to is a class type, enumerate its
2771 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002772 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002773 // C++ [over.match.ctor]p1:
2774 // When objects of class type are direct-initialized (8.5), or
2775 // copy-initialized from an expression of the same or a
2776 // derived class type (8.5), overload resolution selects the
2777 // constructor. [...] For copy-initialization, the candidate
2778 // functions are all the converting constructors (12.3.1) of
2779 // that class. The argument list is the expression-list within
2780 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002781 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002782 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002783 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002784 ConstructorsOnly = true;
2785
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002786 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2787 // RequireCompleteType may have returned true due to some invalid decl
2788 // during template instantiation, but ToType may be complete enough now
2789 // to try to recover.
2790 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002791 // We're not going to find any constructors.
2792 } else if (CXXRecordDecl *ToRecordDecl
2793 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002794
2795 Expr **Args = &From;
2796 unsigned NumArgs = 1;
2797 bool ListInitializing = false;
2798 // If we're list-initializing, we pass the individual elements as
2799 // arguments, not the entire list.
2800 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2801 Args = InitList->getInits();
2802 NumArgs = InitList->getNumInits();
2803 ListInitializing = true;
2804 }
2805
Douglas Gregor89ee6822009-02-28 01:32:25 +00002806 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002807 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002808 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002809 NamedDecl *D = *Con;
2810 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2811
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002812 // Find the constructor (which may be a template).
2813 CXXConstructorDecl *Constructor = 0;
2814 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002815 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002816 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002817 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002818 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2819 else
John McCalla0296f72010-03-19 07:35:19 +00002820 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002822 bool Usable = !Constructor->isInvalidDecl();
2823 if (ListInitializing)
2824 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2825 else
2826 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2827 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002828 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002829 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2830 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002831 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002832 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002833 !ConstructorsOnly &&
2834 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002835 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002836 // Allow one user-defined conversion when user specifies a
2837 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002838 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002839 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002840 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002841 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002842 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002843 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002844 }
2845 }
2846
Douglas Gregor5ab11652010-04-17 22:01:05 +00002847 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002848 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002849 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2850 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002851 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002852 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002853 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002854 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002855 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2856 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002857 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002858 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002859 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002860 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002861 DeclAccessPair FoundDecl = I.getPair();
2862 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002863 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2864 if (isa<UsingShadowDecl>(D))
2865 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2866
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002867 CXXConversionDecl *Conv;
2868 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002869 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2870 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002871 else
John McCallda4458e2010-03-31 01:36:47 +00002872 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002873
2874 if (AllowExplicit || !Conv->isExplicit()) {
2875 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002876 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2877 ActingContext, From, ToType,
2878 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002879 else
John McCall5c32be02010-08-24 20:38:10 +00002880 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2881 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002882 }
2883 }
2884 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002885 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002886
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002887 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2888
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002889 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002890 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002891 case OR_Success:
2892 // Record the standard conversion we used and the conversion function.
2893 if (CXXConstructorDecl *Constructor
2894 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002895 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2896
John McCall5c32be02010-08-24 20:38:10 +00002897 // C++ [over.ics.user]p1:
2898 // If the user-defined conversion is specified by a
2899 // constructor (12.3.1), the initial standard conversion
2900 // sequence converts the source type to the type required by
2901 // the argument of the constructor.
2902 //
2903 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002904 if (isa<InitListExpr>(From)) {
2905 // Initializer lists don't have conversions as such.
2906 User.Before.setAsIdentityConversion();
2907 } else {
2908 if (Best->Conversions[0].isEllipsis())
2909 User.EllipsisConversion = true;
2910 else {
2911 User.Before = Best->Conversions[0].Standard;
2912 User.EllipsisConversion = false;
2913 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002914 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002915 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002916 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002917 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002918 User.After.setAsIdentityConversion();
2919 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2920 User.After.setAllToTypes(ToType);
2921 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00002922 }
2923 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00002924 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002925 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2926
John McCall5c32be02010-08-24 20:38:10 +00002927 // C++ [over.ics.user]p1:
2928 //
2929 // [...] If the user-defined conversion is specified by a
2930 // conversion function (12.3.2), the initial standard
2931 // conversion sequence converts the source type to the
2932 // implicit object parameter of the conversion function.
2933 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002934 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002935 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002936 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002937 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002938
John McCall5c32be02010-08-24 20:38:10 +00002939 // C++ [over.ics.user]p2:
2940 // The second standard conversion sequence converts the
2941 // result of the user-defined conversion to the target type
2942 // for the sequence. Since an implicit conversion sequence
2943 // is an initialization, the special rules for
2944 // initialization by user-defined conversion apply when
2945 // selecting the best user-defined conversion for a
2946 // user-defined conversion sequence (see 13.3.3 and
2947 // 13.3.3.1).
2948 User.After = Best->FinalConversion;
2949 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002950 }
David Blaikie8a40f702012-01-17 06:56:22 +00002951 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002952
John McCall5c32be02010-08-24 20:38:10 +00002953 case OR_No_Viable_Function:
2954 return OR_No_Viable_Function;
2955 case OR_Deleted:
2956 // No conversion here! We're done.
2957 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958
John McCall5c32be02010-08-24 20:38:10 +00002959 case OR_Ambiguous:
2960 return OR_Ambiguous;
2961 }
2962
David Blaikie8a40f702012-01-17 06:56:22 +00002963 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002964}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002966bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002967Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002968 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002969 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002971 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002972 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002973 if (OvResult == OR_Ambiguous)
2974 Diag(From->getSourceRange().getBegin(),
2975 diag::err_typecheck_ambiguous_condition)
2976 << From->getType() << ToType << From->getSourceRange();
2977 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2978 Diag(From->getSourceRange().getBegin(),
2979 diag::err_typecheck_nonviable_condition)
2980 << From->getType() << ToType << From->getSourceRange();
2981 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002982 return false;
John McCall5c32be02010-08-24 20:38:10 +00002983 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002985}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002986
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002987/// CompareImplicitConversionSequences - Compare two implicit
2988/// conversion sequences to determine whether one is better than the
2989/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002990static ImplicitConversionSequence::CompareKind
2991CompareImplicitConversionSequences(Sema &S,
2992 const ImplicitConversionSequence& ICS1,
2993 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002994{
2995 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2996 // conversion sequences (as defined in 13.3.3.1)
2997 // -- a standard conversion sequence (13.3.3.1.1) is a better
2998 // conversion sequence than a user-defined conversion sequence or
2999 // an ellipsis conversion sequence, and
3000 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3001 // conversion sequence than an ellipsis conversion sequence
3002 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003003 //
John McCall0d1da222010-01-12 00:44:57 +00003004 // C++0x [over.best.ics]p10:
3005 // For the purpose of ranking implicit conversion sequences as
3006 // described in 13.3.3.2, the ambiguous conversion sequence is
3007 // treated as a user-defined sequence that is indistinguishable
3008 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003009 if (ICS1.getKindRank() < ICS2.getKindRank())
3010 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003011 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003012 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003013
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003014 // The following checks require both conversion sequences to be of
3015 // the same kind.
3016 if (ICS1.getKind() != ICS2.getKind())
3017 return ImplicitConversionSequence::Indistinguishable;
3018
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003019 ImplicitConversionSequence::CompareKind Result =
3020 ImplicitConversionSequence::Indistinguishable;
3021
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003022 // Two implicit conversion sequences of the same form are
3023 // indistinguishable conversion sequences unless one of the
3024 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003025 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003026 Result = CompareStandardConversionSequences(S,
3027 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003028 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003029 // User-defined conversion sequence U1 is a better conversion
3030 // sequence than another user-defined conversion sequence U2 if
3031 // they contain the same user-defined conversion function or
3032 // constructor and if the second standard conversion sequence of
3033 // U1 is better than the second standard conversion sequence of
3034 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003035 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003036 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003037 Result = CompareStandardConversionSequences(S,
3038 ICS1.UserDefined.After,
3039 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003040 }
3041
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003042 // List-initialization sequence L1 is a better conversion sequence than
3043 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3044 // for some X and L2 does not.
3045 if (Result == ImplicitConversionSequence::Indistinguishable &&
3046 ICS1.isListInitializationSequence() &&
3047 ICS2.isListInitializationSequence()) {
3048 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3049 }
3050
3051 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003052}
3053
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003054static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3055 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3056 Qualifiers Quals;
3057 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003061 return Context.hasSameUnqualifiedType(T1, T2);
3062}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003064// Per 13.3.3.2p3, compare the given standard conversion sequences to
3065// determine if one is a proper subset of the other.
3066static ImplicitConversionSequence::CompareKind
3067compareStandardConversionSubsets(ASTContext &Context,
3068 const StandardConversionSequence& SCS1,
3069 const StandardConversionSequence& SCS2) {
3070 ImplicitConversionSequence::CompareKind Result
3071 = ImplicitConversionSequence::Indistinguishable;
3072
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003074 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003075 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3076 return ImplicitConversionSequence::Better;
3077 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3078 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003080 if (SCS1.Second != SCS2.Second) {
3081 if (SCS1.Second == ICK_Identity)
3082 Result = ImplicitConversionSequence::Better;
3083 else if (SCS2.Second == ICK_Identity)
3084 Result = ImplicitConversionSequence::Worse;
3085 else
3086 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003087 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003088 return ImplicitConversionSequence::Indistinguishable;
3089
3090 if (SCS1.Third == SCS2.Third) {
3091 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3092 : ImplicitConversionSequence::Indistinguishable;
3093 }
3094
3095 if (SCS1.Third == ICK_Identity)
3096 return Result == ImplicitConversionSequence::Worse
3097 ? ImplicitConversionSequence::Indistinguishable
3098 : ImplicitConversionSequence::Better;
3099
3100 if (SCS2.Third == ICK_Identity)
3101 return Result == ImplicitConversionSequence::Better
3102 ? ImplicitConversionSequence::Indistinguishable
3103 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003105 return ImplicitConversionSequence::Indistinguishable;
3106}
3107
Douglas Gregore696ebb2011-01-26 14:52:12 +00003108/// \brief Determine whether one of the given reference bindings is better
3109/// than the other based on what kind of bindings they are.
3110static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3111 const StandardConversionSequence &SCS2) {
3112 // C++0x [over.ics.rank]p3b4:
3113 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3114 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003116 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003118 // reference*.
3119 //
3120 // FIXME: Rvalue references. We're going rogue with the above edits,
3121 // because the semantics in the current C++0x working paper (N3225 at the
3122 // time of this writing) break the standard definition of std::forward
3123 // and std::reference_wrapper when dealing with references to functions.
3124 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003125 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3126 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3127 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
Douglas Gregore696ebb2011-01-26 14:52:12 +00003129 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3130 SCS2.IsLvalueReference) ||
3131 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3132 !SCS2.IsLvalueReference);
3133}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003135/// CompareStandardConversionSequences - Compare two standard
3136/// conversion sequences to determine whether one is better than the
3137/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003138static ImplicitConversionSequence::CompareKind
3139CompareStandardConversionSequences(Sema &S,
3140 const StandardConversionSequence& SCS1,
3141 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003142{
3143 // Standard conversion sequence S1 is a better conversion sequence
3144 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3145
3146 // -- S1 is a proper subsequence of S2 (comparing the conversion
3147 // sequences in the canonical form defined by 13.3.3.1.1,
3148 // excluding any Lvalue Transformation; the identity conversion
3149 // sequence is considered to be a subsequence of any
3150 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003151 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003152 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003153 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003154
3155 // -- the rank of S1 is better than the rank of S2 (by the rules
3156 // defined below), or, if not that,
3157 ImplicitConversionRank Rank1 = SCS1.getRank();
3158 ImplicitConversionRank Rank2 = SCS2.getRank();
3159 if (Rank1 < Rank2)
3160 return ImplicitConversionSequence::Better;
3161 else if (Rank2 < Rank1)
3162 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003163
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003164 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3165 // are indistinguishable unless one of the following rules
3166 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003167
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003168 // A conversion that is not a conversion of a pointer, or
3169 // pointer to member, to bool is better than another conversion
3170 // that is such a conversion.
3171 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3172 return SCS2.isPointerConversionToBool()
3173 ? ImplicitConversionSequence::Better
3174 : ImplicitConversionSequence::Worse;
3175
Douglas Gregor5c407d92008-10-23 00:40:37 +00003176 // C++ [over.ics.rank]p4b2:
3177 //
3178 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003179 // conversion of B* to A* is better than conversion of B* to
3180 // void*, and conversion of A* to void* is better than conversion
3181 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003182 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003183 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003184 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003185 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003186 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3187 // Exactly one of the conversion sequences is a conversion to
3188 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003189 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3190 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003191 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3192 // Neither conversion sequence converts to a void pointer; compare
3193 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003194 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003195 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003196 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003197 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3198 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003199 // Both conversion sequences are conversions to void
3200 // pointers. Compare the source types to determine if there's an
3201 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003202 QualType FromType1 = SCS1.getFromType();
3203 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003204
3205 // Adjust the types we're converting from via the array-to-pointer
3206 // conversion, if we need to.
3207 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003208 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003209 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003210 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003211
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003212 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3213 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003214
John McCall5c32be02010-08-24 20:38:10 +00003215 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003216 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003217 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003218 return ImplicitConversionSequence::Worse;
3219
3220 // Objective-C++: If one interface is more specific than the
3221 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003222 const ObjCObjectPointerType* FromObjCPtr1
3223 = FromType1->getAs<ObjCObjectPointerType>();
3224 const ObjCObjectPointerType* FromObjCPtr2
3225 = FromType2->getAs<ObjCObjectPointerType>();
3226 if (FromObjCPtr1 && FromObjCPtr2) {
3227 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3228 FromObjCPtr2);
3229 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3230 FromObjCPtr1);
3231 if (AssignLeft != AssignRight) {
3232 return AssignLeft? ImplicitConversionSequence::Better
3233 : ImplicitConversionSequence::Worse;
3234 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003235 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003236 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003237
3238 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3239 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003240 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003241 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003242 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003243
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003244 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003245 // Check for a better reference binding based on the kind of bindings.
3246 if (isBetterReferenceBindingKind(SCS1, SCS2))
3247 return ImplicitConversionSequence::Better;
3248 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3249 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250
Sebastian Redlb28b4072009-03-22 23:49:27 +00003251 // C++ [over.ics.rank]p3b4:
3252 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3253 // which the references refer are the same type except for
3254 // top-level cv-qualifiers, and the type to which the reference
3255 // initialized by S2 refers is more cv-qualified than the type
3256 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003257 QualType T1 = SCS1.getToType(2);
3258 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003259 T1 = S.Context.getCanonicalType(T1);
3260 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003261 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003262 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3263 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003264 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003265 // Objective-C++ ARC: If the references refer to objects with different
3266 // lifetimes, prefer bindings that don't change lifetime.
3267 if (SCS1.ObjCLifetimeConversionBinding !=
3268 SCS2.ObjCLifetimeConversionBinding) {
3269 return SCS1.ObjCLifetimeConversionBinding
3270 ? ImplicitConversionSequence::Worse
3271 : ImplicitConversionSequence::Better;
3272 }
3273
Chandler Carruth8e543b32010-12-12 08:17:55 +00003274 // If the type is an array type, promote the element qualifiers to the
3275 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003276 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003277 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003278 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003279 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003280 if (T2.isMoreQualifiedThan(T1))
3281 return ImplicitConversionSequence::Better;
3282 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003283 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003284 }
3285 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003286
Francois Pichet08d2fa02011-09-18 21:37:37 +00003287 // In Microsoft mode, prefer an integral conversion to a
3288 // floating-to-integral conversion if the integral conversion
3289 // is between types of the same size.
3290 // For example:
3291 // void f(float);
3292 // void f(int);
3293 // int main {
3294 // long a;
3295 // f(a);
3296 // }
3297 // Here, MSVC will call f(int) instead of generating a compile error
3298 // as clang will do in standard mode.
3299 if (S.getLangOptions().MicrosoftMode &&
3300 SCS1.Second == ICK_Integral_Conversion &&
3301 SCS2.Second == ICK_Floating_Integral &&
3302 S.Context.getTypeSize(SCS1.getFromType()) ==
3303 S.Context.getTypeSize(SCS1.getToType(2)))
3304 return ImplicitConversionSequence::Better;
3305
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003306 return ImplicitConversionSequence::Indistinguishable;
3307}
3308
3309/// CompareQualificationConversions - Compares two standard conversion
3310/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003311/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3312ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003313CompareQualificationConversions(Sema &S,
3314 const StandardConversionSequence& SCS1,
3315 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003316 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003317 // -- S1 and S2 differ only in their qualification conversion and
3318 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3319 // cv-qualification signature of type T1 is a proper subset of
3320 // the cv-qualification signature of type T2, and S1 is not the
3321 // deprecated string literal array-to-pointer conversion (4.2).
3322 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3323 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3324 return ImplicitConversionSequence::Indistinguishable;
3325
3326 // FIXME: the example in the standard doesn't use a qualification
3327 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003328 QualType T1 = SCS1.getToType(2);
3329 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003330 T1 = S.Context.getCanonicalType(T1);
3331 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003332 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003333 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3334 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003335
3336 // If the types are the same, we won't learn anything by unwrapped
3337 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003338 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003339 return ImplicitConversionSequence::Indistinguishable;
3340
Chandler Carruth607f38e2009-12-29 07:16:59 +00003341 // If the type is an array type, promote the element qualifiers to the type
3342 // for comparison.
3343 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003344 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003345 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003346 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003347
Mike Stump11289f42009-09-09 15:08:12 +00003348 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003349 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003350
3351 // Objective-C++ ARC:
3352 // Prefer qualification conversions not involving a change in lifetime
3353 // to qualification conversions that do not change lifetime.
3354 if (SCS1.QualificationIncludesObjCLifetime !=
3355 SCS2.QualificationIncludesObjCLifetime) {
3356 Result = SCS1.QualificationIncludesObjCLifetime
3357 ? ImplicitConversionSequence::Worse
3358 : ImplicitConversionSequence::Better;
3359 }
3360
John McCall5c32be02010-08-24 20:38:10 +00003361 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003362 // Within each iteration of the loop, we check the qualifiers to
3363 // determine if this still looks like a qualification
3364 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003365 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003366 // until there are no more pointers or pointers-to-members left
3367 // to unwrap. This essentially mimics what
3368 // IsQualificationConversion does, but here we're checking for a
3369 // strict subset of qualifiers.
3370 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3371 // The qualifiers are the same, so this doesn't tell us anything
3372 // about how the sequences rank.
3373 ;
3374 else if (T2.isMoreQualifiedThan(T1)) {
3375 // T1 has fewer qualifiers, so it could be the better sequence.
3376 if (Result == ImplicitConversionSequence::Worse)
3377 // Neither has qualifiers that are a subset of the other's
3378 // qualifiers.
3379 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003381 Result = ImplicitConversionSequence::Better;
3382 } else if (T1.isMoreQualifiedThan(T2)) {
3383 // T2 has fewer qualifiers, so it could be the better sequence.
3384 if (Result == ImplicitConversionSequence::Better)
3385 // Neither has qualifiers that are a subset of the other's
3386 // qualifiers.
3387 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003389 Result = ImplicitConversionSequence::Worse;
3390 } else {
3391 // Qualifiers are disjoint.
3392 return ImplicitConversionSequence::Indistinguishable;
3393 }
3394
3395 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003396 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003397 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003398 }
3399
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003400 // Check that the winning standard conversion sequence isn't using
3401 // the deprecated string literal array to pointer conversion.
3402 switch (Result) {
3403 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003404 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003405 Result = ImplicitConversionSequence::Indistinguishable;
3406 break;
3407
3408 case ImplicitConversionSequence::Indistinguishable:
3409 break;
3410
3411 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003412 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003413 Result = ImplicitConversionSequence::Indistinguishable;
3414 break;
3415 }
3416
3417 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003418}
3419
Douglas Gregor5c407d92008-10-23 00:40:37 +00003420/// CompareDerivedToBaseConversions - Compares two standard conversion
3421/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003422/// various kinds of derived-to-base conversions (C++
3423/// [over.ics.rank]p4b3). As part of these checks, we also look at
3424/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003425ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003426CompareDerivedToBaseConversions(Sema &S,
3427 const StandardConversionSequence& SCS1,
3428 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003429 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003430 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003431 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003432 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003433
3434 // Adjust the types we're converting from via the array-to-pointer
3435 // conversion, if we need to.
3436 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003437 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003438 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003439 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003440
3441 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003442 FromType1 = S.Context.getCanonicalType(FromType1);
3443 ToType1 = S.Context.getCanonicalType(ToType1);
3444 FromType2 = S.Context.getCanonicalType(FromType2);
3445 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003446
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003447 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003448 //
3449 // If class B is derived directly or indirectly from class A and
3450 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003451 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003452 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003453 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003454 SCS2.Second == ICK_Pointer_Conversion &&
3455 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3456 FromType1->isPointerType() && FromType2->isPointerType() &&
3457 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003458 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003460 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003462 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003464 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003466
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003467 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003468 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003469 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003470 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003471 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003472 return ImplicitConversionSequence::Worse;
3473 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003474
3475 // -- conversion of B* to A* is better than conversion of C* to A*,
3476 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003477 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003478 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003479 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003480 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003481 }
3482 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3483 SCS2.Second == ICK_Pointer_Conversion) {
3484 const ObjCObjectPointerType *FromPtr1
3485 = FromType1->getAs<ObjCObjectPointerType>();
3486 const ObjCObjectPointerType *FromPtr2
3487 = FromType2->getAs<ObjCObjectPointerType>();
3488 const ObjCObjectPointerType *ToPtr1
3489 = ToType1->getAs<ObjCObjectPointerType>();
3490 const ObjCObjectPointerType *ToPtr2
3491 = ToType2->getAs<ObjCObjectPointerType>();
3492
3493 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3494 // Apply the same conversion ranking rules for Objective-C pointer types
3495 // that we do for C++ pointers to class types. However, we employ the
3496 // Objective-C pseudo-subtyping relationship used for assignment of
3497 // Objective-C pointer types.
3498 bool FromAssignLeft
3499 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3500 bool FromAssignRight
3501 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3502 bool ToAssignLeft
3503 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3504 bool ToAssignRight
3505 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3506
3507 // A conversion to an a non-id object pointer type or qualified 'id'
3508 // type is better than a conversion to 'id'.
3509 if (ToPtr1->isObjCIdType() &&
3510 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3511 return ImplicitConversionSequence::Worse;
3512 if (ToPtr2->isObjCIdType() &&
3513 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3514 return ImplicitConversionSequence::Better;
3515
3516 // A conversion to a non-id object pointer type is better than a
3517 // conversion to a qualified 'id' type
3518 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3519 return ImplicitConversionSequence::Worse;
3520 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3521 return ImplicitConversionSequence::Better;
3522
3523 // A conversion to an a non-Class object pointer type or qualified 'Class'
3524 // type is better than a conversion to 'Class'.
3525 if (ToPtr1->isObjCClassType() &&
3526 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3527 return ImplicitConversionSequence::Worse;
3528 if (ToPtr2->isObjCClassType() &&
3529 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3530 return ImplicitConversionSequence::Better;
3531
3532 // A conversion to a non-Class object pointer type is better than a
3533 // conversion to a qualified 'Class' type.
3534 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3535 return ImplicitConversionSequence::Worse;
3536 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3537 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003538
Douglas Gregor058d3de2011-01-31 18:51:41 +00003539 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3540 if (S.Context.hasSameType(FromType1, FromType2) &&
3541 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3542 (ToAssignLeft != ToAssignRight))
3543 return ToAssignLeft? ImplicitConversionSequence::Worse
3544 : ImplicitConversionSequence::Better;
3545
3546 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3547 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3548 (FromAssignLeft != FromAssignRight))
3549 return FromAssignLeft? ImplicitConversionSequence::Better
3550 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003551 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003552 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003553
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003554 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003555 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3556 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3557 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003559 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003561 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003563 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003565 ToType2->getAs<MemberPointerType>();
3566 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3567 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3568 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3569 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3570 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3571 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3572 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3573 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003574 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003575 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003576 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003577 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003578 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003579 return ImplicitConversionSequence::Better;
3580 }
3581 // conversion of B::* to C::* is better than conversion of A::* to C::*
3582 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003583 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003584 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003585 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003586 return ImplicitConversionSequence::Worse;
3587 }
3588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Douglas Gregor5ab11652010-04-17 22:01:05 +00003590 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003591 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003592 // -- binding of an expression of type C to a reference of type
3593 // B& is better than binding an expression of type C to a
3594 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003595 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3596 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3597 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003598 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003599 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003600 return ImplicitConversionSequence::Worse;
3601 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003602
Douglas Gregor2fe98832008-11-03 19:09:14 +00003603 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003604 // -- binding of an expression of type B to a reference of type
3605 // A& is better than binding an expression of type C to a
3606 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003607 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3608 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3609 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003610 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003611 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003612 return ImplicitConversionSequence::Worse;
3613 }
3614 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003615
Douglas Gregor5c407d92008-10-23 00:40:37 +00003616 return ImplicitConversionSequence::Indistinguishable;
3617}
3618
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003619/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3620/// determine whether they are reference-related,
3621/// reference-compatible, reference-compatible with added
3622/// qualification, or incompatible, for use in C++ initialization by
3623/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3624/// type, and the first type (T1) is the pointee type of the reference
3625/// type being initialized.
3626Sema::ReferenceCompareResult
3627Sema::CompareReferenceRelationship(SourceLocation Loc,
3628 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003629 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003630 bool &ObjCConversion,
3631 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003632 assert(!OrigT1->isReferenceType() &&
3633 "T1 must be the pointee type of the reference type");
3634 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3635
3636 QualType T1 = Context.getCanonicalType(OrigT1);
3637 QualType T2 = Context.getCanonicalType(OrigT2);
3638 Qualifiers T1Quals, T2Quals;
3639 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3640 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3641
3642 // C++ [dcl.init.ref]p4:
3643 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3644 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3645 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003646 DerivedToBase = false;
3647 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003648 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003649 if (UnqualT1 == UnqualT2) {
3650 // Nothing to do.
3651 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003652 IsDerivedFrom(UnqualT2, UnqualT1))
3653 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003654 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3655 UnqualT2->isObjCObjectOrInterfaceType() &&
3656 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3657 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003658 else
3659 return Ref_Incompatible;
3660
3661 // At this point, we know that T1 and T2 are reference-related (at
3662 // least).
3663
3664 // If the type is an array type, promote the element qualifiers to the type
3665 // for comparison.
3666 if (isa<ArrayType>(T1) && T1Quals)
3667 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3668 if (isa<ArrayType>(T2) && T2Quals)
3669 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3670
3671 // C++ [dcl.init.ref]p4:
3672 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3673 // reference-related to T2 and cv1 is the same cv-qualification
3674 // as, or greater cv-qualification than, cv2. For purposes of
3675 // overload resolution, cases for which cv1 is greater
3676 // cv-qualification than cv2 are identified as
3677 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003678 //
3679 // Note that we also require equivalence of Objective-C GC and address-space
3680 // qualifiers when performing these computations, so that e.g., an int in
3681 // address space 1 is not reference-compatible with an int in address
3682 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003683 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3684 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3685 T1Quals.removeObjCLifetime();
3686 T2Quals.removeObjCLifetime();
3687 ObjCLifetimeConversion = true;
3688 }
3689
Douglas Gregord517d552011-04-28 17:56:11 +00003690 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003691 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003692 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003693 return Ref_Compatible_With_Added_Qualification;
3694 else
3695 return Ref_Related;
3696}
3697
Douglas Gregor836a7e82010-08-11 02:15:33 +00003698/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003699/// with DeclType. Return true if something definite is found.
3700static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003701FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3702 QualType DeclType, SourceLocation DeclLoc,
3703 Expr *Init, QualType T2, bool AllowRvalues,
3704 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003705 assert(T2->isRecordType() && "Can only find conversions of record types.");
3706 CXXRecordDecl *T2RecordDecl
3707 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3708
3709 OverloadCandidateSet CandidateSet(DeclLoc);
3710 const UnresolvedSetImpl *Conversions
3711 = T2RecordDecl->getVisibleConversionFunctions();
3712 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3713 E = Conversions->end(); I != E; ++I) {
3714 NamedDecl *D = *I;
3715 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3716 if (isa<UsingShadowDecl>(D))
3717 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3718
3719 FunctionTemplateDecl *ConvTemplate
3720 = dyn_cast<FunctionTemplateDecl>(D);
3721 CXXConversionDecl *Conv;
3722 if (ConvTemplate)
3723 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3724 else
3725 Conv = cast<CXXConversionDecl>(D);
3726
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003728 // explicit conversions, skip it.
3729 if (!AllowExplicit && Conv->isExplicit())
3730 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003731
Douglas Gregor836a7e82010-08-11 02:15:33 +00003732 if (AllowRvalues) {
3733 bool DerivedToBase = false;
3734 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003735 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003736
3737 // If we are initializing an rvalue reference, don't permit conversion
3738 // functions that return lvalues.
3739 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3740 const ReferenceType *RefType
3741 = Conv->getConversionType()->getAs<LValueReferenceType>();
3742 if (RefType && !RefType->getPointeeType()->isFunctionType())
3743 continue;
3744 }
3745
Douglas Gregor836a7e82010-08-11 02:15:33 +00003746 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003747 S.CompareReferenceRelationship(
3748 DeclLoc,
3749 Conv->getConversionType().getNonReferenceType()
3750 .getUnqualifiedType(),
3751 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003752 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003753 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003754 continue;
3755 } else {
3756 // If the conversion function doesn't return a reference type,
3757 // it can't be considered for this conversion. An rvalue reference
3758 // is only acceptable if its referencee is a function type.
3759
3760 const ReferenceType *RefType =
3761 Conv->getConversionType()->getAs<ReferenceType>();
3762 if (!RefType ||
3763 (!RefType->isLValueReferenceType() &&
3764 !RefType->getPointeeType()->isFunctionType()))
3765 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Douglas Gregor836a7e82010-08-11 02:15:33 +00003768 if (ConvTemplate)
3769 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003770 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003771 else
3772 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003773 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003774 }
3775
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003776 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3777
Sebastian Redld92badf2010-06-30 18:13:39 +00003778 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003779 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003780 case OR_Success:
3781 // C++ [over.ics.ref]p1:
3782 //
3783 // [...] If the parameter binds directly to the result of
3784 // applying a conversion function to the argument
3785 // expression, the implicit conversion sequence is a
3786 // user-defined conversion sequence (13.3.3.1.2), with the
3787 // second standard conversion sequence either an identity
3788 // conversion or, if the conversion function returns an
3789 // entity of a type that is a derived class of the parameter
3790 // type, a derived-to-base Conversion.
3791 if (!Best->FinalConversion.DirectBinding)
3792 return false;
3793
Chandler Carruth30141632011-02-25 19:41:05 +00003794 if (Best->Function)
3795 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003796 ICS.setUserDefined();
3797 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3798 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003799 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003800 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003801 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003802 ICS.UserDefined.EllipsisConversion = false;
3803 assert(ICS.UserDefined.After.ReferenceBinding &&
3804 ICS.UserDefined.After.DirectBinding &&
3805 "Expected a direct reference binding!");
3806 return true;
3807
3808 case OR_Ambiguous:
3809 ICS.setAmbiguous();
3810 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3811 Cand != CandidateSet.end(); ++Cand)
3812 if (Cand->Viable)
3813 ICS.Ambiguous.addConversion(Cand->Function);
3814 return true;
3815
3816 case OR_No_Viable_Function:
3817 case OR_Deleted:
3818 // There was no suitable conversion, or we found a deleted
3819 // conversion; continue with other checks.
3820 return false;
3821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
David Blaikie8a40f702012-01-17 06:56:22 +00003823 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003824}
3825
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003826/// \brief Compute an implicit conversion sequence for reference
3827/// initialization.
3828static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003829TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003830 SourceLocation DeclLoc,
3831 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003832 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003833 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3834
3835 // Most paths end in a failed conversion.
3836 ImplicitConversionSequence ICS;
3837 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3838
3839 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3840 QualType T2 = Init->getType();
3841
3842 // If the initializer is the address of an overloaded function, try
3843 // to resolve the overloaded function. If all goes well, T2 is the
3844 // type of the resulting function.
3845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3846 DeclAccessPair Found;
3847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3848 false, Found))
3849 T2 = Fn->getType();
3850 }
3851
3852 // Compute some basic properties of the types and the initializer.
3853 bool isRValRef = DeclType->isRValueReferenceType();
3854 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003855 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003856 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003857 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003858 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003859 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003860 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003861
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003862
Sebastian Redld92badf2010-06-30 18:13:39 +00003863 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003864 // A reference to type "cv1 T1" is initialized by an expression
3865 // of type "cv2 T2" as follows:
3866
Sebastian Redld92badf2010-06-30 18:13:39 +00003867 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003868 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003869 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3870 // reference-compatible with "cv2 T2," or
3871 //
3872 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3873 if (InitCategory.isLValue() &&
3874 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003875 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003876 // When a parameter of reference type binds directly (8.5.3)
3877 // to an argument expression, the implicit conversion sequence
3878 // is the identity conversion, unless the argument expression
3879 // has a type that is a derived class of the parameter type,
3880 // in which case the implicit conversion sequence is a
3881 // derived-to-base Conversion (13.3.3.1).
3882 ICS.setStandard();
3883 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003884 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3885 : ObjCConversion? ICK_Compatible_Conversion
3886 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003887 ICS.Standard.Third = ICK_Identity;
3888 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3889 ICS.Standard.setToType(0, T2);
3890 ICS.Standard.setToType(1, T1);
3891 ICS.Standard.setToType(2, T1);
3892 ICS.Standard.ReferenceBinding = true;
3893 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003894 ICS.Standard.IsLvalueReference = !isRValRef;
3895 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3896 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003897 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003898 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003899 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003900
Sebastian Redld92badf2010-06-30 18:13:39 +00003901 // Nothing more to do: the inaccessibility/ambiguity check for
3902 // derived-to-base conversions is suppressed when we're
3903 // computing the implicit conversion sequence (C++
3904 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003905 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003906 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003907
Sebastian Redld92badf2010-06-30 18:13:39 +00003908 // -- has a class type (i.e., T2 is a class type), where T1 is
3909 // not reference-related to T2, and can be implicitly
3910 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3911 // is reference-compatible with "cv3 T3" 92) (this
3912 // conversion is selected by enumerating the applicable
3913 // conversion functions (13.3.1.6) and choosing the best
3914 // one through overload resolution (13.3)),
3915 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003917 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003918 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3919 Init, T2, /*AllowRvalues=*/false,
3920 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003921 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003922 }
3923 }
3924
Sebastian Redld92badf2010-06-30 18:13:39 +00003925 // -- Otherwise, the reference shall be an lvalue reference to a
3926 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003927 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003928 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003929 // We actually handle one oddity of C++ [over.ics.ref] at this
3930 // point, which is that, due to p2 (which short-circuits reference
3931 // binding by only attempting a simple conversion for non-direct
3932 // bindings) and p3's strange wording, we allow a const volatile
3933 // reference to bind to an rvalue. Hence the check for the presence
3934 // of "const" rather than checking for "const" being the only
3935 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003936 // This is also the point where rvalue references and lvalue inits no longer
3937 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003938 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003939 return ICS;
3940
Douglas Gregorf143cd52011-01-24 16:14:37 +00003941 // -- If the initializer expression
3942 //
3943 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003944 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003945 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3946 (InitCategory.isXValue() ||
3947 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3948 (InitCategory.isLValue() && T2->isFunctionType()))) {
3949 ICS.setStandard();
3950 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003952 : ObjCConversion? ICK_Compatible_Conversion
3953 : ICK_Identity;
3954 ICS.Standard.Third = ICK_Identity;
3955 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3956 ICS.Standard.setToType(0, T2);
3957 ICS.Standard.setToType(1, T1);
3958 ICS.Standard.setToType(2, T1);
3959 ICS.Standard.ReferenceBinding = true;
3960 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3961 // binding unless we're binding to a class prvalue.
3962 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3963 // allow the use of rvalue references in C++98/03 for the benefit of
3964 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 ICS.Standard.DirectBinding =
3966 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003967 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003968 ICS.Standard.IsLvalueReference = !isRValRef;
3969 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003970 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003971 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003972 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003973 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976
Douglas Gregorf143cd52011-01-24 16:14:37 +00003977 // -- has a class type (i.e., T2 is a class type), where T1 is not
3978 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979 // an xvalue, class prvalue, or function lvalue of type
3980 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003981 // "cv3 T3",
3982 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003984 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003986 // class subobject).
3987 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003989 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3990 Init, T2, /*AllowRvalues=*/true,
3991 AllowExplicit)) {
3992 // In the second case, if the reference is an rvalue reference
3993 // and the second standard conversion sequence of the
3994 // user-defined conversion sequence includes an lvalue-to-rvalue
3995 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003997 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3998 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3999
Douglas Gregor95273c32011-01-21 16:36:05 +00004000 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004003 // -- Otherwise, a temporary of type "cv1 T1" is created and
4004 // initialized from the initializer expression using the
4005 // rules for a non-reference copy initialization (8.5). The
4006 // reference is then bound to the temporary. If T1 is
4007 // reference-related to T2, cv1 must be the same
4008 // cv-qualification as, or greater cv-qualification than,
4009 // cv2; otherwise, the program is ill-formed.
4010 if (RefRelationship == Sema::Ref_Related) {
4011 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4012 // we would be reference-compatible or reference-compatible with
4013 // added qualification. But that wasn't the case, so the reference
4014 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004015 //
4016 // Note that we only want to check address spaces and cvr-qualifiers here.
4017 // ObjC GC and lifetime qualifiers aren't important.
4018 Qualifiers T1Quals = T1.getQualifiers();
4019 Qualifiers T2Quals = T2.getQualifiers();
4020 T1Quals.removeObjCGCAttr();
4021 T1Quals.removeObjCLifetime();
4022 T2Quals.removeObjCGCAttr();
4023 T2Quals.removeObjCLifetime();
4024 if (!T1Quals.compatiblyIncludes(T2Quals))
4025 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004026 }
4027
4028 // If at least one of the types is a class type, the types are not
4029 // related, and we aren't allowed any user conversions, the
4030 // reference binding fails. This case is important for breaking
4031 // recursion, since TryImplicitConversion below will attempt to
4032 // create a temporary through the use of a copy constructor.
4033 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4034 (T1->isRecordType() || T2->isRecordType()))
4035 return ICS;
4036
Douglas Gregorcba72b12011-01-21 05:18:22 +00004037 // If T1 is reference-related to T2 and the reference is an rvalue
4038 // reference, the initializer expression shall not be an lvalue.
4039 if (RefRelationship >= Sema::Ref_Related &&
4040 isRValRef && Init->Classify(S.Context).isLValue())
4041 return ICS;
4042
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004043 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004044 // When a parameter of reference type is not bound directly to
4045 // an argument expression, the conversion sequence is the one
4046 // required to convert the argument expression to the
4047 // underlying type of the reference according to
4048 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4049 // to copy-initializing a temporary of the underlying type with
4050 // the argument expression. Any difference in top-level
4051 // cv-qualification is subsumed by the initialization itself
4052 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004053 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4054 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004055 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004056 /*CStyle=*/false,
4057 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004058
4059 // Of course, that's still a reference binding.
4060 if (ICS.isStandard()) {
4061 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004062 ICS.Standard.IsLvalueReference = !isRValRef;
4063 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4064 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004065 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004066 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004067 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004068 // Don't allow rvalue references to bind to lvalues.
4069 if (DeclType->isRValueReferenceType()) {
4070 if (const ReferenceType *RefType
4071 = ICS.UserDefined.ConversionFunction->getResultType()
4072 ->getAs<LValueReferenceType>()) {
4073 if (!RefType->getPointeeType()->isFunctionType()) {
4074 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4075 DeclType);
4076 return ICS;
4077 }
4078 }
4079 }
4080
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004081 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004082 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4083 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4084 ICS.UserDefined.After.BindsToRvalue = true;
4085 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4086 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004087 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004088
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004089 return ICS;
4090}
4091
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004092static ImplicitConversionSequence
4093TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4094 bool SuppressUserConversions,
4095 bool InOverloadResolution,
4096 bool AllowObjCWritebackConversion);
4097
4098/// TryListConversion - Try to copy-initialize a value of type ToType from the
4099/// initializer list From.
4100static ImplicitConversionSequence
4101TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4102 bool SuppressUserConversions,
4103 bool InOverloadResolution,
4104 bool AllowObjCWritebackConversion) {
4105 // C++11 [over.ics.list]p1:
4106 // When an argument is an initializer list, it is not an expression and
4107 // special rules apply for converting it to a parameter type.
4108
4109 ImplicitConversionSequence Result;
4110 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004111 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004112
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004113 // We need a complete type for what follows. Incomplete types can bever be
4114 // initialized from init lists.
4115 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4116 return Result;
4117
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004118 // C++11 [over.ics.list]p2:
4119 // If the parameter type is std::initializer_list<X> or "array of X" and
4120 // all the elements can be implicitly converted to X, the implicit
4121 // conversion sequence is the worst conversion necessary to convert an
4122 // element of the list to X.
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004123 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004124 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004125 X = S.Context.getBaseElementType(ToType);
4126 else
4127 (void)S.isStdInitializerList(ToType, &X);
4128 if (!X.isNull()) {
4129 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4130 Expr *Init = From->getInit(i);
4131 ImplicitConversionSequence ICS =
4132 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4133 InOverloadResolution,
4134 AllowObjCWritebackConversion);
4135 // If a single element isn't convertible, fail.
4136 if (ICS.isBad()) {
4137 Result = ICS;
4138 break;
4139 }
4140 // Otherwise, look for the worst conversion.
4141 if (Result.isBad() ||
4142 CompareImplicitConversionSequences(S, ICS, Result) ==
4143 ImplicitConversionSequence::Worse)
4144 Result = ICS;
4145 }
4146 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004147 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004148 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004149
4150 // C++11 [over.ics.list]p3:
4151 // Otherwise, if the parameter is a non-aggregate class X and overload
4152 // resolution chooses a single best constructor [...] the implicit
4153 // conversion sequence is a user-defined conversion sequence. If multiple
4154 // constructors are viable but none is better than the others, the
4155 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004156 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4157 // This function can deal with initializer lists.
4158 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4159 /*AllowExplicit=*/false,
4160 InOverloadResolution, /*CStyle=*/false,
4161 AllowObjCWritebackConversion);
4162 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004163 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004164 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004165
4166 // C++11 [over.ics.list]p4:
4167 // Otherwise, if the parameter has an aggregate type which can be
4168 // initialized from the initializer list [...] the implicit conversion
4169 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004170 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004171 // Type is an aggregate, argument is an init list. At this point it comes
4172 // down to checking whether the initialization works.
4173 // FIXME: Find out whether this parameter is consumed or not.
4174 InitializedEntity Entity =
4175 InitializedEntity::InitializeParameter(S.Context, ToType,
4176 /*Consumed=*/false);
4177 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4178 Result.setUserDefined();
4179 Result.UserDefined.Before.setAsIdentityConversion();
4180 // Initializer lists don't have a type.
4181 Result.UserDefined.Before.setFromType(QualType());
4182 Result.UserDefined.Before.setAllToTypes(QualType());
4183
4184 Result.UserDefined.After.setAsIdentityConversion();
4185 Result.UserDefined.After.setFromType(ToType);
4186 Result.UserDefined.After.setAllToTypes(ToType);
4187 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004188 return Result;
4189 }
4190
4191 // C++11 [over.ics.list]p5:
4192 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004193 if (ToType->isReferenceType()) {
4194 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4195 // mention initializer lists in any way. So we go by what list-
4196 // initialization would do and try to extrapolate from that.
4197
4198 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4199
4200 // If the initializer list has a single element that is reference-related
4201 // to the parameter type, we initialize the reference from that.
4202 if (From->getNumInits() == 1) {
4203 Expr *Init = From->getInit(0);
4204
4205 QualType T2 = Init->getType();
4206
4207 // If the initializer is the address of an overloaded function, try
4208 // to resolve the overloaded function. If all goes well, T2 is the
4209 // type of the resulting function.
4210 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4211 DeclAccessPair Found;
4212 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4213 Init, ToType, false, Found))
4214 T2 = Fn->getType();
4215 }
4216
4217 // Compute some basic properties of the types and the initializer.
4218 bool dummy1 = false;
4219 bool dummy2 = false;
4220 bool dummy3 = false;
4221 Sema::ReferenceCompareResult RefRelationship
4222 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4223 dummy2, dummy3);
4224
4225 if (RefRelationship >= Sema::Ref_Related)
4226 return TryReferenceInit(S, Init, ToType,
4227 /*FIXME:*/From->getLocStart(),
4228 SuppressUserConversions,
4229 /*AllowExplicit=*/false);
4230 }
4231
4232 // Otherwise, we bind the reference to a temporary created from the
4233 // initializer list.
4234 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4235 InOverloadResolution,
4236 AllowObjCWritebackConversion);
4237 if (Result.isFailure())
4238 return Result;
4239 assert(!Result.isEllipsis() &&
4240 "Sub-initialization cannot result in ellipsis conversion.");
4241
4242 // Can we even bind to a temporary?
4243 if (ToType->isRValueReferenceType() ||
4244 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4245 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4246 Result.UserDefined.After;
4247 SCS.ReferenceBinding = true;
4248 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4249 SCS.BindsToRvalue = true;
4250 SCS.BindsToFunctionLvalue = false;
4251 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4252 SCS.ObjCLifetimeConversionBinding = false;
4253 } else
4254 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4255 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004256 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004257 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004258
4259 // C++11 [over.ics.list]p6:
4260 // Otherwise, if the parameter type is not a class:
4261 if (!ToType->isRecordType()) {
4262 // - if the initializer list has one element, the implicit conversion
4263 // sequence is the one required to convert the element to the
4264 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004265 unsigned NumInits = From->getNumInits();
4266 if (NumInits == 1)
4267 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4268 SuppressUserConversions,
4269 InOverloadResolution,
4270 AllowObjCWritebackConversion);
4271 // - if the initializer list has no elements, the implicit conversion
4272 // sequence is the identity conversion.
4273 else if (NumInits == 0) {
4274 Result.setStandard();
4275 Result.Standard.setAsIdentityConversion();
4276 }
4277 return Result;
4278 }
4279
4280 // C++11 [over.ics.list]p7:
4281 // In all cases other than those enumerated above, no conversion is possible
4282 return Result;
4283}
4284
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004285/// TryCopyInitialization - Try to copy-initialize a value of type
4286/// ToType from the expression From. Return the implicit conversion
4287/// sequence required to pass this argument, which may be a bad
4288/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004289/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004290/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004291static ImplicitConversionSequence
4292TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004294 bool InOverloadResolution,
4295 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004296 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4297 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4298 InOverloadResolution,AllowObjCWritebackConversion);
4299
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004301 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004302 /*FIXME:*/From->getLocStart(),
4303 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004304 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004305
John McCall5c32be02010-08-24 20:38:10 +00004306 return TryImplicitConversion(S, From, ToType,
4307 SuppressUserConversions,
4308 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004309 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004310 /*CStyle=*/false,
4311 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004312}
4313
Anna Zaks1b068122011-07-28 19:46:48 +00004314static bool TryCopyInitialization(const CanQualType FromQTy,
4315 const CanQualType ToQTy,
4316 Sema &S,
4317 SourceLocation Loc,
4318 ExprValueKind FromVK) {
4319 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4320 ImplicitConversionSequence ICS =
4321 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4322
4323 return !ICS.isBad();
4324}
4325
Douglas Gregor436424c2008-11-18 23:14:02 +00004326/// TryObjectArgumentInitialization - Try to initialize the object
4327/// parameter of the given member function (@c Method) from the
4328/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004329static ImplicitConversionSequence
4330TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004331 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004332 CXXMethodDecl *Method,
4333 CXXRecordDecl *ActingContext) {
4334 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004335 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4336 // const volatile object.
4337 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4338 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004339 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004340
4341 // Set up the conversion sequence as a "bad" conversion, to allow us
4342 // to exit early.
4343 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004344
4345 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004346 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004347 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004348 FromType = PT->getPointeeType();
4349
Douglas Gregor02824322011-01-26 19:30:28 +00004350 // When we had a pointer, it's implicitly dereferenced, so we
4351 // better have an lvalue.
4352 assert(FromClassification.isLValue());
4353 }
4354
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004355 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004356
Douglas Gregor02824322011-01-26 19:30:28 +00004357 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004359 // parameter is
4360 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004361 // - "lvalue reference to cv X" for functions declared without a
4362 // ref-qualifier or with the & ref-qualifier
4363 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004364 // ref-qualifier
4365 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004367 // cv-qualification on the member function declaration.
4368 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004370 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004371 // (C++ [over.match.funcs]p5). We perform a simplified version of
4372 // reference binding here, that allows class rvalues to bind to
4373 // non-constant references.
4374
Douglas Gregor02824322011-01-26 19:30:28 +00004375 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004376 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004378 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004379 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004380 ICS.setBad(BadConversionSequence::bad_qualifiers,
4381 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004382 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004383 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004384
4385 // Check that we have either the same type or a derived type. It
4386 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004387 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004388 ImplicitConversionKind SecondKind;
4389 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4390 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004391 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004392 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004393 else {
John McCall65eb8792010-02-25 01:37:24 +00004394 ICS.setBad(BadConversionSequence::unrelated_class,
4395 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004396 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004397 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004398
Douglas Gregor02824322011-01-26 19:30:28 +00004399 // Check the ref-qualifier.
4400 switch (Method->getRefQualifier()) {
4401 case RQ_None:
4402 // Do nothing; we don't care about lvalueness or rvalueness.
4403 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregor02824322011-01-26 19:30:28 +00004405 case RQ_LValue:
4406 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4407 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004409 ImplicitParamType);
4410 return ICS;
4411 }
4412 break;
4413
4414 case RQ_RValue:
4415 if (!FromClassification.isRValue()) {
4416 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004418 ImplicitParamType);
4419 return ICS;
4420 }
4421 break;
4422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregor436424c2008-11-18 23:14:02 +00004424 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004425 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004426 ICS.Standard.setAsIdentityConversion();
4427 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004428 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004429 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004430 ICS.Standard.ReferenceBinding = true;
4431 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004433 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004434 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4435 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4436 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004437 return ICS;
4438}
4439
4440/// PerformObjectArgumentInitialization - Perform initialization of
4441/// the implicit object parameter for the given Method with the given
4442/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004443ExprResult
4444Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004446 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004447 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004448 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004449 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004450 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004451
Douglas Gregor02824322011-01-26 19:30:28 +00004452 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004453 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004454 FromRecordType = PT->getPointeeType();
4455 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004456 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004457 } else {
4458 FromRecordType = From->getType();
4459 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004460 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004461 }
4462
John McCall6e9f8f62009-12-03 04:06:58 +00004463 // Note that we always use the true parent context when performing
4464 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004465 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004466 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4467 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004468 if (ICS.isBad()) {
4469 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4470 Qualifiers FromQs = FromRecordType.getQualifiers();
4471 Qualifiers ToQs = DestType.getQualifiers();
4472 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4473 if (CVR) {
4474 Diag(From->getSourceRange().getBegin(),
4475 diag::err_member_function_call_bad_cvr)
4476 << Method->getDeclName() << FromRecordType << (CVR - 1)
4477 << From->getSourceRange();
4478 Diag(Method->getLocation(), diag::note_previous_decl)
4479 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004480 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004481 }
4482 }
4483
Douglas Gregor436424c2008-11-18 23:14:02 +00004484 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004485 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004486 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004487 }
Mike Stump11289f42009-09-09 15:08:12 +00004488
John Wiegley01296292011-04-08 18:41:53 +00004489 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4490 ExprResult FromRes =
4491 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4492 if (FromRes.isInvalid())
4493 return ExprError();
4494 From = FromRes.take();
4495 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004496
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004497 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004498 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004499 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004500 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004501}
4502
Douglas Gregor5fb53972009-01-14 15:45:31 +00004503/// TryContextuallyConvertToBool - Attempt to contextually convert the
4504/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004505static ImplicitConversionSequence
4506TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004507 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004508 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004509 // FIXME: Are these flags correct?
4510 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004511 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004512 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004513 /*CStyle=*/false,
4514 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004515}
4516
4517/// PerformContextuallyConvertToBool - Perform a contextual conversion
4518/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004519ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004520 if (checkPlaceholderForOverload(*this, From))
4521 return ExprError();
4522
John McCall5c32be02010-08-24 20:38:10 +00004523 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004524 if (!ICS.isBad())
4525 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
Fariborz Jahanian76197412009-11-18 18:26:29 +00004527 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004528 return Diag(From->getSourceRange().getBegin(),
4529 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004530 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004531 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
John McCallfec112d2011-09-09 06:11:02 +00004534/// dropPointerConversions - If the given standard conversion sequence
4535/// involves any pointer conversions, remove them. This may change
4536/// the result type of the conversion sequence.
4537static void dropPointerConversion(StandardConversionSequence &SCS) {
4538 if (SCS.Second == ICK_Pointer_Conversion) {
4539 SCS.Second = ICK_Identity;
4540 SCS.Third = ICK_Identity;
4541 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4542 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004543}
John McCall5c32be02010-08-24 20:38:10 +00004544
John McCallfec112d2011-09-09 06:11:02 +00004545/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4546/// convert the expression From to an Objective-C pointer type.
4547static ImplicitConversionSequence
4548TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4549 // Do an implicit conversion to 'id'.
4550 QualType Ty = S.Context.getObjCIdType();
4551 ImplicitConversionSequence ICS
4552 = TryImplicitConversion(S, From, Ty,
4553 // FIXME: Are these flags correct?
4554 /*SuppressUserConversions=*/false,
4555 /*AllowExplicit=*/true,
4556 /*InOverloadResolution=*/false,
4557 /*CStyle=*/false,
4558 /*AllowObjCWritebackConversion=*/false);
4559
4560 // Strip off any final conversions to 'id'.
4561 switch (ICS.getKind()) {
4562 case ImplicitConversionSequence::BadConversion:
4563 case ImplicitConversionSequence::AmbiguousConversion:
4564 case ImplicitConversionSequence::EllipsisConversion:
4565 break;
4566
4567 case ImplicitConversionSequence::UserDefinedConversion:
4568 dropPointerConversion(ICS.UserDefined.After);
4569 break;
4570
4571 case ImplicitConversionSequence::StandardConversion:
4572 dropPointerConversion(ICS.Standard);
4573 break;
4574 }
4575
4576 return ICS;
4577}
4578
4579/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4580/// conversion of the expression From to an Objective-C pointer type.
4581ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004582 if (checkPlaceholderForOverload(*this, From))
4583 return ExprError();
4584
John McCall8b07ec22010-05-15 11:32:37 +00004585 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004586 ImplicitConversionSequence ICS =
4587 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004588 if (!ICS.isBad())
4589 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004590 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004591}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004592
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004594/// enumeration type.
4595///
4596/// This routine will attempt to convert an expression of class type to an
4597/// integral or enumeration type, if that class type only has a single
4598/// conversion to an integral or enumeration type.
4599///
Douglas Gregor4799d032010-06-30 00:20:43 +00004600/// \param Loc The source location of the construct that requires the
4601/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004602///
Douglas Gregor4799d032010-06-30 00:20:43 +00004603/// \param FromE The expression we're converting from.
4604///
4605/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4606/// have integral or enumeration type.
4607///
4608/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4609/// incomplete class type.
4610///
4611/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4612/// explicit conversion function (because no implicit conversion functions
4613/// were available). This is a recovery mode.
4614///
4615/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4616/// showing which conversion was picked.
4617///
4618/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4619/// conversion function that could convert to integral or enumeration type.
4620///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004622/// usable conversion function.
4623///
4624/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4625/// function, which may be an extension in this case.
4626///
4627/// \returns The expression, converted to an integral or enumeration type if
4628/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629ExprResult
John McCallb268a282010-08-23 23:25:46 +00004630Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004631 const PartialDiagnostic &NotIntDiag,
4632 const PartialDiagnostic &IncompleteDiag,
4633 const PartialDiagnostic &ExplicitConvDiag,
4634 const PartialDiagnostic &ExplicitConvNote,
4635 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004636 const PartialDiagnostic &AmbigNote,
4637 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004638 // We can't perform any more checking for type-dependent expressions.
4639 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004640 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004642 // If the expression already has integral or enumeration type, we're golden.
4643 QualType T = From->getType();
4644 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004645 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004646
4647 // FIXME: Check for missing '()' if T is a function type?
4648
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649 // 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 +00004650 // expression of integral or enumeration type.
4651 const RecordType *RecordTy = T->getAs<RecordType>();
4652 if (!RecordTy || !getLangOptions().CPlusPlus) {
4653 Diag(Loc, NotIntDiag)
4654 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004655 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004658 // We must have a complete class type.
4659 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004660 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004662 // Look for a conversion to an integral or enumeration type.
4663 UnresolvedSet<4> ViableConversions;
4664 UnresolvedSet<4> ExplicitConversions;
4665 const UnresolvedSetImpl *Conversions
4666 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004668 bool HadMultipleCandidates = (Conversions->size() > 1);
4669
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004670 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671 E = Conversions->end();
4672 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004673 ++I) {
4674 if (CXXConversionDecl *Conversion
4675 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4676 if (Conversion->getConversionType().getNonReferenceType()
4677 ->isIntegralOrEnumerationType()) {
4678 if (Conversion->isExplicit())
4679 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4680 else
4681 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4682 }
4683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004685 switch (ViableConversions.size()) {
4686 case 0:
4687 if (ExplicitConversions.size() == 1) {
4688 DeclAccessPair Found = ExplicitConversions[0];
4689 CXXConversionDecl *Conversion
4690 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004692 // The user probably meant to invoke the given explicit
4693 // conversion; use it.
4694 QualType ConvTy
4695 = Conversion->getConversionType().getNonReferenceType();
4696 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004697 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004698
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004699 Diag(Loc, ExplicitConvDiag)
4700 << T << ConvTy
4701 << FixItHint::CreateInsertion(From->getLocStart(),
4702 "static_cast<" + TypeStr + ">(")
4703 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4704 ")");
4705 Diag(Conversion->getLocation(), ExplicitConvNote)
4706 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
4708 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004709 // explicit conversion function.
4710 if (isSFINAEContext())
4711 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004713 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004714 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4715 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004716 if (Result.isInvalid())
4717 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004718 // Record usage of conversion in an implicit cast.
4719 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4720 CK_UserDefinedConversion,
4721 Result.get(), 0,
4722 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004725 // We'll complain below about a non-integral condition type.
4726 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004728 case 1: {
4729 // Apply this conversion.
4730 DeclAccessPair Found = ViableConversions[0];
4731 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732
Douglas Gregor4799d032010-06-30 00:20:43 +00004733 CXXConversionDecl *Conversion
4734 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4735 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004737 if (ConvDiag.getDiagID()) {
4738 if (isSFINAEContext())
4739 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
Douglas Gregor4799d032010-06-30 00:20:43 +00004741 Diag(Loc, ConvDiag)
4742 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004745 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4746 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004747 if (Result.isInvalid())
4748 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004749 // Record usage of conversion in an implicit cast.
4750 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4751 CK_UserDefinedConversion,
4752 Result.get(), 0,
4753 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004754 break;
4755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004756
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004757 default:
4758 Diag(Loc, AmbigDiag)
4759 << T << From->getSourceRange();
4760 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4761 CXXConversionDecl *Conv
4762 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4763 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4764 Diag(Conv->getLocation(), AmbigNote)
4765 << ConvTy->isEnumeralType() << ConvTy;
4766 }
John McCallb268a282010-08-23 23:25:46 +00004767 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Douglas Gregor5823da32010-06-29 23:25:20 +00004770 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004771 Diag(Loc, NotIntDiag)
4772 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004773
John McCallb268a282010-08-23 23:25:46 +00004774 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004775}
4776
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004777/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004778/// candidate functions, using the given function call arguments. If
4779/// @p SuppressUserConversions, then don't allow user-defined
4780/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004781///
4782/// \para PartialOverloading true if we are performing "partial" overloading
4783/// based on an incomplete set of function arguments. This feature is used by
4784/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004785void
4786Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004787 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004788 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004789 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004790 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004791 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004792 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004793 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004794 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004795 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004796 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004798 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004799 if (!isa<CXXConstructorDecl>(Method)) {
4800 // If we get here, it's because we're calling a member function
4801 // that is named without a member access expression (e.g.,
4802 // "this->f") that was either written explicitly or created
4803 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004804 // function, e.g., X::f(). We use an empty type for the implied
4805 // object argument (C++ [over.call.func]p3), and the acting context
4806 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004807 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004809 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004810 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004811 return;
4812 }
4813 // We treat a constructor like a non-member function, since its object
4814 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004815 }
4816
Douglas Gregorff7028a2009-11-13 23:59:09 +00004817 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004818 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004819
Douglas Gregor27381f32009-11-23 12:27:39 +00004820 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004821 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004822
Douglas Gregorffe14e32009-11-14 01:20:54 +00004823 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4824 // C++ [class.copy]p3:
4825 // A member function template is never instantiated to perform the copy
4826 // of a class object to an object of its class type.
4827 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004829 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004830 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4831 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004832 return;
4833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004835 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004836 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00004837 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004838 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004839 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004840 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004841 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004842 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004844 unsigned NumArgsInProto = Proto->getNumArgs();
4845
4846 // (C++ 13.3.2p2): A candidate function having fewer than m
4847 // parameters is viable only if it has an ellipsis in its parameter
4848 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004850 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004851 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004852 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004853 return;
4854 }
4855
4856 // (C++ 13.3.2p2): A candidate function having more than m parameters
4857 // is viable only if the (m+1)st parameter has a default argument
4858 // (8.3.6). For the purposes of overload resolution, the
4859 // parameter list is truncated on the right, so that there are
4860 // exactly m parameters.
4861 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004862 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004863 // Not enough arguments.
4864 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004865 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004866 return;
4867 }
4868
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004869 // (CUDA B.1): Check for invalid calls between targets.
4870 if (getLangOptions().CUDA)
4871 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4872 if (CheckCUDATarget(Caller, Function)) {
4873 Candidate.Viable = false;
4874 Candidate.FailureKind = ovl_fail_bad_target;
4875 return;
4876 }
4877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004878 // Determine the implicit conversion sequences for each of the
4879 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004880 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4881 if (ArgIdx < NumArgsInProto) {
4882 // (C++ 13.3.2p3): for F to be a viable function, there shall
4883 // exist for each argument an implicit conversion sequence
4884 // (13.3.3.1) that converts that argument to the corresponding
4885 // parameter of F.
4886 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004887 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004888 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004890 /*InOverloadResolution=*/true,
4891 /*AllowObjCWritebackConversion=*/
4892 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004893 if (Candidate.Conversions[ArgIdx].isBad()) {
4894 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004895 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004896 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004897 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004898 } else {
4899 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4900 // argument for which there is no corresponding parameter is
4901 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004902 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004903 }
4904 }
4905}
4906
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004907/// \brief Add all of the function declarations in the given function set to
4908/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004909void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004910 Expr **Args, unsigned NumArgs,
4911 OverloadCandidateSet& CandidateSet,
4912 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004913 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004914 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4915 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004916 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004917 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004918 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004919 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004921 CandidateSet, SuppressUserConversions);
4922 else
John McCalla0296f72010-03-19 07:35:19 +00004923 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004924 SuppressUserConversions);
4925 } else {
John McCalla0296f72010-03-19 07:35:19 +00004926 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004927 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4928 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004929 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004930 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004931 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004933 Args[0]->Classify(Context),
4934 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004935 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004936 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004937 else
John McCalla0296f72010-03-19 07:35:19 +00004938 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004939 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004940 Args, NumArgs, CandidateSet,
4941 SuppressUserConversions);
4942 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004943 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004944}
4945
John McCallf0f1cf02009-11-17 07:50:12 +00004946/// AddMethodCandidate - Adds a named decl (which is some kind of
4947/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004948void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004949 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004950 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004951 Expr **Args, unsigned NumArgs,
4952 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004953 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004954 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004955 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004956
4957 if (isa<UsingShadowDecl>(Decl))
4958 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959
John McCallf0f1cf02009-11-17 07:50:12 +00004960 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4961 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4962 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004963 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4964 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004965 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004966 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004967 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004968 } else {
John McCalla0296f72010-03-19 07:35:19 +00004969 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004970 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004971 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004972 }
4973}
4974
Douglas Gregor436424c2008-11-18 23:14:02 +00004975/// AddMethodCandidate - Adds the given C++ member function to the set
4976/// of candidate functions, using the given function call arguments
4977/// and the object argument (@c Object). For example, in a call
4978/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4979/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4980/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004981/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004982void
John McCalla0296f72010-03-19 07:35:19 +00004983Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004984 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004985 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004986 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004987 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004988 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004989 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004990 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004991 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004992 assert(!isa<CXXConstructorDecl>(Method) &&
4993 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004994
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004995 if (!CandidateSet.isNewCandidate(Method))
4996 return;
4997
Douglas Gregor27381f32009-11-23 12:27:39 +00004998 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004999 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005000
Douglas Gregor436424c2008-11-18 23:14:02 +00005001 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005002 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005003 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005004 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005005 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005006 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005007 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00005008
5009 unsigned NumArgsInProto = Proto->getNumArgs();
5010
5011 // (C++ 13.3.2p2): A candidate function having fewer than m
5012 // parameters is viable only if it has an ellipsis in its parameter
5013 // list (8.3.5).
5014 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5015 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005016 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005017 return;
5018 }
5019
5020 // (C++ 13.3.2p2): A candidate function having more than m parameters
5021 // is viable only if the (m+1)st parameter has a default argument
5022 // (8.3.6). For the purposes of overload resolution, the
5023 // parameter list is truncated on the right, so that there are
5024 // exactly m parameters.
5025 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5026 if (NumArgs < MinRequiredArgs) {
5027 // Not enough arguments.
5028 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005029 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005030 return;
5031 }
5032
5033 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005034
John McCall6e9f8f62009-12-03 04:06:58 +00005035 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005036 // The implicit object argument is ignored.
5037 Candidate.IgnoreObjectArgument = true;
5038 else {
5039 // Determine the implicit conversion sequence for the object
5040 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005041 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005042 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5043 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005044 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005045 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005046 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005047 return;
5048 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005049 }
5050
5051 // Determine the implicit conversion sequences for each of the
5052 // arguments.
5053 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5054 if (ArgIdx < NumArgsInProto) {
5055 // (C++ 13.3.2p3): for F to be a viable function, there shall
5056 // exist for each argument an implicit conversion sequence
5057 // (13.3.3.1) that converts that argument to the corresponding
5058 // parameter of F.
5059 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005060 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005061 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005063 /*InOverloadResolution=*/true,
5064 /*AllowObjCWritebackConversion=*/
5065 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005066 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005067 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005068 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005069 break;
5070 }
5071 } else {
5072 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5073 // argument for which there is no corresponding parameter is
5074 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005075 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005076 }
5077 }
5078}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079
Douglas Gregor97628d62009-08-21 00:16:32 +00005080/// \brief Add a C++ member function template as a candidate to the candidate
5081/// set, using template argument deduction to produce an appropriate member
5082/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005083void
Douglas Gregor97628d62009-08-21 00:16:32 +00005084Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005085 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005086 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005087 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005088 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005089 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00005090 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005091 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005092 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005093 if (!CandidateSet.isNewCandidate(MethodTmpl))
5094 return;
5095
Douglas Gregor97628d62009-08-21 00:16:32 +00005096 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005097 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005098 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005099 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005100 // candidate functions in the usual way.113) A given name can refer to one
5101 // or more function templates and also to a set of overloaded non-template
5102 // functions. In such a case, the candidate functions generated from each
5103 // function template are combined with the set of non-template candidate
5104 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005105 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005106 FunctionDecl *Specialization = 0;
5107 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005108 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005109 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005110 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005111 Candidate.FoundDecl = FoundDecl;
5112 Candidate.Function = MethodTmpl->getTemplatedDecl();
5113 Candidate.Viable = false;
5114 Candidate.FailureKind = ovl_fail_bad_deduction;
5115 Candidate.IsSurrogate = false;
5116 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005117 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005119 Info);
5120 return;
5121 }
Mike Stump11289f42009-09-09 15:08:12 +00005122
Douglas Gregor97628d62009-08-21 00:16:32 +00005123 // Add the function template specialization produced by template argument
5124 // deduction as a candidate.
5125 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005126 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005127 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005128 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00005129 ActingContext, ObjectType, ObjectClassification,
5130 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005131}
5132
Douglas Gregor05155d82009-08-21 23:19:43 +00005133/// \brief Add a C++ function template specialization as a candidate
5134/// in the candidate set, using template argument deduction to produce
5135/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005136void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005137Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005138 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005139 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005140 Expr **Args, unsigned NumArgs,
5141 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005142 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005143 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5144 return;
5145
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005146 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005147 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005148 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005149 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005150 // candidate functions in the usual way.113) A given name can refer to one
5151 // or more function templates and also to a set of overloaded non-template
5152 // functions. In such a case, the candidate functions generated from each
5153 // function template are combined with the set of non-template candidate
5154 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005155 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005156 FunctionDecl *Specialization = 0;
5157 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005158 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005159 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005160 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005161 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005162 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5163 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005164 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005165 Candidate.IsSurrogate = false;
5166 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005167 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005169 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005170 return;
5171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005173 // Add the function template specialization produced by template argument
5174 // deduction as a candidate.
5175 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005176 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005177 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005178}
Mike Stump11289f42009-09-09 15:08:12 +00005179
Douglas Gregora1f013e2008-11-07 22:36:19 +00005180/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005181/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005182/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005183/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005184/// (which may or may not be the same type as the type that the
5185/// conversion function produces).
5186void
5187Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005188 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005189 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005190 Expr *From, QualType ToType,
5191 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005192 assert(!Conversion->getDescribedFunctionTemplate() &&
5193 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005194 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005195 if (!CandidateSet.isNewCandidate(Conversion))
5196 return;
5197
Douglas Gregor27381f32009-11-23 12:27:39 +00005198 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005199 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005200
Douglas Gregora1f013e2008-11-07 22:36:19 +00005201 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005202 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005203 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005204 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005205 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005206 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005207 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005208 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005209 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005210 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005211 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005212
Douglas Gregor6affc782010-08-19 15:37:02 +00005213 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214 // For conversion functions, the function is considered to be a member of
5215 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005216 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005217 //
5218 // Determine the implicit conversion sequence for the implicit
5219 // object parameter.
5220 QualType ImplicitParamType = From->getType();
5221 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5222 ImplicitParamType = FromPtrType->getPointeeType();
5223 CXXRecordDecl *ConversionContext
5224 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005225
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005226 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005227 = TryObjectArgumentInitialization(*this, From->getType(),
5228 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005229 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
John McCall0d1da222010-01-12 00:44:57 +00005231 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005232 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005233 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005234 return;
5235 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005236
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005237 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005238 // derived to base as such conversions are given Conversion Rank. They only
5239 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5240 QualType FromCanon
5241 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5242 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5243 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5244 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005245 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005246 return;
5247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005248
Douglas Gregora1f013e2008-11-07 22:36:19 +00005249 // To determine what the conversion from the result of calling the
5250 // conversion function to the type we're eventually trying to
5251 // convert to (ToType), we need to synthesize a call to the
5252 // conversion function and attempt copy initialization from it. This
5253 // makes sure that we get the right semantics with respect to
5254 // lvalues/rvalues and the type. Fortunately, we can allocate this
5255 // call on the stack and we don't need its arguments to be
5256 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005257 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005258 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005259 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5260 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005261 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005262 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005263
Richard Smith48d24642011-07-13 22:53:21 +00005264 QualType ConversionType = Conversion->getConversionType();
5265 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005266 Candidate.Viable = false;
5267 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5268 return;
5269 }
5270
Richard Smith48d24642011-07-13 22:53:21 +00005271 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005272
Mike Stump11289f42009-09-09 15:08:12 +00005273 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005274 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5275 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005276 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005277 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005278 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005279 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005280 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005281 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005282 /*InOverloadResolution=*/false,
5283 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005284
John McCall0d1da222010-01-12 00:44:57 +00005285 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005286 case ImplicitConversionSequence::StandardConversion:
5287 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005289 // C++ [over.ics.user]p3:
5290 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005292 // shall have exact match rank.
5293 if (Conversion->getPrimaryTemplate() &&
5294 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5295 Candidate.Viable = false;
5296 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005298
Douglas Gregorcba72b12011-01-21 05:18:22 +00005299 // C++0x [dcl.init.ref]p5:
5300 // In the second case, if the reference is an rvalue reference and
5301 // the second standard conversion sequence of the user-defined
5302 // conversion sequence includes an lvalue-to-rvalue conversion, the
5303 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005304 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005305 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5306 Candidate.Viable = false;
5307 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5308 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005309 break;
5310
5311 case ImplicitConversionSequence::BadConversion:
5312 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005313 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005314 break;
5315
5316 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005317 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005318 "Can only end up with a standard conversion sequence or failure");
5319 }
5320}
5321
Douglas Gregor05155d82009-08-21 23:19:43 +00005322/// \brief Adds a conversion function template specialization
5323/// candidate to the overload set, using template argument deduction
5324/// to deduce the template arguments of the conversion function
5325/// template from the type that we are converting to (C++
5326/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005327void
Douglas Gregor05155d82009-08-21 23:19:43 +00005328Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005329 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005330 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005331 Expr *From, QualType ToType,
5332 OverloadCandidateSet &CandidateSet) {
5333 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5334 "Only conversion function templates permitted here");
5335
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005336 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5337 return;
5338
John McCallbc077cf2010-02-08 23:07:23 +00005339 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005340 CXXConversionDecl *Specialization = 0;
5341 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005342 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005343 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005344 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005345 Candidate.FoundDecl = FoundDecl;
5346 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5347 Candidate.Viable = false;
5348 Candidate.FailureKind = ovl_fail_bad_deduction;
5349 Candidate.IsSurrogate = false;
5350 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005351 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005353 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005354 return;
5355 }
Mike Stump11289f42009-09-09 15:08:12 +00005356
Douglas Gregor05155d82009-08-21 23:19:43 +00005357 // Add the conversion function template specialization produced by
5358 // template argument deduction as a candidate.
5359 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005360 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005361 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005362}
5363
Douglas Gregorab7897a2008-11-19 22:57:39 +00005364/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5365/// converts the given @c Object to a function pointer via the
5366/// conversion function @c Conversion, and then attempts to call it
5367/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5368/// the type of function that we'll eventually be calling.
5369void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005370 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005371 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005372 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005373 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005374 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005375 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005376 if (!CandidateSet.isNewCandidate(Conversion))
5377 return;
5378
Douglas Gregor27381f32009-11-23 12:27:39 +00005379 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005380 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005381
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005382 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005383 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005384 Candidate.Function = 0;
5385 Candidate.Surrogate = Conversion;
5386 Candidate.Viable = true;
5387 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005388 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005389 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005390
5391 // Determine the implicit conversion sequence for the implicit
5392 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005393 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005395 Object->Classify(Context),
5396 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005397 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005398 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005399 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005400 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005401 return;
5402 }
5403
5404 // The first conversion is actually a user-defined conversion whose
5405 // first conversion is ObjectInit's standard conversion (which is
5406 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005407 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005408 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005409 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005410 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005411 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005412 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005413 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005414 = Candidate.Conversions[0].UserDefined.Before;
5415 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5416
Mike Stump11289f42009-09-09 15:08:12 +00005417 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005418 unsigned NumArgsInProto = Proto->getNumArgs();
5419
5420 // (C++ 13.3.2p2): A candidate function having fewer than m
5421 // parameters is viable only if it has an ellipsis in its parameter
5422 // list (8.3.5).
5423 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5424 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005425 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005426 return;
5427 }
5428
5429 // Function types don't have any default arguments, so just check if
5430 // we have enough arguments.
5431 if (NumArgs < NumArgsInProto) {
5432 // Not enough arguments.
5433 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005434 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005435 return;
5436 }
5437
5438 // Determine the implicit conversion sequences for each of the
5439 // arguments.
5440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5441 if (ArgIdx < NumArgsInProto) {
5442 // (C++ 13.3.2p3): for F to be a viable function, there shall
5443 // exist for each argument an implicit conversion sequence
5444 // (13.3.3.1) that converts that argument to the corresponding
5445 // parameter of F.
5446 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005447 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005448 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005449 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005450 /*InOverloadResolution=*/false,
5451 /*AllowObjCWritebackConversion=*/
5452 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005453 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005454 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005455 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005456 break;
5457 }
5458 } else {
5459 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5460 // argument for which there is no corresponding parameter is
5461 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005462 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005463 }
5464 }
5465}
5466
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005467/// \brief Add overload candidates for overloaded operators that are
5468/// member functions.
5469///
5470/// Add the overloaded operator candidates that are member functions
5471/// for the operator Op that was used in an operator expression such
5472/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5473/// CandidateSet will store the added overload candidates. (C++
5474/// [over.match.oper]).
5475void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5476 SourceLocation OpLoc,
5477 Expr **Args, unsigned NumArgs,
5478 OverloadCandidateSet& CandidateSet,
5479 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005480 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5481
5482 // C++ [over.match.oper]p3:
5483 // For a unary operator @ with an operand of a type whose
5484 // cv-unqualified version is T1, and for a binary operator @ with
5485 // a left operand of a type whose cv-unqualified version is T1 and
5486 // a right operand of a type whose cv-unqualified version is T2,
5487 // three sets of candidate functions, designated member
5488 // candidates, non-member candidates and built-in candidates, are
5489 // constructed as follows:
5490 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005491
5492 // -- If T1 is a class type, the set of member candidates is the
5493 // result of the qualified lookup of T1::operator@
5494 // (13.3.1.1.1); otherwise, the set of member candidates is
5495 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005496 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005497 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005498 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005499 return;
Mike Stump11289f42009-09-09 15:08:12 +00005500
John McCall27b18f82009-11-17 02:14:36 +00005501 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5502 LookupQualifiedName(Operators, T1Rec->getDecl());
5503 Operators.suppressDiagnostics();
5504
Mike Stump11289f42009-09-09 15:08:12 +00005505 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005506 OperEnd = Operators.end();
5507 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005508 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005509 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005511 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005512 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005513 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005514}
5515
Douglas Gregora11693b2008-11-12 17:17:38 +00005516/// AddBuiltinCandidate - Add a candidate for a built-in
5517/// operator. ResultTy and ParamTys are the result and parameter types
5518/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005519/// arguments being passed to the candidate. IsAssignmentOperator
5520/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005521/// operator. NumContextualBoolArguments is the number of arguments
5522/// (at the beginning of the argument list) that will be contextually
5523/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005524void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005525 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005526 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005527 bool IsAssignmentOperator,
5528 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005529 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005530 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005531
Douglas Gregora11693b2008-11-12 17:17:38 +00005532 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005533 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005534 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005535 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005536 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005537 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005538 Candidate.BuiltinTypes.ResultTy = ResultTy;
5539 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5540 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5541
5542 // Determine the implicit conversion sequences for each of the
5543 // arguments.
5544 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005545 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005546 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005547 // C++ [over.match.oper]p4:
5548 // For the built-in assignment operators, conversions of the
5549 // left operand are restricted as follows:
5550 // -- no temporaries are introduced to hold the left operand, and
5551 // -- no user-defined conversions are applied to the left
5552 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005553 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005554 //
5555 // We block these conversions by turning off user-defined
5556 // conversions, since that is the only way that initialization of
5557 // a reference to a non-class type can occur from something that
5558 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005559 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005560 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005561 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005562 Candidate.Conversions[ArgIdx]
5563 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005564 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005565 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005566 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005567 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005568 /*InOverloadResolution=*/false,
5569 /*AllowObjCWritebackConversion=*/
5570 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005571 }
John McCall0d1da222010-01-12 00:44:57 +00005572 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005573 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005574 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005575 break;
5576 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005577 }
5578}
5579
5580/// BuiltinCandidateTypeSet - A set of types that will be used for the
5581/// candidate operator functions for built-in operators (C++
5582/// [over.built]). The types are separated into pointer types and
5583/// enumeration types.
5584class BuiltinCandidateTypeSet {
5585 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005586 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005587
5588 /// PointerTypes - The set of pointer types that will be used in the
5589 /// built-in candidates.
5590 TypeSet PointerTypes;
5591
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005592 /// MemberPointerTypes - The set of member pointer types that will be
5593 /// used in the built-in candidates.
5594 TypeSet MemberPointerTypes;
5595
Douglas Gregora11693b2008-11-12 17:17:38 +00005596 /// EnumerationTypes - The set of enumeration types that will be
5597 /// used in the built-in candidates.
5598 TypeSet EnumerationTypes;
5599
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005601 /// candidates.
5602 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005603
5604 /// \brief A flag indicating non-record types are viable candidates
5605 bool HasNonRecordTypes;
5606
5607 /// \brief A flag indicating whether either arithmetic or enumeration types
5608 /// were present in the candidate set.
5609 bool HasArithmeticOrEnumeralTypes;
5610
Douglas Gregor80af3132011-05-21 23:15:46 +00005611 /// \brief A flag indicating whether the nullptr type was present in the
5612 /// candidate set.
5613 bool HasNullPtrType;
5614
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005615 /// Sema - The semantic analysis instance where we are building the
5616 /// candidate type set.
5617 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005618
Douglas Gregora11693b2008-11-12 17:17:38 +00005619 /// Context - The AST context in which we will build the type sets.
5620 ASTContext &Context;
5621
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005622 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5623 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005624 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005625
5626public:
5627 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005628 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005629
Mike Stump11289f42009-09-09 15:08:12 +00005630 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005631 : HasNonRecordTypes(false),
5632 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005633 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005634 SemaRef(SemaRef),
5635 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005638 SourceLocation Loc,
5639 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005640 bool AllowExplicitConversions,
5641 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005642
5643 /// pointer_begin - First pointer type found;
5644 iterator pointer_begin() { return PointerTypes.begin(); }
5645
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005646 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005647 iterator pointer_end() { return PointerTypes.end(); }
5648
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005649 /// member_pointer_begin - First member pointer type found;
5650 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5651
5652 /// member_pointer_end - Past the last member pointer type found;
5653 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5654
Douglas Gregora11693b2008-11-12 17:17:38 +00005655 /// enumeration_begin - First enumeration type found;
5656 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5657
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005658 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005659 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005661 iterator vector_begin() { return VectorTypes.begin(); }
5662 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005663
5664 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5665 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005666 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005667};
5668
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005669/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005670/// the set of pointer types along with any more-qualified variants of
5671/// that type. For example, if @p Ty is "int const *", this routine
5672/// will add "int const *", "int const volatile *", "int const
5673/// restrict *", and "int const volatile restrict *" to the set of
5674/// pointer types. Returns true if the add of @p Ty itself succeeded,
5675/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005676///
5677/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005678bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005679BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5680 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005681
Douglas Gregora11693b2008-11-12 17:17:38 +00005682 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005683 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005684 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005686 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005687 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005688 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005689 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005690 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005691 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005692 buildObjCPtr = true;
5693 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005694 else
David Blaikie83d382b2011-09-23 05:06:16 +00005695 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005696 }
5697 else
5698 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699
Sebastian Redl4990a632009-11-18 20:39:26 +00005700 // Don't add qualified variants of arrays. For one, they're not allowed
5701 // (the qualifier would sink to the element type), and for another, the
5702 // only overload situation where it matters is subscript or pointer +- int,
5703 // and those shouldn't have qualifier variants anyway.
5704 if (PointeeTy->isArrayType())
5705 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005706 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005707 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005708 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005709 bool hasVolatile = VisibleQuals.hasVolatile();
5710 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
John McCall8ccfcb52009-09-24 19:53:00 +00005712 // Iterate through all strict supersets of BaseCVR.
5713 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5714 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005715 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5716 // in the types.
5717 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5718 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005719 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005720 if (!buildObjCPtr)
5721 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5722 else
5723 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005724 }
5725
5726 return true;
5727}
5728
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005729/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5730/// to the set of pointer types along with any more-qualified variants of
5731/// that type. For example, if @p Ty is "int const *", this routine
5732/// will add "int const *", "int const volatile *", "int const
5733/// restrict *", and "int const volatile restrict *" to the set of
5734/// pointer types. Returns true if the add of @p Ty itself succeeded,
5735/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005736///
5737/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005738bool
5739BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5740 QualType Ty) {
5741 // Insert this type.
5742 if (!MemberPointerTypes.insert(Ty))
5743 return false;
5744
John McCall8ccfcb52009-09-24 19:53:00 +00005745 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5746 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005747
John McCall8ccfcb52009-09-24 19:53:00 +00005748 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005749 // Don't add qualified variants of arrays. For one, they're not allowed
5750 // (the qualifier would sink to the element type), and for another, the
5751 // only overload situation where it matters is subscript or pointer +- int,
5752 // and those shouldn't have qualifier variants anyway.
5753 if (PointeeTy->isArrayType())
5754 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005755 const Type *ClassTy = PointerTy->getClass();
5756
5757 // Iterate through all strict supersets of the pointee type's CVR
5758 // qualifiers.
5759 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5760 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5761 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005762
John McCall8ccfcb52009-09-24 19:53:00 +00005763 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005764 MemberPointerTypes.insert(
5765 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005766 }
5767
5768 return true;
5769}
5770
Douglas Gregora11693b2008-11-12 17:17:38 +00005771/// AddTypesConvertedFrom - Add each of the types to which the type @p
5772/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005773/// primarily interested in pointer types and enumeration types. We also
5774/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005775/// AllowUserConversions is true if we should look at the conversion
5776/// functions of a class type, and AllowExplicitConversions if we
5777/// should also include the explicit conversion functions of a class
5778/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005779void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005780BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005781 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005782 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005783 bool AllowExplicitConversions,
5784 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005785 // Only deal with canonical types.
5786 Ty = Context.getCanonicalType(Ty);
5787
5788 // Look through reference types; they aren't part of the type of an
5789 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005790 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005791 Ty = RefTy->getPointeeType();
5792
John McCall33ddac02011-01-19 10:06:00 +00005793 // If we're dealing with an array type, decay to the pointer.
5794 if (Ty->isArrayType())
5795 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5796
5797 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005798 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005799
Chandler Carruth00a38332010-12-13 01:44:01 +00005800 // Flag if we ever add a non-record type.
5801 const RecordType *TyRec = Ty->getAs<RecordType>();
5802 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5803
Chandler Carruth00a38332010-12-13 01:44:01 +00005804 // Flag if we encounter an arithmetic type.
5805 HasArithmeticOrEnumeralTypes =
5806 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5807
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005808 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5809 PointerTypes.insert(Ty);
5810 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005811 // Insert our type, and its more-qualified variants, into the set
5812 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005813 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005814 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005815 } else if (Ty->isMemberPointerType()) {
5816 // Member pointers are far easier, since the pointee can't be converted.
5817 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5818 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005819 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005820 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005821 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005822 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005823 // We treat vector types as arithmetic types in many contexts as an
5824 // extension.
5825 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005826 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005827 } else if (Ty->isNullPtrType()) {
5828 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005829 } else if (AllowUserConversions && TyRec) {
5830 // No conversion functions in incomplete types.
5831 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5832 return;
Mike Stump11289f42009-09-09 15:08:12 +00005833
Chandler Carruth00a38332010-12-13 01:44:01 +00005834 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5835 const UnresolvedSetImpl *Conversions
5836 = ClassDecl->getVisibleConversionFunctions();
5837 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5838 E = Conversions->end(); I != E; ++I) {
5839 NamedDecl *D = I.getDecl();
5840 if (isa<UsingShadowDecl>(D))
5841 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005842
Chandler Carruth00a38332010-12-13 01:44:01 +00005843 // Skip conversion function templates; they don't tell us anything
5844 // about which builtin types we can convert to.
5845 if (isa<FunctionTemplateDecl>(D))
5846 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005847
Chandler Carruth00a38332010-12-13 01:44:01 +00005848 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5849 if (AllowExplicitConversions || !Conv->isExplicit()) {
5850 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5851 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005852 }
5853 }
5854 }
5855}
5856
Douglas Gregor84605ae2009-08-24 13:43:27 +00005857/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5858/// the volatile- and non-volatile-qualified assignment operators for the
5859/// given type to the candidate set.
5860static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5861 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005862 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005863 unsigned NumArgs,
5864 OverloadCandidateSet &CandidateSet) {
5865 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005866
Douglas Gregor84605ae2009-08-24 13:43:27 +00005867 // T& operator=(T&, T)
5868 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5869 ParamTypes[1] = T;
5870 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5871 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005872
Douglas Gregor84605ae2009-08-24 13:43:27 +00005873 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5874 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005875 ParamTypes[0]
5876 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005877 ParamTypes[1] = T;
5878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005879 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005880 }
5881}
Mike Stump11289f42009-09-09 15:08:12 +00005882
Sebastian Redl1054fae2009-10-25 17:03:50 +00005883/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5884/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005885static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5886 Qualifiers VRQuals;
5887 const RecordType *TyRec;
5888 if (const MemberPointerType *RHSMPType =
5889 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005890 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005891 else
5892 TyRec = ArgExpr->getType()->getAs<RecordType>();
5893 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005894 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005895 VRQuals.addVolatile();
5896 VRQuals.addRestrict();
5897 return VRQuals;
5898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005900 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005901 if (!ClassDecl->hasDefinition())
5902 return VRQuals;
5903
John McCallad371252010-01-20 00:46:10 +00005904 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005905 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
John McCallad371252010-01-20 00:46:10 +00005907 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005908 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005909 NamedDecl *D = I.getDecl();
5910 if (isa<UsingShadowDecl>(D))
5911 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5912 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005913 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5914 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5915 CanTy = ResTypeRef->getPointeeType();
5916 // Need to go down the pointer/mempointer chain and add qualifiers
5917 // as see them.
5918 bool done = false;
5919 while (!done) {
5920 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5921 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005923 CanTy->getAs<MemberPointerType>())
5924 CanTy = ResTypeMPtr->getPointeeType();
5925 else
5926 done = true;
5927 if (CanTy.isVolatileQualified())
5928 VRQuals.addVolatile();
5929 if (CanTy.isRestrictQualified())
5930 VRQuals.addRestrict();
5931 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5932 return VRQuals;
5933 }
5934 }
5935 }
5936 return VRQuals;
5937}
John McCall52872982010-11-13 05:51:15 +00005938
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005939namespace {
John McCall52872982010-11-13 05:51:15 +00005940
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005941/// \brief Helper class to manage the addition of builtin operator overload
5942/// candidates. It provides shared state and utility methods used throughout
5943/// the process, as well as a helper method to add each group of builtin
5944/// operator overloads from the standard to a candidate set.
5945class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005946 // Common instance state available to all overload candidate addition methods.
5947 Sema &S;
5948 Expr **Args;
5949 unsigned NumArgs;
5950 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005951 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005952 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005953 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005954
Chandler Carruthc6586e52010-12-12 10:35:00 +00005955 // Define some constants used to index and iterate over the arithemetic types
5956 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005957 // The "promoted arithmetic types" are the arithmetic
5958 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005959 static const unsigned FirstIntegralType = 3;
5960 static const unsigned LastIntegralType = 18;
5961 static const unsigned FirstPromotedIntegralType = 3,
5962 LastPromotedIntegralType = 9;
5963 static const unsigned FirstPromotedArithmeticType = 0,
5964 LastPromotedArithmeticType = 9;
5965 static const unsigned NumArithmeticTypes = 18;
5966
Chandler Carruthc6586e52010-12-12 10:35:00 +00005967 /// \brief Get the canonical type for a given arithmetic type index.
5968 CanQualType getArithmeticType(unsigned index) {
5969 assert(index < NumArithmeticTypes);
5970 static CanQualType ASTContext::* const
5971 ArithmeticTypes[NumArithmeticTypes] = {
5972 // Start of promoted types.
5973 &ASTContext::FloatTy,
5974 &ASTContext::DoubleTy,
5975 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005976
Chandler Carruthc6586e52010-12-12 10:35:00 +00005977 // Start of integral types.
5978 &ASTContext::IntTy,
5979 &ASTContext::LongTy,
5980 &ASTContext::LongLongTy,
5981 &ASTContext::UnsignedIntTy,
5982 &ASTContext::UnsignedLongTy,
5983 &ASTContext::UnsignedLongLongTy,
5984 // End of promoted types.
5985
5986 &ASTContext::BoolTy,
5987 &ASTContext::CharTy,
5988 &ASTContext::WCharTy,
5989 &ASTContext::Char16Ty,
5990 &ASTContext::Char32Ty,
5991 &ASTContext::SignedCharTy,
5992 &ASTContext::ShortTy,
5993 &ASTContext::UnsignedCharTy,
5994 &ASTContext::UnsignedShortTy,
5995 // End of integral types.
5996 // FIXME: What about complex?
5997 };
5998 return S.Context.*ArithmeticTypes[index];
5999 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006000
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006001 /// \brief Gets the canonical type resulting from the usual arithemetic
6002 /// converions for the given arithmetic types.
6003 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6004 // Accelerator table for performing the usual arithmetic conversions.
6005 // The rules are basically:
6006 // - if either is floating-point, use the wider floating-point
6007 // - if same signedness, use the higher rank
6008 // - if same size, use unsigned of the higher rank
6009 // - use the larger type
6010 // These rules, together with the axiom that higher ranks are
6011 // never smaller, are sufficient to precompute all of these results
6012 // *except* when dealing with signed types of higher rank.
6013 // (we could precompute SLL x UI for all known platforms, but it's
6014 // better not to make any assumptions).
6015 enum PromotedType {
6016 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6017 };
6018 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6019 [LastPromotedArithmeticType] = {
6020 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6021 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6022 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6023 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6024 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6025 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6026 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6027 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6028 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6029 };
6030
6031 assert(L < LastPromotedArithmeticType);
6032 assert(R < LastPromotedArithmeticType);
6033 int Idx = ConversionsTable[L][R];
6034
6035 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006036 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006037
6038 // Slow path: we need to compare widths.
6039 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006040 CanQualType LT = getArithmeticType(L),
6041 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006042 unsigned LW = S.Context.getIntWidth(LT),
6043 RW = S.Context.getIntWidth(RT);
6044
6045 // If they're different widths, use the signed type.
6046 if (LW > RW) return LT;
6047 else if (LW < RW) return RT;
6048
6049 // Otherwise, use the unsigned type of the signed type's rank.
6050 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6051 assert(L == SLL || R == SLL);
6052 return S.Context.UnsignedLongLongTy;
6053 }
6054
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006055 /// \brief Helper method to factor out the common pattern of adding overloads
6056 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006057 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6058 bool HasVolatile) {
6059 QualType ParamTypes[2] = {
6060 S.Context.getLValueReferenceType(CandidateTy),
6061 S.Context.IntTy
6062 };
6063
6064 // Non-volatile version.
6065 if (NumArgs == 1)
6066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6067 else
6068 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6069
6070 // Use a heuristic to reduce number of builtin candidates in the set:
6071 // add volatile version only if there are conversions to a volatile type.
6072 if (HasVolatile) {
6073 ParamTypes[0] =
6074 S.Context.getLValueReferenceType(
6075 S.Context.getVolatileType(CandidateTy));
6076 if (NumArgs == 1)
6077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6078 else
6079 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6080 }
6081 }
6082
6083public:
6084 BuiltinOperatorOverloadBuilder(
6085 Sema &S, Expr **Args, unsigned NumArgs,
6086 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006087 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006088 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006089 OverloadCandidateSet &CandidateSet)
6090 : S(S), Args(Args), NumArgs(NumArgs),
6091 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006092 HasArithmeticOrEnumeralCandidateType(
6093 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006094 CandidateTypes(CandidateTypes),
6095 CandidateSet(CandidateSet) {
6096 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006097 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006098 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006099 assert(getArithmeticType(LastPromotedIntegralType - 1)
6100 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006101 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006102 assert(getArithmeticType(FirstPromotedArithmeticType)
6103 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006104 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006105 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6106 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006107 "Invalid last promoted arithmetic type");
6108 }
6109
6110 // C++ [over.built]p3:
6111 //
6112 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6113 // is either volatile or empty, there exist candidate operator
6114 // functions of the form
6115 //
6116 // VQ T& operator++(VQ T&);
6117 // T operator++(VQ T&, int);
6118 //
6119 // C++ [over.built]p4:
6120 //
6121 // For every pair (T, VQ), where T is an arithmetic type other
6122 // than bool, and VQ is either volatile or empty, there exist
6123 // candidate operator functions of the form
6124 //
6125 // VQ T& operator--(VQ T&);
6126 // T operator--(VQ T&, int);
6127 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006128 if (!HasArithmeticOrEnumeralCandidateType)
6129 return;
6130
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006131 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6132 Arith < NumArithmeticTypes; ++Arith) {
6133 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006134 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006135 VisibleTypeConversionsQuals.hasVolatile());
6136 }
6137 }
6138
6139 // C++ [over.built]p5:
6140 //
6141 // For every pair (T, VQ), where T is a cv-qualified or
6142 // cv-unqualified object type, and VQ is either volatile or
6143 // empty, there exist candidate operator functions of the form
6144 //
6145 // T*VQ& operator++(T*VQ&);
6146 // T*VQ& operator--(T*VQ&);
6147 // T* operator++(T*VQ&, int);
6148 // T* operator--(T*VQ&, int);
6149 void addPlusPlusMinusMinusPointerOverloads() {
6150 for (BuiltinCandidateTypeSet::iterator
6151 Ptr = CandidateTypes[0].pointer_begin(),
6152 PtrEnd = CandidateTypes[0].pointer_end();
6153 Ptr != PtrEnd; ++Ptr) {
6154 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006155 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006156 continue;
6157
6158 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6159 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6160 VisibleTypeConversionsQuals.hasVolatile()));
6161 }
6162 }
6163
6164 // C++ [over.built]p6:
6165 // For every cv-qualified or cv-unqualified object type T, there
6166 // exist candidate operator functions of the form
6167 //
6168 // T& operator*(T*);
6169 //
6170 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006172 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006173 // T& operator*(T*);
6174 void addUnaryStarPointerOverloads() {
6175 for (BuiltinCandidateTypeSet::iterator
6176 Ptr = CandidateTypes[0].pointer_begin(),
6177 PtrEnd = CandidateTypes[0].pointer_end();
6178 Ptr != PtrEnd; ++Ptr) {
6179 QualType ParamTy = *Ptr;
6180 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006181 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6182 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006183
Douglas Gregor02824322011-01-26 19:30:28 +00006184 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6185 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6186 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006187
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006188 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6189 &ParamTy, Args, 1, CandidateSet);
6190 }
6191 }
6192
6193 // C++ [over.built]p9:
6194 // For every promoted arithmetic type T, there exist candidate
6195 // operator functions of the form
6196 //
6197 // T operator+(T);
6198 // T operator-(T);
6199 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006200 if (!HasArithmeticOrEnumeralCandidateType)
6201 return;
6202
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006203 for (unsigned Arith = FirstPromotedArithmeticType;
6204 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006205 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006206 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6207 }
6208
6209 // Extension: We also add these operators for vector types.
6210 for (BuiltinCandidateTypeSet::iterator
6211 Vec = CandidateTypes[0].vector_begin(),
6212 VecEnd = CandidateTypes[0].vector_end();
6213 Vec != VecEnd; ++Vec) {
6214 QualType VecTy = *Vec;
6215 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6216 }
6217 }
6218
6219 // C++ [over.built]p8:
6220 // For every type T, there exist candidate operator functions of
6221 // the form
6222 //
6223 // T* operator+(T*);
6224 void addUnaryPlusPointerOverloads() {
6225 for (BuiltinCandidateTypeSet::iterator
6226 Ptr = CandidateTypes[0].pointer_begin(),
6227 PtrEnd = CandidateTypes[0].pointer_end();
6228 Ptr != PtrEnd; ++Ptr) {
6229 QualType ParamTy = *Ptr;
6230 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6231 }
6232 }
6233
6234 // C++ [over.built]p10:
6235 // For every promoted integral type T, there exist candidate
6236 // operator functions of the form
6237 //
6238 // T operator~(T);
6239 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006240 if (!HasArithmeticOrEnumeralCandidateType)
6241 return;
6242
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006243 for (unsigned Int = FirstPromotedIntegralType;
6244 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006245 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006246 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6247 }
6248
6249 // Extension: We also add this operator for vector types.
6250 for (BuiltinCandidateTypeSet::iterator
6251 Vec = CandidateTypes[0].vector_begin(),
6252 VecEnd = CandidateTypes[0].vector_end();
6253 Vec != VecEnd; ++Vec) {
6254 QualType VecTy = *Vec;
6255 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6256 }
6257 }
6258
6259 // C++ [over.match.oper]p16:
6260 // For every pointer to member type T, there exist candidate operator
6261 // functions of the form
6262 //
6263 // bool operator==(T,T);
6264 // bool operator!=(T,T);
6265 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6266 /// Set of (canonical) types that we've already handled.
6267 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6268
6269 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6270 for (BuiltinCandidateTypeSet::iterator
6271 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6272 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6273 MemPtr != MemPtrEnd;
6274 ++MemPtr) {
6275 // Don't add the same builtin candidate twice.
6276 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6277 continue;
6278
6279 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6280 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6281 CandidateSet);
6282 }
6283 }
6284 }
6285
6286 // C++ [over.built]p15:
6287 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006288 // For every T, where T is an enumeration type, a pointer type, or
6289 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290 //
6291 // bool operator<(T, T);
6292 // bool operator>(T, T);
6293 // bool operator<=(T, T);
6294 // bool operator>=(T, T);
6295 // bool operator==(T, T);
6296 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006297 void addRelationalPointerOrEnumeralOverloads() {
6298 // C++ [over.built]p1:
6299 // If there is a user-written candidate with the same name and parameter
6300 // types as a built-in candidate operator function, the built-in operator
6301 // function is hidden and is not included in the set of candidate
6302 // functions.
6303 //
6304 // The text is actually in a note, but if we don't implement it then we end
6305 // up with ambiguities when the user provides an overloaded operator for
6306 // an enumeration type. Note that only enumeration types have this problem,
6307 // so we track which enumeration types we've seen operators for. Also, the
6308 // only other overloaded operator with enumeration argumenst, operator=,
6309 // cannot be overloaded for enumeration types, so this is the only place
6310 // where we must suppress candidates like this.
6311 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6312 UserDefinedBinaryOperators;
6313
6314 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6315 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6316 CandidateTypes[ArgIdx].enumeration_end()) {
6317 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6318 CEnd = CandidateSet.end();
6319 C != CEnd; ++C) {
6320 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6321 continue;
6322
6323 QualType FirstParamType =
6324 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6325 QualType SecondParamType =
6326 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6327
6328 // Skip if either parameter isn't of enumeral type.
6329 if (!FirstParamType->isEnumeralType() ||
6330 !SecondParamType->isEnumeralType())
6331 continue;
6332
6333 // Add this operator to the set of known user-defined operators.
6334 UserDefinedBinaryOperators.insert(
6335 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6336 S.Context.getCanonicalType(SecondParamType)));
6337 }
6338 }
6339 }
6340
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006341 /// Set of (canonical) types that we've already handled.
6342 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6343
6344 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6345 for (BuiltinCandidateTypeSet::iterator
6346 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6347 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6348 Ptr != PtrEnd; ++Ptr) {
6349 // Don't add the same builtin candidate twice.
6350 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6351 continue;
6352
6353 QualType ParamTypes[2] = { *Ptr, *Ptr };
6354 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6355 CandidateSet);
6356 }
6357 for (BuiltinCandidateTypeSet::iterator
6358 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6359 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6360 Enum != EnumEnd; ++Enum) {
6361 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6362
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006363 // Don't add the same builtin candidate twice, or if a user defined
6364 // candidate exists.
6365 if (!AddedTypes.insert(CanonType) ||
6366 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6367 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006368 continue;
6369
6370 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006371 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6372 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006373 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006374
6375 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6376 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6377 if (AddedTypes.insert(NullPtrTy) &&
6378 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6379 NullPtrTy))) {
6380 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6381 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6382 CandidateSet);
6383 }
6384 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006385 }
6386 }
6387
6388 // C++ [over.built]p13:
6389 //
6390 // For every cv-qualified or cv-unqualified object type T
6391 // there exist candidate operator functions of the form
6392 //
6393 // T* operator+(T*, ptrdiff_t);
6394 // T& operator[](T*, ptrdiff_t); [BELOW]
6395 // T* operator-(T*, ptrdiff_t);
6396 // T* operator+(ptrdiff_t, T*);
6397 // T& operator[](ptrdiff_t, T*); [BELOW]
6398 //
6399 // C++ [over.built]p14:
6400 //
6401 // For every T, where T is a pointer to object type, there
6402 // exist candidate operator functions of the form
6403 //
6404 // ptrdiff_t operator-(T, T);
6405 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6406 /// Set of (canonical) types that we've already handled.
6407 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6408
6409 for (int Arg = 0; Arg < 2; ++Arg) {
6410 QualType AsymetricParamTypes[2] = {
6411 S.Context.getPointerDiffType(),
6412 S.Context.getPointerDiffType(),
6413 };
6414 for (BuiltinCandidateTypeSet::iterator
6415 Ptr = CandidateTypes[Arg].pointer_begin(),
6416 PtrEnd = CandidateTypes[Arg].pointer_end();
6417 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006418 QualType PointeeTy = (*Ptr)->getPointeeType();
6419 if (!PointeeTy->isObjectType())
6420 continue;
6421
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006422 AsymetricParamTypes[Arg] = *Ptr;
6423 if (Arg == 0 || Op == OO_Plus) {
6424 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6425 // T* operator+(ptrdiff_t, T*);
6426 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6427 CandidateSet);
6428 }
6429 if (Op == OO_Minus) {
6430 // ptrdiff_t operator-(T, T);
6431 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6432 continue;
6433
6434 QualType ParamTypes[2] = { *Ptr, *Ptr };
6435 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6436 Args, 2, CandidateSet);
6437 }
6438 }
6439 }
6440 }
6441
6442 // C++ [over.built]p12:
6443 //
6444 // For every pair of promoted arithmetic types L and R, there
6445 // exist candidate operator functions of the form
6446 //
6447 // LR operator*(L, R);
6448 // LR operator/(L, R);
6449 // LR operator+(L, R);
6450 // LR operator-(L, R);
6451 // bool operator<(L, R);
6452 // bool operator>(L, R);
6453 // bool operator<=(L, R);
6454 // bool operator>=(L, R);
6455 // bool operator==(L, R);
6456 // bool operator!=(L, R);
6457 //
6458 // where LR is the result of the usual arithmetic conversions
6459 // between types L and R.
6460 //
6461 // C++ [over.built]p24:
6462 //
6463 // For every pair of promoted arithmetic types L and R, there exist
6464 // candidate operator functions of the form
6465 //
6466 // LR operator?(bool, L, R);
6467 //
6468 // where LR is the result of the usual arithmetic conversions
6469 // between types L and R.
6470 // Our candidates ignore the first parameter.
6471 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006472 if (!HasArithmeticOrEnumeralCandidateType)
6473 return;
6474
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006475 for (unsigned Left = FirstPromotedArithmeticType;
6476 Left < LastPromotedArithmeticType; ++Left) {
6477 for (unsigned Right = FirstPromotedArithmeticType;
6478 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006479 QualType LandR[2] = { getArithmeticType(Left),
6480 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006481 QualType Result =
6482 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006483 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006484 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6485 }
6486 }
6487
6488 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6489 // conditional operator for vector types.
6490 for (BuiltinCandidateTypeSet::iterator
6491 Vec1 = CandidateTypes[0].vector_begin(),
6492 Vec1End = CandidateTypes[0].vector_end();
6493 Vec1 != Vec1End; ++Vec1) {
6494 for (BuiltinCandidateTypeSet::iterator
6495 Vec2 = CandidateTypes[1].vector_begin(),
6496 Vec2End = CandidateTypes[1].vector_end();
6497 Vec2 != Vec2End; ++Vec2) {
6498 QualType LandR[2] = { *Vec1, *Vec2 };
6499 QualType Result = S.Context.BoolTy;
6500 if (!isComparison) {
6501 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6502 Result = *Vec1;
6503 else
6504 Result = *Vec2;
6505 }
6506
6507 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6508 }
6509 }
6510 }
6511
6512 // C++ [over.built]p17:
6513 //
6514 // For every pair of promoted integral types L and R, there
6515 // exist candidate operator functions of the form
6516 //
6517 // LR operator%(L, R);
6518 // LR operator&(L, R);
6519 // LR operator^(L, R);
6520 // LR operator|(L, R);
6521 // L operator<<(L, R);
6522 // L operator>>(L, R);
6523 //
6524 // where LR is the result of the usual arithmetic conversions
6525 // between types L and R.
6526 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006527 if (!HasArithmeticOrEnumeralCandidateType)
6528 return;
6529
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006530 for (unsigned Left = FirstPromotedIntegralType;
6531 Left < LastPromotedIntegralType; ++Left) {
6532 for (unsigned Right = FirstPromotedIntegralType;
6533 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006534 QualType LandR[2] = { getArithmeticType(Left),
6535 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006536 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6537 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006538 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006539 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6540 }
6541 }
6542 }
6543
6544 // C++ [over.built]p20:
6545 //
6546 // For every pair (T, VQ), where T is an enumeration or
6547 // pointer to member type and VQ is either volatile or
6548 // empty, there exist candidate operator functions of the form
6549 //
6550 // VQ T& operator=(VQ T&, T);
6551 void addAssignmentMemberPointerOrEnumeralOverloads() {
6552 /// Set of (canonical) types that we've already handled.
6553 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6554
6555 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6556 for (BuiltinCandidateTypeSet::iterator
6557 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6558 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6559 Enum != EnumEnd; ++Enum) {
6560 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6561 continue;
6562
6563 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6564 CandidateSet);
6565 }
6566
6567 for (BuiltinCandidateTypeSet::iterator
6568 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6569 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6570 MemPtr != MemPtrEnd; ++MemPtr) {
6571 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6572 continue;
6573
6574 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6575 CandidateSet);
6576 }
6577 }
6578 }
6579
6580 // C++ [over.built]p19:
6581 //
6582 // For every pair (T, VQ), where T is any type and VQ is either
6583 // volatile or empty, there exist candidate operator functions
6584 // of the form
6585 //
6586 // T*VQ& operator=(T*VQ&, T*);
6587 //
6588 // C++ [over.built]p21:
6589 //
6590 // For every pair (T, VQ), where T is a cv-qualified or
6591 // cv-unqualified object type and VQ is either volatile or
6592 // empty, there exist candidate operator functions of the form
6593 //
6594 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6595 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6596 void addAssignmentPointerOverloads(bool isEqualOp) {
6597 /// Set of (canonical) types that we've already handled.
6598 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6599
6600 for (BuiltinCandidateTypeSet::iterator
6601 Ptr = CandidateTypes[0].pointer_begin(),
6602 PtrEnd = CandidateTypes[0].pointer_end();
6603 Ptr != PtrEnd; ++Ptr) {
6604 // If this is operator=, keep track of the builtin candidates we added.
6605 if (isEqualOp)
6606 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006607 else if (!(*Ptr)->getPointeeType()->isObjectType())
6608 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006609
6610 // non-volatile version
6611 QualType ParamTypes[2] = {
6612 S.Context.getLValueReferenceType(*Ptr),
6613 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6614 };
6615 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6616 /*IsAssigmentOperator=*/ isEqualOp);
6617
6618 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6619 VisibleTypeConversionsQuals.hasVolatile()) {
6620 // volatile version
6621 ParamTypes[0] =
6622 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6623 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6624 /*IsAssigmentOperator=*/isEqualOp);
6625 }
6626 }
6627
6628 if (isEqualOp) {
6629 for (BuiltinCandidateTypeSet::iterator
6630 Ptr = CandidateTypes[1].pointer_begin(),
6631 PtrEnd = CandidateTypes[1].pointer_end();
6632 Ptr != PtrEnd; ++Ptr) {
6633 // Make sure we don't add the same candidate twice.
6634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6635 continue;
6636
Chandler Carruth8e543b32010-12-12 08:17:55 +00006637 QualType ParamTypes[2] = {
6638 S.Context.getLValueReferenceType(*Ptr),
6639 *Ptr,
6640 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006641
6642 // non-volatile version
6643 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6644 /*IsAssigmentOperator=*/true);
6645
6646 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6647 VisibleTypeConversionsQuals.hasVolatile()) {
6648 // volatile version
6649 ParamTypes[0] =
6650 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006651 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6652 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006653 }
6654 }
6655 }
6656 }
6657
6658 // C++ [over.built]p18:
6659 //
6660 // For every triple (L, VQ, R), where L is an arithmetic type,
6661 // VQ is either volatile or empty, and R is a promoted
6662 // arithmetic type, there exist candidate operator functions of
6663 // the form
6664 //
6665 // VQ L& operator=(VQ L&, R);
6666 // VQ L& operator*=(VQ L&, R);
6667 // VQ L& operator/=(VQ L&, R);
6668 // VQ L& operator+=(VQ L&, R);
6669 // VQ L& operator-=(VQ L&, R);
6670 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006671 if (!HasArithmeticOrEnumeralCandidateType)
6672 return;
6673
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006674 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6675 for (unsigned Right = FirstPromotedArithmeticType;
6676 Right < LastPromotedArithmeticType; ++Right) {
6677 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006678 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006679
6680 // Add this built-in operator as a candidate (VQ is empty).
6681 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006682 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6684 /*IsAssigmentOperator=*/isEqualOp);
6685
6686 // Add this built-in operator as a candidate (VQ is 'volatile').
6687 if (VisibleTypeConversionsQuals.hasVolatile()) {
6688 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006689 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006690 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006691 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6692 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006693 /*IsAssigmentOperator=*/isEqualOp);
6694 }
6695 }
6696 }
6697
6698 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6699 for (BuiltinCandidateTypeSet::iterator
6700 Vec1 = CandidateTypes[0].vector_begin(),
6701 Vec1End = CandidateTypes[0].vector_end();
6702 Vec1 != Vec1End; ++Vec1) {
6703 for (BuiltinCandidateTypeSet::iterator
6704 Vec2 = CandidateTypes[1].vector_begin(),
6705 Vec2End = CandidateTypes[1].vector_end();
6706 Vec2 != Vec2End; ++Vec2) {
6707 QualType ParamTypes[2];
6708 ParamTypes[1] = *Vec2;
6709 // Add this built-in operator as a candidate (VQ is empty).
6710 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6711 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6712 /*IsAssigmentOperator=*/isEqualOp);
6713
6714 // Add this built-in operator as a candidate (VQ is 'volatile').
6715 if (VisibleTypeConversionsQuals.hasVolatile()) {
6716 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6717 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6719 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006720 /*IsAssigmentOperator=*/isEqualOp);
6721 }
6722 }
6723 }
6724 }
6725
6726 // C++ [over.built]p22:
6727 //
6728 // For every triple (L, VQ, R), where L is an integral type, VQ
6729 // is either volatile or empty, and R is a promoted integral
6730 // type, there exist candidate operator functions of the form
6731 //
6732 // VQ L& operator%=(VQ L&, R);
6733 // VQ L& operator<<=(VQ L&, R);
6734 // VQ L& operator>>=(VQ L&, R);
6735 // VQ L& operator&=(VQ L&, R);
6736 // VQ L& operator^=(VQ L&, R);
6737 // VQ L& operator|=(VQ L&, R);
6738 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006739 if (!HasArithmeticOrEnumeralCandidateType)
6740 return;
6741
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006742 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6743 for (unsigned Right = FirstPromotedIntegralType;
6744 Right < LastPromotedIntegralType; ++Right) {
6745 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006746 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006747
6748 // Add this built-in operator as a candidate (VQ is empty).
6749 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006750 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006751 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6752 if (VisibleTypeConversionsQuals.hasVolatile()) {
6753 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006754 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006755 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6756 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6757 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6758 CandidateSet);
6759 }
6760 }
6761 }
6762 }
6763
6764 // C++ [over.operator]p23:
6765 //
6766 // There also exist candidate operator functions of the form
6767 //
6768 // bool operator!(bool);
6769 // bool operator&&(bool, bool);
6770 // bool operator||(bool, bool);
6771 void addExclaimOverload() {
6772 QualType ParamTy = S.Context.BoolTy;
6773 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6774 /*IsAssignmentOperator=*/false,
6775 /*NumContextualBoolArguments=*/1);
6776 }
6777 void addAmpAmpOrPipePipeOverload() {
6778 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6779 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6780 /*IsAssignmentOperator=*/false,
6781 /*NumContextualBoolArguments=*/2);
6782 }
6783
6784 // C++ [over.built]p13:
6785 //
6786 // For every cv-qualified or cv-unqualified object type T there
6787 // exist candidate operator functions of the form
6788 //
6789 // T* operator+(T*, ptrdiff_t); [ABOVE]
6790 // T& operator[](T*, ptrdiff_t);
6791 // T* operator-(T*, ptrdiff_t); [ABOVE]
6792 // T* operator+(ptrdiff_t, T*); [ABOVE]
6793 // T& operator[](ptrdiff_t, T*);
6794 void addSubscriptOverloads() {
6795 for (BuiltinCandidateTypeSet::iterator
6796 Ptr = CandidateTypes[0].pointer_begin(),
6797 PtrEnd = CandidateTypes[0].pointer_end();
6798 Ptr != PtrEnd; ++Ptr) {
6799 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6800 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006801 if (!PointeeType->isObjectType())
6802 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006803
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006804 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6805
6806 // T& operator[](T*, ptrdiff_t)
6807 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6808 }
6809
6810 for (BuiltinCandidateTypeSet::iterator
6811 Ptr = CandidateTypes[1].pointer_begin(),
6812 PtrEnd = CandidateTypes[1].pointer_end();
6813 Ptr != PtrEnd; ++Ptr) {
6814 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6815 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006816 if (!PointeeType->isObjectType())
6817 continue;
6818
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006819 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6820
6821 // T& operator[](ptrdiff_t, T*)
6822 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6823 }
6824 }
6825
6826 // C++ [over.built]p11:
6827 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6828 // C1 is the same type as C2 or is a derived class of C2, T is an object
6829 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6830 // there exist candidate operator functions of the form
6831 //
6832 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6833 //
6834 // where CV12 is the union of CV1 and CV2.
6835 void addArrowStarOverloads() {
6836 for (BuiltinCandidateTypeSet::iterator
6837 Ptr = CandidateTypes[0].pointer_begin(),
6838 PtrEnd = CandidateTypes[0].pointer_end();
6839 Ptr != PtrEnd; ++Ptr) {
6840 QualType C1Ty = (*Ptr);
6841 QualType C1;
6842 QualifierCollector Q1;
6843 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6844 if (!isa<RecordType>(C1))
6845 continue;
6846 // heuristic to reduce number of builtin candidates in the set.
6847 // Add volatile/restrict version only if there are conversions to a
6848 // volatile/restrict type.
6849 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6850 continue;
6851 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6852 continue;
6853 for (BuiltinCandidateTypeSet::iterator
6854 MemPtr = CandidateTypes[1].member_pointer_begin(),
6855 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6856 MemPtr != MemPtrEnd; ++MemPtr) {
6857 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6858 QualType C2 = QualType(mptr->getClass(), 0);
6859 C2 = C2.getUnqualifiedType();
6860 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6861 break;
6862 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6863 // build CV12 T&
6864 QualType T = mptr->getPointeeType();
6865 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6866 T.isVolatileQualified())
6867 continue;
6868 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6869 T.isRestrictQualified())
6870 continue;
6871 T = Q1.apply(S.Context, T);
6872 QualType ResultTy = S.Context.getLValueReferenceType(T);
6873 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6874 }
6875 }
6876 }
6877
6878 // Note that we don't consider the first argument, since it has been
6879 // contextually converted to bool long ago. The candidates below are
6880 // therefore added as binary.
6881 //
6882 // C++ [over.built]p25:
6883 // For every type T, where T is a pointer, pointer-to-member, or scoped
6884 // enumeration type, there exist candidate operator functions of the form
6885 //
6886 // T operator?(bool, T, T);
6887 //
6888 void addConditionalOperatorOverloads() {
6889 /// Set of (canonical) types that we've already handled.
6890 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6891
6892 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6893 for (BuiltinCandidateTypeSet::iterator
6894 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6895 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6896 Ptr != PtrEnd; ++Ptr) {
6897 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6898 continue;
6899
6900 QualType ParamTypes[2] = { *Ptr, *Ptr };
6901 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6902 }
6903
6904 for (BuiltinCandidateTypeSet::iterator
6905 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6906 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6907 MemPtr != MemPtrEnd; ++MemPtr) {
6908 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6909 continue;
6910
6911 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6912 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6913 }
6914
6915 if (S.getLangOptions().CPlusPlus0x) {
6916 for (BuiltinCandidateTypeSet::iterator
6917 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6918 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6919 Enum != EnumEnd; ++Enum) {
6920 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6921 continue;
6922
6923 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6924 continue;
6925
6926 QualType ParamTypes[2] = { *Enum, *Enum };
6927 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6928 }
6929 }
6930 }
6931 }
6932};
6933
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006934} // end anonymous namespace
6935
6936/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6937/// operator overloads to the candidate set (C++ [over.built]), based
6938/// on the operator @p Op and the arguments given. For example, if the
6939/// operator is a binary '+', this routine might add "int
6940/// operator+(int, int)" to cover integer addition.
6941void
6942Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6943 SourceLocation OpLoc,
6944 Expr **Args, unsigned NumArgs,
6945 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006946 // Find all of the types that the arguments can convert to, but only
6947 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006948 // that make use of these types. Also record whether we encounter non-record
6949 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006950 Qualifiers VisibleTypeConversionsQuals;
6951 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006952 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6953 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006954
6955 bool HasNonRecordCandidateType = false;
6956 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006957 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006958 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6959 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6960 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6961 OpLoc,
6962 true,
6963 (Op == OO_Exclaim ||
6964 Op == OO_AmpAmp ||
6965 Op == OO_PipePipe),
6966 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006967 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6968 CandidateTypes[ArgIdx].hasNonRecordTypes();
6969 HasArithmeticOrEnumeralCandidateType =
6970 HasArithmeticOrEnumeralCandidateType ||
6971 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006972 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006973
Chandler Carruth00a38332010-12-13 01:44:01 +00006974 // Exit early when no non-record types have been added to the candidate set
6975 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006976 //
6977 // We can't exit early for !, ||, or &&, since there we have always have
6978 // 'bool' overloads.
6979 if (!HasNonRecordCandidateType &&
6980 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006981 return;
6982
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006983 // Setup an object to manage the common state for building overloads.
6984 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6985 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006986 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006987 CandidateTypes, CandidateSet);
6988
6989 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006990 switch (Op) {
6991 case OO_None:
6992 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006993 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006994
Chandler Carruth5184de02010-12-12 08:51:33 +00006995 case OO_New:
6996 case OO_Delete:
6997 case OO_Array_New:
6998 case OO_Array_Delete:
6999 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007000 llvm_unreachable(
7001 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007002
7003 case OO_Comma:
7004 case OO_Arrow:
7005 // C++ [over.match.oper]p3:
7006 // -- For the operator ',', the unary operator '&', or the
7007 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007008 break;
7009
7010 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007011 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007013 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007014
7015 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007016 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007017 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007018 } else {
7019 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7020 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7021 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007022 break;
7023
Chandler Carruth5184de02010-12-12 08:51:33 +00007024 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007025 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007026 OpBuilder.addUnaryStarPointerOverloads();
7027 else
7028 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7029 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007030
Chandler Carruth5184de02010-12-12 08:51:33 +00007031 case OO_Slash:
7032 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007033 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007034
7035 case OO_PlusPlus:
7036 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007037 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7038 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007039 break;
7040
Douglas Gregor84605ae2009-08-24 13:43:27 +00007041 case OO_EqualEqual:
7042 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007043 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007044 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007045
Douglas Gregora11693b2008-11-12 17:17:38 +00007046 case OO_Less:
7047 case OO_Greater:
7048 case OO_LessEqual:
7049 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007050 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007051 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7052 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007053
Douglas Gregora11693b2008-11-12 17:17:38 +00007054 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007055 case OO_Caret:
7056 case OO_Pipe:
7057 case OO_LessLess:
7058 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007059 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007060 break;
7061
Chandler Carruth5184de02010-12-12 08:51:33 +00007062 case OO_Amp: // '&' is either unary or binary
7063 if (NumArgs == 1)
7064 // C++ [over.match.oper]p3:
7065 // -- For the operator ',', the unary operator '&', or the
7066 // operator '->', the built-in candidates set is empty.
7067 break;
7068
7069 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7070 break;
7071
7072 case OO_Tilde:
7073 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7074 break;
7075
Douglas Gregora11693b2008-11-12 17:17:38 +00007076 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007077 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007078 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007079
7080 case OO_PlusEqual:
7081 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007082 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007083 // Fall through.
7084
7085 case OO_StarEqual:
7086 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007087 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007088 break;
7089
7090 case OO_PercentEqual:
7091 case OO_LessLessEqual:
7092 case OO_GreaterGreaterEqual:
7093 case OO_AmpEqual:
7094 case OO_CaretEqual:
7095 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007096 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007097 break;
7098
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007099 case OO_Exclaim:
7100 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007101 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007102
Douglas Gregora11693b2008-11-12 17:17:38 +00007103 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007104 case OO_PipePipe:
7105 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007106 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007107
7108 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007109 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007110 break;
7111
7112 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007113 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007114 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007115
7116 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007117 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007118 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7119 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007120 }
7121}
7122
Douglas Gregore254f902009-02-04 00:32:51 +00007123/// \brief Add function candidates found via argument-dependent lookup
7124/// to the set of overloading candidates.
7125///
7126/// This routine performs argument-dependent name lookup based on the
7127/// given function name (which may also be an operator name) and adds
7128/// all of the overload candidates found by ADL to the overload
7129/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007130void
Douglas Gregore254f902009-02-04 00:32:51 +00007131Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00007132 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00007133 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007134 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007135 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007136 bool PartialOverloading,
7137 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007138 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007139
John McCall91f61fc2010-01-26 06:04:06 +00007140 // FIXME: This approach for uniquing ADL results (and removing
7141 // redundant candidates from the set) relies on pointer-equality,
7142 // which means we need to key off the canonical decl. However,
7143 // always going back to the canonical decl might not get us the
7144 // right set of default arguments. What default arguments are
7145 // we supposed to consider on ADL candidates, anyway?
7146
Douglas Gregorcabea402009-09-22 15:41:20 +00007147 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00007148 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7149 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007150
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007151 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007152 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7153 CandEnd = CandidateSet.end();
7154 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007155 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007156 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007157 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007158 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007159 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007160
7161 // For each of the ADL candidates we found, add it to the overload
7162 // set.
John McCall8fe68082010-01-26 07:16:45 +00007163 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007164 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007165 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007166 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007167 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007168
John McCalla0296f72010-03-19 07:35:19 +00007169 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007170 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007171 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007172 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007173 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00007174 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007175 }
Douglas Gregore254f902009-02-04 00:32:51 +00007176}
7177
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007178/// isBetterOverloadCandidate - Determines whether the first overload
7179/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007180bool
John McCall5c32be02010-08-24 20:38:10 +00007181isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007182 const OverloadCandidate &Cand1,
7183 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007184 SourceLocation Loc,
7185 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007186 // Define viable functions to be better candidates than non-viable
7187 // functions.
7188 if (!Cand2.Viable)
7189 return Cand1.Viable;
7190 else if (!Cand1.Viable)
7191 return false;
7192
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007193 // C++ [over.match.best]p1:
7194 //
7195 // -- if F is a static member function, ICS1(F) is defined such
7196 // that ICS1(F) is neither better nor worse than ICS1(G) for
7197 // any function G, and, symmetrically, ICS1(G) is neither
7198 // better nor worse than ICS1(F).
7199 unsigned StartArg = 0;
7200 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7201 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007202
Douglas Gregord3cb3562009-07-07 23:38:56 +00007203 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007204 // A viable function F1 is defined to be a better function than another
7205 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007206 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007207 unsigned NumArgs = Cand1.NumConversions;
7208 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007209 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007210 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007211 switch (CompareImplicitConversionSequences(S,
7212 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007213 Cand2.Conversions[ArgIdx])) {
7214 case ImplicitConversionSequence::Better:
7215 // Cand1 has a better conversion sequence.
7216 HasBetterConversion = true;
7217 break;
7218
7219 case ImplicitConversionSequence::Worse:
7220 // Cand1 can't be better than Cand2.
7221 return false;
7222
7223 case ImplicitConversionSequence::Indistinguishable:
7224 // Do nothing.
7225 break;
7226 }
7227 }
7228
Mike Stump11289f42009-09-09 15:08:12 +00007229 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007230 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007231 if (HasBetterConversion)
7232 return true;
7233
Mike Stump11289f42009-09-09 15:08:12 +00007234 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007235 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007236 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007237 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7238 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007239
7240 // -- F1 and F2 are function template specializations, and the function
7241 // template for F1 is more specialized than the template for F2
7242 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007243 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007244 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007245 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007246 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007247 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7248 Cand2.Function->getPrimaryTemplate(),
7249 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007250 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007251 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007252 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007253 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007255
Douglas Gregora1f013e2008-11-07 22:36:19 +00007256 // -- the context is an initialization by user-defined conversion
7257 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7258 // from the return type of F1 to the destination type (i.e.,
7259 // the type of the entity being initialized) is a better
7260 // conversion sequence than the standard conversion sequence
7261 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007262 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007263 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007264 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007265 switch (CompareStandardConversionSequences(S,
7266 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007267 Cand2.FinalConversion)) {
7268 case ImplicitConversionSequence::Better:
7269 // Cand1 has a better conversion sequence.
7270 return true;
7271
7272 case ImplicitConversionSequence::Worse:
7273 // Cand1 can't be better than Cand2.
7274 return false;
7275
7276 case ImplicitConversionSequence::Indistinguishable:
7277 // Do nothing
7278 break;
7279 }
7280 }
7281
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007282 return false;
7283}
7284
Mike Stump11289f42009-09-09 15:08:12 +00007285/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007286/// within an overload candidate set.
7287///
7288/// \param CandidateSet the set of candidate functions.
7289///
7290/// \param Loc the location of the function name (or operator symbol) for
7291/// which overload resolution occurs.
7292///
Mike Stump11289f42009-09-09 15:08:12 +00007293/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007294/// function, Best points to the candidate function found.
7295///
7296/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007297OverloadingResult
7298OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007299 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007300 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007301 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007302 Best = end();
7303 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7304 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007305 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007306 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007307 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007308 }
7309
7310 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007311 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007312 return OR_No_Viable_Function;
7313
7314 // Make sure that this function is better than every other viable
7315 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007316 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007317 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007318 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007319 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007320 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007321 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007322 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007323 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007324 }
Mike Stump11289f42009-09-09 15:08:12 +00007325
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007326 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007327 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007328 (Best->Function->isDeleted() ||
7329 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007330 return OR_Deleted;
7331
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007332 return OR_Success;
7333}
7334
John McCall53262c92010-01-12 02:15:36 +00007335namespace {
7336
7337enum OverloadCandidateKind {
7338 oc_function,
7339 oc_method,
7340 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007341 oc_function_template,
7342 oc_method_template,
7343 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007344 oc_implicit_default_constructor,
7345 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007346 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007347 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007348 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007349 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007350};
7351
John McCalle1ac8d12010-01-13 00:25:19 +00007352OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7353 FunctionDecl *Fn,
7354 std::string &Description) {
7355 bool isTemplate = false;
7356
7357 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7358 isTemplate = true;
7359 Description = S.getTemplateArgumentBindingsText(
7360 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7361 }
John McCallfd0b2f82010-01-06 09:43:14 +00007362
7363 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007364 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007365 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007366
Sebastian Redl08905022011-02-05 19:23:19 +00007367 if (Ctor->getInheritedConstructor())
7368 return oc_implicit_inherited_constructor;
7369
Alexis Hunt119c10e2011-05-25 23:16:36 +00007370 if (Ctor->isDefaultConstructor())
7371 return oc_implicit_default_constructor;
7372
7373 if (Ctor->isMoveConstructor())
7374 return oc_implicit_move_constructor;
7375
7376 assert(Ctor->isCopyConstructor() &&
7377 "unexpected sort of implicit constructor");
7378 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007379 }
7380
7381 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7382 // This actually gets spelled 'candidate function' for now, but
7383 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007384 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007385 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007386
Alexis Hunt119c10e2011-05-25 23:16:36 +00007387 if (Meth->isMoveAssignmentOperator())
7388 return oc_implicit_move_assignment;
7389
Douglas Gregorec3bec02010-09-27 22:37:28 +00007390 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007391 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007392 return oc_implicit_copy_assignment;
7393 }
7394
John McCalle1ac8d12010-01-13 00:25:19 +00007395 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007396}
7397
Sebastian Redl08905022011-02-05 19:23:19 +00007398void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7399 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7400 if (!Ctor) return;
7401
7402 Ctor = Ctor->getInheritedConstructor();
7403 if (!Ctor) return;
7404
7405 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7406}
7407
John McCall53262c92010-01-12 02:15:36 +00007408} // end anonymous namespace
7409
7410// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007411void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007412 std::string FnDesc;
7413 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007414 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7415 << (unsigned) K << FnDesc;
7416 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7417 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007418 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007419}
7420
Douglas Gregorb491ed32011-02-19 21:32:49 +00007421//Notes the location of all overload candidates designated through
7422// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007423void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007424 assert(OverloadedExpr->getType() == Context.OverloadTy);
7425
7426 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7427 OverloadExpr *OvlExpr = Ovl.Expression;
7428
7429 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7430 IEnd = OvlExpr->decls_end();
7431 I != IEnd; ++I) {
7432 if (FunctionTemplateDecl *FunTmpl =
7433 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007434 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007435 } else if (FunctionDecl *Fun
7436 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007437 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007438 }
7439 }
7440}
7441
John McCall0d1da222010-01-12 00:44:57 +00007442/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7443/// "lead" diagnostic; it will be given two arguments, the source and
7444/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007445void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7446 Sema &S,
7447 SourceLocation CaretLoc,
7448 const PartialDiagnostic &PDiag) const {
7449 S.Diag(CaretLoc, PDiag)
7450 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007451 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007452 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7453 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007454 }
John McCall12f97bc2010-01-08 04:41:39 +00007455}
7456
John McCall0d1da222010-01-12 00:44:57 +00007457namespace {
7458
John McCall6a61b522010-01-13 09:16:55 +00007459void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7460 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7461 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007462 assert(Cand->Function && "for now, candidate must be a function");
7463 FunctionDecl *Fn = Cand->Function;
7464
7465 // There's a conversion slot for the object argument if this is a
7466 // non-constructor method. Note that 'I' corresponds the
7467 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007468 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007469 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007470 if (I == 0)
7471 isObjectArgument = true;
7472 else
7473 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007474 }
7475
John McCalle1ac8d12010-01-13 00:25:19 +00007476 std::string FnDesc;
7477 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7478
John McCall6a61b522010-01-13 09:16:55 +00007479 Expr *FromExpr = Conv.Bad.FromExpr;
7480 QualType FromTy = Conv.Bad.getFromType();
7481 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007482
John McCallfb7ad0f2010-02-02 02:42:52 +00007483 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007484 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007485 Expr *E = FromExpr->IgnoreParens();
7486 if (isa<UnaryOperator>(E))
7487 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007488 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007489
7490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7491 << (unsigned) FnKind << FnDesc
7492 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7493 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007494 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007495 return;
7496 }
7497
John McCall6d174642010-01-23 08:10:49 +00007498 // Do some hand-waving analysis to see if the non-viability is due
7499 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007500 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7501 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7502 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7503 CToTy = RT->getPointeeType();
7504 else {
7505 // TODO: detect and diagnose the full richness of const mismatches.
7506 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7507 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7508 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7509 }
7510
7511 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7512 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7513 // It is dumb that we have to do this here.
7514 while (isa<ArrayType>(CFromTy))
7515 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7516 while (isa<ArrayType>(CToTy))
7517 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7518
7519 Qualifiers FromQs = CFromTy.getQualifiers();
7520 Qualifiers ToQs = CToTy.getQualifiers();
7521
7522 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7524 << (unsigned) FnKind << FnDesc
7525 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7526 << FromTy
7527 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7528 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007529 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007530 return;
7531 }
7532
John McCall31168b02011-06-15 23:02:42 +00007533 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007535 << (unsigned) FnKind << FnDesc
7536 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7537 << FromTy
7538 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7539 << (unsigned) isObjectArgument << I+1;
7540 MaybeEmitInheritedConstructorNote(S, Fn);
7541 return;
7542 }
7543
Douglas Gregoraec25842011-04-26 23:16:46 +00007544 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7546 << (unsigned) FnKind << FnDesc
7547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7548 << FromTy
7549 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7550 << (unsigned) isObjectArgument << I+1;
7551 MaybeEmitInheritedConstructorNote(S, Fn);
7552 return;
7553 }
7554
John McCall47000992010-01-14 03:28:57 +00007555 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7556 assert(CVR && "unexpected qualifiers mismatch");
7557
7558 if (isObjectArgument) {
7559 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7560 << (unsigned) FnKind << FnDesc
7561 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7562 << FromTy << (CVR - 1);
7563 } else {
7564 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7565 << (unsigned) FnKind << FnDesc
7566 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7567 << FromTy << (CVR - 1) << I+1;
7568 }
Sebastian Redl08905022011-02-05 19:23:19 +00007569 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007570 return;
7571 }
7572
Sebastian Redla72462c2011-09-24 17:48:32 +00007573 // Special diagnostic for failure to convert an initializer list, since
7574 // telling the user that it has type void is not useful.
7575 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7576 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7577 << (unsigned) FnKind << FnDesc
7578 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7579 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7580 MaybeEmitInheritedConstructorNote(S, Fn);
7581 return;
7582 }
7583
John McCall6d174642010-01-23 08:10:49 +00007584 // Diagnose references or pointers to incomplete types differently,
7585 // since it's far from impossible that the incompleteness triggered
7586 // the failure.
7587 QualType TempFromTy = FromTy.getNonReferenceType();
7588 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7589 TempFromTy = PTy->getPointeeType();
7590 if (TempFromTy->isIncompleteType()) {
7591 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7592 << (unsigned) FnKind << FnDesc
7593 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7594 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007595 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007596 return;
7597 }
7598
Douglas Gregor56f2e342010-06-30 23:01:39 +00007599 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007600 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007601 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7602 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7603 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7604 FromPtrTy->getPointeeType()) &&
7605 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7606 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007608 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007609 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007610 }
7611 } else if (const ObjCObjectPointerType *FromPtrTy
7612 = FromTy->getAs<ObjCObjectPointerType>()) {
7613 if (const ObjCObjectPointerType *ToPtrTy
7614 = ToTy->getAs<ObjCObjectPointerType>())
7615 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7616 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7617 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7618 FromPtrTy->getPointeeType()) &&
7619 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007620 BaseToDerivedConversion = 2;
7621 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7622 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7623 !FromTy->isIncompleteType() &&
7624 !ToRefTy->getPointeeType()->isIncompleteType() &&
7625 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7626 BaseToDerivedConversion = 3;
7627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007628
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007629 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007630 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007631 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007632 << (unsigned) FnKind << FnDesc
7633 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007634 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007635 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007636 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007637 return;
7638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007640 if (isa<ObjCObjectPointerType>(CFromTy) &&
7641 isa<PointerType>(CToTy)) {
7642 Qualifiers FromQs = CFromTy.getQualifiers();
7643 Qualifiers ToQs = CToTy.getQualifiers();
7644 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7646 << (unsigned) FnKind << FnDesc
7647 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7648 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7649 MaybeEmitInheritedConstructorNote(S, Fn);
7650 return;
7651 }
7652 }
7653
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007654 // Emit the generic diagnostic and, optionally, add the hints to it.
7655 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7656 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007657 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007658 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7659 << (unsigned) (Cand->Fix.Kind);
7660
7661 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00007662 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7663 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007664 FDiag << *HI;
7665 S.Diag(Fn->getLocation(), FDiag);
7666
Sebastian Redl08905022011-02-05 19:23:19 +00007667 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007668}
7669
7670void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7671 unsigned NumFormalArgs) {
7672 // TODO: treat calls to a missing default constructor as a special case
7673
7674 FunctionDecl *Fn = Cand->Function;
7675 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7676
7677 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007678
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007679 // With invalid overloaded operators, it's possible that we think we
7680 // have an arity mismatch when it fact it looks like we have the
7681 // right number of arguments, because only overloaded operators have
7682 // the weird behavior of overloading member and non-member functions.
7683 // Just don't report anything.
7684 if (Fn->isInvalidDecl() &&
7685 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7686 return;
7687
John McCall6a61b522010-01-13 09:16:55 +00007688 // at least / at most / exactly
7689 unsigned mode, modeCount;
7690 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007691 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7692 (Cand->FailureKind == ovl_fail_bad_deduction &&
7693 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007694 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007695 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007696 mode = 0; // "at least"
7697 else
7698 mode = 2; // "exactly"
7699 modeCount = MinParams;
7700 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007701 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7702 (Cand->FailureKind == ovl_fail_bad_deduction &&
7703 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007704 if (MinParams != FnTy->getNumArgs())
7705 mode = 1; // "at most"
7706 else
7707 mode = 2; // "exactly"
7708 modeCount = FnTy->getNumArgs();
7709 }
7710
7711 std::string Description;
7712 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7713
7714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007715 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007716 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007717 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007718}
7719
John McCall8b9ed552010-02-01 18:53:26 +00007720/// Diagnose a failed template-argument deduction.
7721void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7722 Expr **Args, unsigned NumArgs) {
7723 FunctionDecl *Fn = Cand->Function; // pattern
7724
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007725 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007726 NamedDecl *ParamD;
7727 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7728 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7729 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007730 switch (Cand->DeductionFailure.Result) {
7731 case Sema::TDK_Success:
7732 llvm_unreachable("TDK_success while diagnosing bad deduction");
7733
7734 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007735 assert(ParamD && "no parameter found for incomplete deduction result");
7736 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7737 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007738 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007739 return;
7740 }
7741
John McCall42d7d192010-08-05 09:05:08 +00007742 case Sema::TDK_Underqualified: {
7743 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7744 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7745
7746 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7747
7748 // Param will have been canonicalized, but it should just be a
7749 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007750 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007751 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007752 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007753 assert(S.Context.hasSameType(Param, NonCanonParam));
7754
7755 // Arg has also been canonicalized, but there's nothing we can do
7756 // about that. It also doesn't matter as much, because it won't
7757 // have any template parameters in it (because deduction isn't
7758 // done on dependent types).
7759 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7760
7761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7762 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007763 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007764 return;
7765 }
7766
7767 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007768 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007769 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007770 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007771 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007772 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007773 which = 1;
7774 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007775 which = 2;
7776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007777
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007778 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007780 << *Cand->DeductionFailure.getFirstArg()
7781 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007782 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007783 return;
7784 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007785
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007786 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007787 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007788 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007790 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7791 << ParamD->getDeclName();
7792 else {
7793 int index = 0;
7794 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7795 index = TTP->getIndex();
7796 else if (NonTypeTemplateParmDecl *NTTP
7797 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7798 index = NTTP->getIndex();
7799 else
7800 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007801 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007802 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7803 << (index + 1);
7804 }
Sebastian Redl08905022011-02-05 19:23:19 +00007805 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007806 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807
Douglas Gregor02eb4832010-05-08 18:13:28 +00007808 case Sema::TDK_TooManyArguments:
7809 case Sema::TDK_TooFewArguments:
7810 DiagnoseArityMismatch(S, Cand, NumArgs);
7811 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007812
7813 case Sema::TDK_InstantiationDepth:
7814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007815 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007816 return;
7817
7818 case Sema::TDK_SubstitutionFailure: {
7819 std::string ArgString;
7820 if (TemplateArgumentList *Args
7821 = Cand->DeductionFailure.getTemplateArgumentList())
7822 ArgString = S.getTemplateArgumentBindingsText(
7823 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7824 *Args);
7825 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7826 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007827 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007828 return;
7829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007830
John McCall8b9ed552010-02-01 18:53:26 +00007831 // TODO: diagnose these individually, then kill off
7832 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007833 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007834 case Sema::TDK_FailedOverloadResolution:
7835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007836 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007837 return;
7838 }
7839}
7840
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007841/// CUDA: diagnose an invalid call across targets.
7842void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7843 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7844 FunctionDecl *Callee = Cand->Function;
7845
7846 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7847 CalleeTarget = S.IdentifyCUDATarget(Callee);
7848
7849 std::string FnDesc;
7850 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7851
7852 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7853 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7854}
7855
John McCall8b9ed552010-02-01 18:53:26 +00007856/// Generates a 'note' diagnostic for an overload candidate. We've
7857/// already generated a primary error at the call site.
7858///
7859/// It really does need to be a single diagnostic with its caret
7860/// pointed at the candidate declaration. Yes, this creates some
7861/// major challenges of technical writing. Yes, this makes pointing
7862/// out problems with specific arguments quite awkward. It's still
7863/// better than generating twenty screens of text for every failed
7864/// overload.
7865///
7866/// It would be great to be able to express per-candidate problems
7867/// more richly for those diagnostic clients that cared, but we'd
7868/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007869void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7870 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007871 FunctionDecl *Fn = Cand->Function;
7872
John McCall12f97bc2010-01-08 04:41:39 +00007873 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007874 if (Cand->Viable && (Fn->isDeleted() ||
7875 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007876 std::string FnDesc;
7877 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007878
7879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007880 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007881 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007882 return;
John McCall12f97bc2010-01-08 04:41:39 +00007883 }
7884
John McCalle1ac8d12010-01-13 00:25:19 +00007885 // We don't really have anything else to say about viable candidates.
7886 if (Cand->Viable) {
7887 S.NoteOverloadCandidate(Fn);
7888 return;
7889 }
John McCall0d1da222010-01-12 00:44:57 +00007890
John McCall6a61b522010-01-13 09:16:55 +00007891 switch (Cand->FailureKind) {
7892 case ovl_fail_too_many_arguments:
7893 case ovl_fail_too_few_arguments:
7894 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007895
John McCall6a61b522010-01-13 09:16:55 +00007896 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007897 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7898
John McCallfe796dd2010-01-23 05:17:32 +00007899 case ovl_fail_trivial_conversion:
7900 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007901 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007902 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007903
John McCall65eb8792010-02-25 01:37:24 +00007904 case ovl_fail_bad_conversion: {
7905 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007906 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007907 if (Cand->Conversions[I].isBad())
7908 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007909
John McCall6a61b522010-01-13 09:16:55 +00007910 // FIXME: this currently happens when we're called from SemaInit
7911 // when user-conversion overload fails. Figure out how to handle
7912 // those conditions and diagnose them well.
7913 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007914 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007915
7916 case ovl_fail_bad_target:
7917 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007918 }
John McCalld3224162010-01-08 00:58:21 +00007919}
7920
7921void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7922 // Desugar the type of the surrogate down to a function type,
7923 // retaining as many typedefs as possible while still showing
7924 // the function type (and, therefore, its parameter types).
7925 QualType FnType = Cand->Surrogate->getConversionType();
7926 bool isLValueReference = false;
7927 bool isRValueReference = false;
7928 bool isPointer = false;
7929 if (const LValueReferenceType *FnTypeRef =
7930 FnType->getAs<LValueReferenceType>()) {
7931 FnType = FnTypeRef->getPointeeType();
7932 isLValueReference = true;
7933 } else if (const RValueReferenceType *FnTypeRef =
7934 FnType->getAs<RValueReferenceType>()) {
7935 FnType = FnTypeRef->getPointeeType();
7936 isRValueReference = true;
7937 }
7938 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7939 FnType = FnTypePtr->getPointeeType();
7940 isPointer = true;
7941 }
7942 // Desugar down to a function type.
7943 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7944 // Reconstruct the pointer/reference as appropriate.
7945 if (isPointer) FnType = S.Context.getPointerType(FnType);
7946 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7947 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7948
7949 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7950 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007951 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007952}
7953
7954void NoteBuiltinOperatorCandidate(Sema &S,
7955 const char *Opc,
7956 SourceLocation OpLoc,
7957 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007958 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00007959 std::string TypeStr("operator");
7960 TypeStr += Opc;
7961 TypeStr += "(";
7962 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00007963 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00007964 TypeStr += ")";
7965 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7966 } else {
7967 TypeStr += ", ";
7968 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7969 TypeStr += ")";
7970 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7971 }
7972}
7973
7974void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7975 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007976 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00007977 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7978 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007979 if (ICS.isBad()) break; // all meaningless after first invalid
7980 if (!ICS.isAmbiguous()) continue;
7981
John McCall5c32be02010-08-24 20:38:10 +00007982 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007983 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007984 }
7985}
7986
John McCall3712d9e2010-01-15 23:32:50 +00007987SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7988 if (Cand->Function)
7989 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007990 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007991 return Cand->Surrogate->getLocation();
7992 return SourceLocation();
7993}
7994
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007995static unsigned
7996RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007997 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007998 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007999 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008000
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008001 case Sema::TDK_Incomplete:
8002 return 1;
8003
8004 case Sema::TDK_Underqualified:
8005 case Sema::TDK_Inconsistent:
8006 return 2;
8007
8008 case Sema::TDK_SubstitutionFailure:
8009 case Sema::TDK_NonDeducedMismatch:
8010 return 3;
8011
8012 case Sema::TDK_InstantiationDepth:
8013 case Sema::TDK_FailedOverloadResolution:
8014 return 4;
8015
8016 case Sema::TDK_InvalidExplicitArguments:
8017 return 5;
8018
8019 case Sema::TDK_TooManyArguments:
8020 case Sema::TDK_TooFewArguments:
8021 return 6;
8022 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008023 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008024}
8025
John McCallad2587a2010-01-12 00:48:53 +00008026struct CompareOverloadCandidatesForDisplay {
8027 Sema &S;
8028 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008029
8030 bool operator()(const OverloadCandidate *L,
8031 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008032 // Fast-path this check.
8033 if (L == R) return false;
8034
John McCall12f97bc2010-01-08 04:41:39 +00008035 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008036 if (L->Viable) {
8037 if (!R->Viable) return true;
8038
8039 // TODO: introduce a tri-valued comparison for overload
8040 // candidates. Would be more worthwhile if we had a sort
8041 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008042 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8043 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008044 } else if (R->Viable)
8045 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008046
John McCall3712d9e2010-01-15 23:32:50 +00008047 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008048
John McCall3712d9e2010-01-15 23:32:50 +00008049 // Criteria by which we can sort non-viable candidates:
8050 if (!L->Viable) {
8051 // 1. Arity mismatches come after other candidates.
8052 if (L->FailureKind == ovl_fail_too_many_arguments ||
8053 L->FailureKind == ovl_fail_too_few_arguments)
8054 return false;
8055 if (R->FailureKind == ovl_fail_too_many_arguments ||
8056 R->FailureKind == ovl_fail_too_few_arguments)
8057 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008058
John McCallfe796dd2010-01-23 05:17:32 +00008059 // 2. Bad conversions come first and are ordered by the number
8060 // of bad conversions and quality of good conversions.
8061 if (L->FailureKind == ovl_fail_bad_conversion) {
8062 if (R->FailureKind != ovl_fail_bad_conversion)
8063 return true;
8064
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008065 // The conversion that can be fixed with a smaller number of changes,
8066 // comes first.
8067 unsigned numLFixes = L->Fix.NumConversionsFixed;
8068 unsigned numRFixes = R->Fix.NumConversionsFixed;
8069 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8070 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008071 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008072 if (numLFixes < numRFixes)
8073 return true;
8074 else
8075 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008076 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008077
John McCallfe796dd2010-01-23 05:17:32 +00008078 // If there's any ordering between the defined conversions...
8079 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008080 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008081
8082 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008083 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008084 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008085 switch (CompareImplicitConversionSequences(S,
8086 L->Conversions[I],
8087 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008088 case ImplicitConversionSequence::Better:
8089 leftBetter++;
8090 break;
8091
8092 case ImplicitConversionSequence::Worse:
8093 leftBetter--;
8094 break;
8095
8096 case ImplicitConversionSequence::Indistinguishable:
8097 break;
8098 }
8099 }
8100 if (leftBetter > 0) return true;
8101 if (leftBetter < 0) return false;
8102
8103 } else if (R->FailureKind == ovl_fail_bad_conversion)
8104 return false;
8105
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008106 if (L->FailureKind == ovl_fail_bad_deduction) {
8107 if (R->FailureKind != ovl_fail_bad_deduction)
8108 return true;
8109
8110 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8111 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008112 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008113 } else if (R->FailureKind == ovl_fail_bad_deduction)
8114 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008115
John McCall3712d9e2010-01-15 23:32:50 +00008116 // TODO: others?
8117 }
8118
8119 // Sort everything else by location.
8120 SourceLocation LLoc = GetLocationForCandidate(L);
8121 SourceLocation RLoc = GetLocationForCandidate(R);
8122
8123 // Put candidates without locations (e.g. builtins) at the end.
8124 if (LLoc.isInvalid()) return false;
8125 if (RLoc.isInvalid()) return true;
8126
8127 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008128 }
8129};
8130
John McCallfe796dd2010-01-23 05:17:32 +00008131/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008132/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008133void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8134 Expr **Args, unsigned NumArgs) {
8135 assert(!Cand->Viable);
8136
8137 // Don't do anything on failures other than bad conversion.
8138 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8139
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008140 // We only want the FixIts if all the arguments can be corrected.
8141 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008142 // Use a implicit copy initialization to check conversion fixes.
8143 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008144
John McCallfe796dd2010-01-23 05:17:32 +00008145 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008146 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008147 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008148 while (true) {
8149 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8150 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008151 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008152 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008153 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008154 }
John McCallfe796dd2010-01-23 05:17:32 +00008155 }
8156
8157 if (ConvIdx == ConvCount)
8158 return;
8159
John McCall65eb8792010-02-25 01:37:24 +00008160 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8161 "remaining conversion is initialized?");
8162
Douglas Gregoradc7a702010-04-16 17:45:54 +00008163 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008164 // operation somehow.
8165 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008166
8167 const FunctionProtoType* Proto;
8168 unsigned ArgIdx = ConvIdx;
8169
8170 if (Cand->IsSurrogate) {
8171 QualType ConvType
8172 = Cand->Surrogate->getConversionType().getNonReferenceType();
8173 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8174 ConvType = ConvPtrType->getPointeeType();
8175 Proto = ConvType->getAs<FunctionProtoType>();
8176 ArgIdx--;
8177 } else if (Cand->Function) {
8178 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8179 if (isa<CXXMethodDecl>(Cand->Function) &&
8180 !isa<CXXConstructorDecl>(Cand->Function))
8181 ArgIdx--;
8182 } else {
8183 // Builtin binary operator with a bad first conversion.
8184 assert(ConvCount <= 3);
8185 for (; ConvIdx != ConvCount; ++ConvIdx)
8186 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008187 = TryCopyInitialization(S, Args[ConvIdx],
8188 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008189 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008190 /*InOverloadResolution*/ true,
8191 /*AllowObjCWritebackConversion=*/
8192 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008193 return;
8194 }
8195
8196 // Fill in the rest of the conversions.
8197 unsigned NumArgsInProto = Proto->getNumArgs();
8198 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008199 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008200 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008201 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008203 /*InOverloadResolution=*/true,
8204 /*AllowObjCWritebackConversion=*/
8205 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008206 // Store the FixIt in the candidate if it exists.
8207 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008208 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008209 }
John McCallfe796dd2010-01-23 05:17:32 +00008210 else
8211 Cand->Conversions[ConvIdx].setEllipsis();
8212 }
8213}
8214
John McCalld3224162010-01-08 00:58:21 +00008215} // end anonymous namespace
8216
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008217/// PrintOverloadCandidates - When overload resolution fails, prints
8218/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008219/// set.
John McCall5c32be02010-08-24 20:38:10 +00008220void OverloadCandidateSet::NoteCandidates(Sema &S,
8221 OverloadCandidateDisplayKind OCD,
8222 Expr **Args, unsigned NumArgs,
8223 const char *Opc,
8224 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008225 // Sort the candidates by viability and position. Sorting directly would
8226 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008227 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008228 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8229 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008230 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008231 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008232 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008233 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008234 if (Cand->Function || Cand->IsSurrogate)
8235 Cands.push_back(Cand);
8236 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8237 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008238 }
8239 }
8240
John McCallad2587a2010-01-12 00:48:53 +00008241 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008242 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243
John McCall0d1da222010-01-12 00:44:57 +00008244 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008246 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008247 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8248 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008249 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008250 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8251 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008252
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008253 // Set an arbitrary limit on the number of candidate functions we'll spam
8254 // the user with. FIXME: This limit should depend on details of the
8255 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008256 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008257 break;
8258 }
8259 ++CandsShown;
8260
John McCalld3224162010-01-08 00:58:21 +00008261 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008262 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008263 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008264 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008265 else {
8266 assert(Cand->Viable &&
8267 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008268 // Generally we only see ambiguities including viable builtin
8269 // operators if overload resolution got screwed up by an
8270 // ambiguous user-defined conversion.
8271 //
8272 // FIXME: It's quite possible for different conversions to see
8273 // different ambiguities, though.
8274 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008275 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008276 ReportedAmbiguousConversions = true;
8277 }
John McCalld3224162010-01-08 00:58:21 +00008278
John McCall0d1da222010-01-12 00:44:57 +00008279 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008280 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008281 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008282 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008283
8284 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008285 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008286}
8287
Douglas Gregorb491ed32011-02-19 21:32:49 +00008288// [PossiblyAFunctionType] --> [Return]
8289// NonFunctionType --> NonFunctionType
8290// R (A) --> R(A)
8291// R (*)(A) --> R (A)
8292// R (&)(A) --> R (A)
8293// R (S::*)(A) --> R (A)
8294QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8295 QualType Ret = PossiblyAFunctionType;
8296 if (const PointerType *ToTypePtr =
8297 PossiblyAFunctionType->getAs<PointerType>())
8298 Ret = ToTypePtr->getPointeeType();
8299 else if (const ReferenceType *ToTypeRef =
8300 PossiblyAFunctionType->getAs<ReferenceType>())
8301 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008302 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008303 PossiblyAFunctionType->getAs<MemberPointerType>())
8304 Ret = MemTypePtr->getPointeeType();
8305 Ret =
8306 Context.getCanonicalType(Ret).getUnqualifiedType();
8307 return Ret;
8308}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008309
Douglas Gregorb491ed32011-02-19 21:32:49 +00008310// A helper class to help with address of function resolution
8311// - allows us to avoid passing around all those ugly parameters
8312class AddressOfFunctionResolver
8313{
8314 Sema& S;
8315 Expr* SourceExpr;
8316 const QualType& TargetType;
8317 QualType TargetFunctionType; // Extracted function type from target type
8318
8319 bool Complain;
8320 //DeclAccessPair& ResultFunctionAccessPair;
8321 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322
Douglas Gregorb491ed32011-02-19 21:32:49 +00008323 bool TargetTypeIsNonStaticMemberFunction;
8324 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008325
Douglas Gregorb491ed32011-02-19 21:32:49 +00008326 OverloadExpr::FindResult OvlExprInfo;
8327 OverloadExpr *OvlExpr;
8328 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008329 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008330
Douglas Gregorb491ed32011-02-19 21:32:49 +00008331public:
8332 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8333 const QualType& TargetType, bool Complain)
8334 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8335 Complain(Complain), Context(S.getASTContext()),
8336 TargetTypeIsNonStaticMemberFunction(
8337 !!TargetType->getAs<MemberPointerType>()),
8338 FoundNonTemplateFunction(false),
8339 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8340 OvlExpr(OvlExprInfo.Expression)
8341 {
8342 ExtractUnqualifiedFunctionTypeFromTargetType();
8343
8344 if (!TargetFunctionType->isFunctionType()) {
8345 if (OvlExpr->hasExplicitTemplateArgs()) {
8346 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008347 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008348 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008349
8350 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8351 if (!Method->isStatic()) {
8352 // If the target type is a non-function type and the function
8353 // found is a non-static member function, pretend as if that was
8354 // the target, it's the only possible type to end up with.
8355 TargetTypeIsNonStaticMemberFunction = true;
8356
8357 // And skip adding the function if its not in the proper form.
8358 // We'll diagnose this due to an empty set of functions.
8359 if (!OvlExprInfo.HasFormOfMemberPointer)
8360 return;
8361 }
8362 }
8363
Douglas Gregorb491ed32011-02-19 21:32:49 +00008364 Matches.push_back(std::make_pair(dap,Fn));
8365 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008366 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008367 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008368 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008369
8370 if (OvlExpr->hasExplicitTemplateArgs())
8371 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008372
Douglas Gregorb491ed32011-02-19 21:32:49 +00008373 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8374 // C++ [over.over]p4:
8375 // If more than one function is selected, [...]
8376 if (Matches.size() > 1) {
8377 if (FoundNonTemplateFunction)
8378 EliminateAllTemplateMatches();
8379 else
8380 EliminateAllExceptMostSpecializedTemplate();
8381 }
8382 }
8383 }
8384
8385private:
8386 bool isTargetTypeAFunction() const {
8387 return TargetFunctionType->isFunctionType();
8388 }
8389
8390 // [ToType] [Return]
8391
8392 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8393 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8394 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8395 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8396 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8397 }
8398
8399 // return true if any matching specializations were found
8400 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8401 const DeclAccessPair& CurAccessFunPair) {
8402 if (CXXMethodDecl *Method
8403 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8404 // Skip non-static function templates when converting to pointer, and
8405 // static when converting to member pointer.
8406 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8407 return false;
8408 }
8409 else if (TargetTypeIsNonStaticMemberFunction)
8410 return false;
8411
8412 // C++ [over.over]p2:
8413 // If the name is a function template, template argument deduction is
8414 // done (14.8.2.2), and if the argument deduction succeeds, the
8415 // resulting template argument list is used to generate a single
8416 // function template specialization, which is added to the set of
8417 // overloaded functions considered.
8418 FunctionDecl *Specialization = 0;
8419 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8420 if (Sema::TemplateDeductionResult Result
8421 = S.DeduceTemplateArguments(FunctionTemplate,
8422 &OvlExplicitTemplateArgs,
8423 TargetFunctionType, Specialization,
8424 Info)) {
8425 // FIXME: make a note of the failed deduction for diagnostics.
8426 (void)Result;
8427 return false;
8428 }
8429
8430 // Template argument deduction ensures that we have an exact match.
8431 // This function template specicalization works.
8432 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8433 assert(TargetFunctionType
8434 == Context.getCanonicalType(Specialization->getType()));
8435 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8436 return true;
8437 }
8438
8439 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8440 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008441 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008442 // Skip non-static functions when converting to pointer, and static
8443 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008444 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8445 return false;
8446 }
8447 else if (TargetTypeIsNonStaticMemberFunction)
8448 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008449
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008450 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008451 if (S.getLangOptions().CUDA)
8452 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8453 if (S.CheckCUDATarget(Caller, FunDecl))
8454 return false;
8455
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008456 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008457 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8458 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008459 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8460 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008461 Matches.push_back(std::make_pair(CurAccessFunPair,
8462 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008463 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008464 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008465 }
Mike Stump11289f42009-09-09 15:08:12 +00008466 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008467
8468 return false;
8469 }
8470
8471 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8472 bool Ret = false;
8473
8474 // If the overload expression doesn't have the form of a pointer to
8475 // member, don't try to convert it to a pointer-to-member type.
8476 if (IsInvalidFormOfPointerToMemberFunction())
8477 return false;
8478
8479 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8480 E = OvlExpr->decls_end();
8481 I != E; ++I) {
8482 // Look through any using declarations to find the underlying function.
8483 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8484
8485 // C++ [over.over]p3:
8486 // Non-member functions and static member functions match
8487 // targets of type "pointer-to-function" or "reference-to-function."
8488 // Nonstatic member functions match targets of
8489 // type "pointer-to-member-function."
8490 // Note that according to DR 247, the containing class does not matter.
8491 if (FunctionTemplateDecl *FunctionTemplate
8492 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8493 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8494 Ret = true;
8495 }
8496 // If we have explicit template arguments supplied, skip non-templates.
8497 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8498 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8499 Ret = true;
8500 }
8501 assert(Ret || Matches.empty());
8502 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008503 }
8504
Douglas Gregorb491ed32011-02-19 21:32:49 +00008505 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008506 // [...] and any given function template specialization F1 is
8507 // eliminated if the set contains a second function template
8508 // specialization whose function template is more specialized
8509 // than the function template of F1 according to the partial
8510 // ordering rules of 14.5.5.2.
8511
8512 // The algorithm specified above is quadratic. We instead use a
8513 // two-pass algorithm (similar to the one used to identify the
8514 // best viable function in an overload set) that identifies the
8515 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008516
8517 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8518 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8519 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008520
John McCall58cc69d2010-01-27 01:50:18 +00008521 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008522 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8523 TPOC_Other, 0, SourceExpr->getLocStart(),
8524 S.PDiag(),
8525 S.PDiag(diag::err_addr_ovl_ambiguous)
8526 << Matches[0].second->getDeclName(),
8527 S.PDiag(diag::note_ovl_candidate)
8528 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008529 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008530
Douglas Gregorb491ed32011-02-19 21:32:49 +00008531 if (Result != MatchesCopy.end()) {
8532 // Make it the first and only element
8533 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8534 Matches[0].second = cast<FunctionDecl>(*Result);
8535 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008536 }
8537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008538
Douglas Gregorb491ed32011-02-19 21:32:49 +00008539 void EliminateAllTemplateMatches() {
8540 // [...] any function template specializations in the set are
8541 // eliminated if the set also contains a non-template function, [...]
8542 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8543 if (Matches[I].second->getPrimaryTemplate() == 0)
8544 ++I;
8545 else {
8546 Matches[I] = Matches[--N];
8547 Matches.set_size(N);
8548 }
8549 }
8550 }
8551
8552public:
8553 void ComplainNoMatchesFound() const {
8554 assert(Matches.empty());
8555 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8556 << OvlExpr->getName() << TargetFunctionType
8557 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008558 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008559 }
8560
8561 bool IsInvalidFormOfPointerToMemberFunction() const {
8562 return TargetTypeIsNonStaticMemberFunction &&
8563 !OvlExprInfo.HasFormOfMemberPointer;
8564 }
8565
8566 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8567 // TODO: Should we condition this on whether any functions might
8568 // have matched, or is it more appropriate to do that in callers?
8569 // TODO: a fixit wouldn't hurt.
8570 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8571 << TargetType << OvlExpr->getSourceRange();
8572 }
8573
8574 void ComplainOfInvalidConversion() const {
8575 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8576 << OvlExpr->getName() << TargetType;
8577 }
8578
8579 void ComplainMultipleMatchesFound() const {
8580 assert(Matches.size() > 1);
8581 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8582 << OvlExpr->getName()
8583 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008584 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008585 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008586
8587 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8588
Douglas Gregorb491ed32011-02-19 21:32:49 +00008589 int getNumMatches() const { return Matches.size(); }
8590
8591 FunctionDecl* getMatchingFunctionDecl() const {
8592 if (Matches.size() != 1) return 0;
8593 return Matches[0].second;
8594 }
8595
8596 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8597 if (Matches.size() != 1) return 0;
8598 return &Matches[0].first;
8599 }
8600};
8601
8602/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8603/// an overloaded function (C++ [over.over]), where @p From is an
8604/// expression with overloaded function type and @p ToType is the type
8605/// we're trying to resolve to. For example:
8606///
8607/// @code
8608/// int f(double);
8609/// int f(int);
8610///
8611/// int (*pfd)(double) = f; // selects f(double)
8612/// @endcode
8613///
8614/// This routine returns the resulting FunctionDecl if it could be
8615/// resolved, and NULL otherwise. When @p Complain is true, this
8616/// routine will emit diagnostics if there is an error.
8617FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008618Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8619 QualType TargetType,
8620 bool Complain,
8621 DeclAccessPair &FoundResult,
8622 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008623 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008624
8625 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8626 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008627 int NumMatches = Resolver.getNumMatches();
8628 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008629 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008630 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8631 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8632 else
8633 Resolver.ComplainNoMatchesFound();
8634 }
8635 else if (NumMatches > 1 && Complain)
8636 Resolver.ComplainMultipleMatchesFound();
8637 else if (NumMatches == 1) {
8638 Fn = Resolver.getMatchingFunctionDecl();
8639 assert(Fn);
8640 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8641 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008642 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008643 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008644 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008645
8646 if (pHadMultipleCandidates)
8647 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008648 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008649}
8650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008651/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008652/// resolve that overloaded function expression down to a single function.
8653///
8654/// This routine can only resolve template-ids that refer to a single function
8655/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008656/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008657/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008658FunctionDecl *
8659Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8660 bool Complain,
8661 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008662 // C++ [over.over]p1:
8663 // [...] [Note: any redundant set of parentheses surrounding the
8664 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008665 // C++ [over.over]p1:
8666 // [...] The overloaded function name can be preceded by the &
8667 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008668
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008669 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008670 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008671 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008672
8673 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008674 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008675
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008676 // Look through all of the overloaded functions, searching for one
8677 // whose type matches exactly.
8678 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008679 for (UnresolvedSetIterator I = ovl->decls_begin(),
8680 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008681 // C++0x [temp.arg.explicit]p3:
8682 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008683 // where deduction is not done, if a template argument list is
8684 // specified and it, along with any default template arguments,
8685 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008686 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008687 FunctionTemplateDecl *FunctionTemplate
8688 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008689
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008690 // C++ [over.over]p2:
8691 // If the name is a function template, template argument deduction is
8692 // done (14.8.2.2), and if the argument deduction succeeds, the
8693 // resulting template argument list is used to generate a single
8694 // function template specialization, which is added to the set of
8695 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008696 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008697 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008698 if (TemplateDeductionResult Result
8699 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8700 Specialization, Info)) {
8701 // FIXME: make a note of the failed deduction for diagnostics.
8702 (void)Result;
8703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008704 }
8705
John McCall0009fcc2011-04-26 20:42:42 +00008706 assert(Specialization && "no specialization and no error?");
8707
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008708 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008709 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008710 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008711 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8712 << ovl->getName();
8713 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008714 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008715 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008716 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008717
John McCall0009fcc2011-04-26 20:42:42 +00008718 Matched = Specialization;
8719 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008721
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008722 return Matched;
8723}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008724
Douglas Gregor1beec452011-03-12 01:48:56 +00008725
8726
8727
John McCall50a2c2c2011-10-11 23:14:30 +00008728// Resolve and fix an overloaded expression that can be resolved
8729// because it identifies a single function template specialization.
8730//
Douglas Gregor1beec452011-03-12 01:48:56 +00008731// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008732//
8733// Return true if it was logically possible to so resolve the
8734// expression, regardless of whether or not it succeeded. Always
8735// returns true if 'complain' is set.
8736bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8737 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8738 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008739 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008740 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008741 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008742
John McCall50a2c2c2011-10-11 23:14:30 +00008743 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008744
John McCall0009fcc2011-04-26 20:42:42 +00008745 DeclAccessPair found;
8746 ExprResult SingleFunctionExpression;
8747 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8748 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008749 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8750 SrcExpr = ExprError();
8751 return true;
8752 }
John McCall0009fcc2011-04-26 20:42:42 +00008753
8754 // It is only correct to resolve to an instance method if we're
8755 // resolving a form that's permitted to be a pointer to member.
8756 // Otherwise we'll end up making a bound member expression, which
8757 // is illegal in all the contexts we resolve like this.
8758 if (!ovl.HasFormOfMemberPointer &&
8759 isa<CXXMethodDecl>(fn) &&
8760 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008761 if (!complain) return false;
8762
8763 Diag(ovl.Expression->getExprLoc(),
8764 diag::err_bound_member_function)
8765 << 0 << ovl.Expression->getSourceRange();
8766
8767 // TODO: I believe we only end up here if there's a mix of
8768 // static and non-static candidates (otherwise the expression
8769 // would have 'bound member' type, not 'overload' type).
8770 // Ideally we would note which candidate was chosen and why
8771 // the static candidates were rejected.
8772 SrcExpr = ExprError();
8773 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008774 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008775
John McCall0009fcc2011-04-26 20:42:42 +00008776 // Fix the expresion to refer to 'fn'.
8777 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008778 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008779
8780 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008781 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008782 SingleFunctionExpression =
8783 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008784 if (SingleFunctionExpression.isInvalid()) {
8785 SrcExpr = ExprError();
8786 return true;
8787 }
8788 }
John McCall0009fcc2011-04-26 20:42:42 +00008789 }
8790
8791 if (!SingleFunctionExpression.isUsable()) {
8792 if (complain) {
8793 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8794 << ovl.Expression->getName()
8795 << DestTypeForComplaining
8796 << OpRangeForComplaining
8797 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008798 NoteAllOverloadCandidates(SrcExpr.get());
8799
8800 SrcExpr = ExprError();
8801 return true;
8802 }
8803
8804 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008805 }
8806
John McCall50a2c2c2011-10-11 23:14:30 +00008807 SrcExpr = SingleFunctionExpression;
8808 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008809}
8810
Douglas Gregorcabea402009-09-22 15:41:20 +00008811/// \brief Add a single candidate to the overload set.
8812static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008813 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008814 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008815 Expr **Args, unsigned NumArgs,
8816 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008817 bool PartialOverloading,
8818 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008819 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008820 if (isa<UsingShadowDecl>(Callee))
8821 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8822
Douglas Gregorcabea402009-09-22 15:41:20 +00008823 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008824 if (ExplicitTemplateArgs) {
8825 assert(!KnownValid && "Explicit template arguments?");
8826 return;
8827 }
John McCalla0296f72010-03-19 07:35:19 +00008828 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008829 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008830 return;
John McCalld14a8642009-11-21 08:51:07 +00008831 }
8832
8833 if (FunctionTemplateDecl *FuncTemplate
8834 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008835 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8836 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008837 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008838 return;
8839 }
8840
Richard Smith95ce4f62011-06-26 22:19:54 +00008841 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008842}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008843
Douglas Gregorcabea402009-09-22 15:41:20 +00008844/// \brief Add the overload candidates named by callee and/or found by argument
8845/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008846void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008847 Expr **Args, unsigned NumArgs,
8848 OverloadCandidateSet &CandidateSet,
8849 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008850
8851#ifndef NDEBUG
8852 // Verify that ArgumentDependentLookup is consistent with the rules
8853 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008854 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008855 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8856 // and let Y be the lookup set produced by argument dependent
8857 // lookup (defined as follows). If X contains
8858 //
8859 // -- a declaration of a class member, or
8860 //
8861 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008862 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008863 //
8864 // -- a declaration that is neither a function or a function
8865 // template
8866 //
8867 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008868
John McCall57500772009-12-16 12:17:52 +00008869 if (ULE->requiresADL()) {
8870 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8871 E = ULE->decls_end(); I != E; ++I) {
8872 assert(!(*I)->getDeclContext()->isRecord());
8873 assert(isa<UsingShadowDecl>(*I) ||
8874 !(*I)->getDeclContext()->isFunctionOrMethod());
8875 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008876 }
8877 }
8878#endif
8879
John McCall57500772009-12-16 12:17:52 +00008880 // It would be nice to avoid this copy.
8881 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008882 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008883 if (ULE->hasExplicitTemplateArgs()) {
8884 ULE->copyTemplateArgumentsInto(TABuffer);
8885 ExplicitTemplateArgs = &TABuffer;
8886 }
8887
8888 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8889 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008890 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008891 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008892 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008893
John McCall57500772009-12-16 12:17:52 +00008894 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008895 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8896 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008897 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008898 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008899 PartialOverloading,
8900 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008901}
John McCalld681c392009-12-16 08:11:27 +00008902
Richard Smith998a5912011-06-05 22:42:48 +00008903/// Attempt to recover from an ill-formed use of a non-dependent name in a
8904/// template, where the non-dependent name was declared after the template
8905/// was defined. This is common in code written for a compilers which do not
8906/// correctly implement two-stage name lookup.
8907///
8908/// Returns true if a viable candidate was found and a diagnostic was issued.
8909static bool
8910DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8911 const CXXScopeSpec &SS, LookupResult &R,
8912 TemplateArgumentListInfo *ExplicitTemplateArgs,
8913 Expr **Args, unsigned NumArgs) {
8914 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8915 return false;
8916
8917 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8918 SemaRef.LookupQualifiedName(R, DC);
8919
8920 if (!R.empty()) {
8921 R.suppressDiagnostics();
8922
8923 if (isa<CXXRecordDecl>(DC)) {
8924 // Don't diagnose names we find in classes; we get much better
8925 // diagnostics for these from DiagnoseEmptyLookup.
8926 R.clear();
8927 return false;
8928 }
8929
8930 OverloadCandidateSet Candidates(FnLoc);
8931 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8932 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8933 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008934 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008935
8936 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008937 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008938 // No viable functions. Don't bother the user with notes for functions
8939 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008940 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008941 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008942 }
Richard Smith998a5912011-06-05 22:42:48 +00008943
8944 // Find the namespaces where ADL would have looked, and suggest
8945 // declaring the function there instead.
8946 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8947 Sema::AssociatedClassSet AssociatedClasses;
8948 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8949 AssociatedNamespaces,
8950 AssociatedClasses);
8951 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008952 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008953 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008954 for (Sema::AssociatedNamespaceSet::iterator
8955 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008956 end = AssociatedNamespaces.end(); it != end; ++it) {
8957 if (!Std->Encloses(*it))
8958 SuggestedNamespaces.insert(*it);
8959 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008960 } else {
8961 // Lacking the 'std::' namespace, use all of the associated namespaces.
8962 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008963 }
8964
8965 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8966 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008967 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008968 SemaRef.Diag(Best->Function->getLocation(),
8969 diag::note_not_found_by_two_phase_lookup)
8970 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008971 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008972 SemaRef.Diag(Best->Function->getLocation(),
8973 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008974 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008975 } else {
8976 // FIXME: It would be useful to list the associated namespaces here,
8977 // but the diagnostics infrastructure doesn't provide a way to produce
8978 // a localized representation of a list of items.
8979 SemaRef.Diag(Best->Function->getLocation(),
8980 diag::note_not_found_by_two_phase_lookup)
8981 << R.getLookupName() << 2;
8982 }
8983
8984 // Try to recover by calling this function.
8985 return true;
8986 }
8987
8988 R.clear();
8989 }
8990
8991 return false;
8992}
8993
8994/// Attempt to recover from ill-formed use of a non-dependent operator in a
8995/// template, where the non-dependent operator was declared after the template
8996/// was defined.
8997///
8998/// Returns true if a viable candidate was found and a diagnostic was issued.
8999static bool
9000DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9001 SourceLocation OpLoc,
9002 Expr **Args, unsigned NumArgs) {
9003 DeclarationName OpName =
9004 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9005 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9006 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9007 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9008}
9009
John McCalld681c392009-12-16 08:11:27 +00009010/// Attempts to recover from a call where no functions were found.
9011///
9012/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009013static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009014BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009015 UnresolvedLookupExpr *ULE,
9016 SourceLocation LParenLoc,
9017 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00009018 SourceLocation RParenLoc,
9019 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00009020
9021 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009022 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00009023
John McCall57500772009-12-16 12:17:52 +00009024 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009025 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009026 if (ULE->hasExplicitTemplateArgs()) {
9027 ULE->copyTemplateArgumentsInto(TABuffer);
9028 ExplicitTemplateArgs = &TABuffer;
9029 }
9030
John McCalld681c392009-12-16 08:11:27 +00009031 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9032 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00009033 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9034 ExplicitTemplateArgs, Args, NumArgs) &&
9035 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00009036 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00009037 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00009038 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009039
John McCall57500772009-12-16 12:17:52 +00009040 assert(!R.empty() && "lookup results empty despite recovery");
9041
9042 // Build an implicit member call if appropriate. Just drop the
9043 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009044 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009045 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00009046 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
9047 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009048 else if (ExplicitTemplateArgs)
9049 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
9050 else
9051 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9052
9053 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009054 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009055
9056 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009057 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009058 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009059 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009060 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009061}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009062
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009063/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009064/// (which eventually refers to the declaration Func) and the call
9065/// arguments Args/NumArgs, attempt to resolve the function call down
9066/// to a specific function. If overload resolution succeeds, returns
9067/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009068/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009069/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009070ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009071Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009072 SourceLocation LParenLoc,
9073 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009074 SourceLocation RParenLoc,
9075 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00009076#ifndef NDEBUG
9077 if (ULE->requiresADL()) {
9078 // To do ADL, we must have found an unqualified name.
9079 assert(!ULE->getQualifier() && "qualified name with ADL");
9080
9081 // We don't perform ADL for implicit declarations of builtins.
9082 // Verify that this was correctly set up.
9083 FunctionDecl *F;
9084 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9085 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9086 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009087 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009088
John McCall57500772009-12-16 12:17:52 +00009089 // We don't perform ADL in C.
9090 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009091 } else
9092 assert(!ULE->isStdAssociatedNamespace() &&
9093 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009094#endif
9095
John McCall4124c492011-10-17 18:40:02 +00009096 UnbridgedCastsSet UnbridgedCasts;
9097 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9098 return ExprError();
9099
John McCallbc077cf2010-02-08 23:07:23 +00009100 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009101
John McCall57500772009-12-16 12:17:52 +00009102 // Add the functions denoted by the callee to the set of candidate
9103 // functions, including those from argument-dependent lookup.
9104 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009105
9106 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009107 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9108 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009109 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009110 // In Microsoft mode, if we are inside a template class member function then
9111 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009112 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009113 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00009114 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009115 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009116 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9117 Context.DependentTy, VK_RValue,
9118 RParenLoc);
9119 CE->setTypeDependent(true);
9120 return Owned(CE);
9121 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009122 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00009123 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00009124 }
John McCalld681c392009-12-16 08:11:27 +00009125
John McCall4124c492011-10-17 18:40:02 +00009126 UnbridgedCasts.restore();
9127
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009128 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009129 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009130 case OR_Success: {
9131 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00009132 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009133 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009134 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009135 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009136 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9137 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009138 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009139
Richard Smith998a5912011-06-05 22:42:48 +00009140 case OR_No_Viable_Function: {
9141 // Try to recover by looking for viable functions which the user might
9142 // have meant to call.
9143 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9144 Args, NumArgs, RParenLoc,
9145 /*EmptyLookup=*/false);
9146 if (!Recovery.isInvalid())
9147 return Recovery;
9148
Chris Lattner45d9d602009-02-17 07:29:20 +00009149 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009150 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009151 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009152 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009153 break;
Richard Smith998a5912011-06-05 22:42:48 +00009154 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009155
9156 case OR_Ambiguous:
9157 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009158 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009159 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009160 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009161
9162 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009163 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009164 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9165 << Best->Function->isDeleted()
9166 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009167 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009168 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009169 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009170
9171 // We emitted an error for the unvailable/deleted function call but keep
9172 // the call in the AST.
9173 FunctionDecl *FDecl = Best->Function;
9174 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9175 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9176 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009177 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009178 }
9179
Douglas Gregorb412e172010-07-25 18:17:45 +00009180 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009181 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009182}
9183
John McCall4c4c1df2010-01-26 03:27:55 +00009184static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009185 return Functions.size() > 1 ||
9186 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9187}
9188
Douglas Gregor084d8552009-03-13 23:49:33 +00009189/// \brief Create a unary operation that may resolve to an overloaded
9190/// operator.
9191///
9192/// \param OpLoc The location of the operator itself (e.g., '*').
9193///
9194/// \param OpcIn The UnaryOperator::Opcode that describes this
9195/// operator.
9196///
9197/// \param Functions The set of non-member functions that will be
9198/// considered by overload resolution. The caller needs to build this
9199/// set based on the context using, e.g.,
9200/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9201/// set should not contain any member functions; those will be added
9202/// by CreateOverloadedUnaryOp().
9203///
9204/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009205ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009206Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9207 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009208 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009209 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009210
9211 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9212 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9213 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009214 // TODO: provide better source location info.
9215 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009216
John McCall4124c492011-10-17 18:40:02 +00009217 if (checkPlaceholderForOverload(*this, Input))
9218 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009219
Douglas Gregor084d8552009-03-13 23:49:33 +00009220 Expr *Args[2] = { Input, 0 };
9221 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009222
Douglas Gregor084d8552009-03-13 23:49:33 +00009223 // For post-increment and post-decrement, add the implicit '0' as
9224 // the second argument, so that we know this is a post-increment or
9225 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009226 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009227 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009228 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9229 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009230 NumArgs = 2;
9231 }
9232
9233 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009234 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009235 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009236 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009237 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009238 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009239 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009240
John McCall58cc69d2010-01-27 01:50:18 +00009241 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009242 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009243 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009244 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009245 /*ADL*/ true, IsOverloaded(Fns),
9246 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009247 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009248 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009249 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009250 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009251 OpLoc));
9252 }
9253
9254 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009255 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009256
9257 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009258 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009259
9260 // Add operator candidates that are member functions.
9261 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9262
John McCall4c4c1df2010-01-26 03:27:55 +00009263 // Add candidates from ADL.
9264 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009265 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009266 /*ExplicitTemplateArgs*/ 0,
9267 CandidateSet);
9268
Douglas Gregor084d8552009-03-13 23:49:33 +00009269 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009270 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009271
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9273
Douglas Gregor084d8552009-03-13 23:49:33 +00009274 // Perform overload resolution.
9275 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009276 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009277 case OR_Success: {
9278 // We found a built-in operator or an overloaded operator.
9279 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009280
Douglas Gregor084d8552009-03-13 23:49:33 +00009281 if (FnDecl) {
9282 // We matched an overloaded operator. Build a call to that
9283 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009284
Chandler Carruth30141632011-02-25 19:41:05 +00009285 MarkDeclarationReferenced(OpLoc, FnDecl);
9286
Douglas Gregor084d8552009-03-13 23:49:33 +00009287 // Convert the arguments.
9288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009289 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009290
John Wiegley01296292011-04-08 18:41:53 +00009291 ExprResult InputRes =
9292 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9293 Best->FoundDecl, Method);
9294 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009295 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009296 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009297 } else {
9298 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009299 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009300 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009301 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009302 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009303 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009304 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009305 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009306 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009307 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009308 }
9309
John McCall4fa0d5f2010-05-06 18:15:07 +00009310 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9311
John McCall7decc9e2010-11-18 06:31:45 +00009312 // Determine the result type.
9313 QualType ResultTy = FnDecl->getResultType();
9314 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9315 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009316
Douglas Gregor084d8552009-03-13 23:49:33 +00009317 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009318 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9319 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009320 if (FnExpr.isInvalid())
9321 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009322
Eli Friedman030eee42009-11-18 03:58:17 +00009323 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009324 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009325 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009326 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009328 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009329 FnDecl))
9330 return ExprError();
9331
John McCallb268a282010-08-23 23:25:46 +00009332 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009333 } else {
9334 // We matched a built-in operator. Convert the arguments, then
9335 // break out so that we will build the appropriate built-in
9336 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009337 ExprResult InputRes =
9338 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9339 Best->Conversions[0], AA_Passing);
9340 if (InputRes.isInvalid())
9341 return ExprError();
9342 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009343 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009344 }
John Wiegley01296292011-04-08 18:41:53 +00009345 }
9346
9347 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009348 // This is an erroneous use of an operator which can be overloaded by
9349 // a non-member function. Check for non-member operators which were
9350 // defined too late to be candidates.
9351 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9352 // FIXME: Recover by calling the found function.
9353 return ExprError();
9354
John Wiegley01296292011-04-08 18:41:53 +00009355 // No viable function; fall through to handling this as a
9356 // built-in operator, which will produce an error message for us.
9357 break;
9358
9359 case OR_Ambiguous:
9360 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9361 << UnaryOperator::getOpcodeStr(Opc)
9362 << Input->getType()
9363 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009364 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009365 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9366 return ExprError();
9367
9368 case OR_Deleted:
9369 Diag(OpLoc, diag::err_ovl_deleted_oper)
9370 << Best->Function->isDeleted()
9371 << UnaryOperator::getOpcodeStr(Opc)
9372 << getDeletedOrUnavailableSuffix(Best->Function)
9373 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009374 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9375 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009376 return ExprError();
9377 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009378
9379 // Either we found no viable overloaded operator or we matched a
9380 // built-in operator. In either case, fall through to trying to
9381 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009382 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009383}
9384
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009385/// \brief Create a binary operation that may resolve to an overloaded
9386/// operator.
9387///
9388/// \param OpLoc The location of the operator itself (e.g., '+').
9389///
9390/// \param OpcIn The BinaryOperator::Opcode that describes this
9391/// operator.
9392///
9393/// \param Functions The set of non-member functions that will be
9394/// considered by overload resolution. The caller needs to build this
9395/// set based on the context using, e.g.,
9396/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9397/// set should not contain any member functions; those will be added
9398/// by CreateOverloadedBinOp().
9399///
9400/// \param LHS Left-hand argument.
9401/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009402ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009403Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009404 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009405 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009406 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009407 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009408 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009409
9410 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9411 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9412 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9413
9414 // If either side is type-dependent, create an appropriate dependent
9415 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009416 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009417 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009419 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009420 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009421 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009422 Context.DependentTy,
9423 VK_RValue, OK_Ordinary,
9424 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009425
Douglas Gregor5287f092009-11-05 00:51:44 +00009426 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9427 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009428 VK_LValue,
9429 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009430 Context.DependentTy,
9431 Context.DependentTy,
9432 OpLoc));
9433 }
John McCall4c4c1df2010-01-26 03:27:55 +00009434
9435 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009436 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009437 // TODO: provide better source location info in DNLoc component.
9438 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009439 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009440 = UnresolvedLookupExpr::Create(Context, NamingClass,
9441 NestedNameSpecifierLoc(), OpNameInfo,
9442 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009443 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009444 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009445 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009446 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009447 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009448 OpLoc));
9449 }
9450
John McCall4124c492011-10-17 18:40:02 +00009451 // Always do placeholder-like conversions on the RHS.
9452 if (checkPlaceholderForOverload(*this, Args[1]))
9453 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009454
John McCall526ab472011-10-25 17:37:35 +00009455 // Do placeholder-like conversion on the LHS; note that we should
9456 // not get here with a PseudoObject LHS.
9457 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009458 if (checkPlaceholderForOverload(*this, Args[0]))
9459 return ExprError();
9460
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009461 // If this is the assignment operator, we only perform overload resolution
9462 // if the left-hand side is a class or enumeration type. This is actually
9463 // a hack. The standard requires that we do overload resolution between the
9464 // various built-in candidates, but as DR507 points out, this can lead to
9465 // problems. So we do it this way, which pretty much follows what GCC does.
9466 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009467 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009468 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009469
John McCalle26a8722010-12-04 08:14:53 +00009470 // If this is the .* operator, which is not overloadable, just
9471 // create a built-in binary operator.
9472 if (Opc == BO_PtrMemD)
9473 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9474
Douglas Gregor084d8552009-03-13 23:49:33 +00009475 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009476 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009477
9478 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009479 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009480
9481 // Add operator candidates that are member functions.
9482 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9483
John McCall4c4c1df2010-01-26 03:27:55 +00009484 // Add candidates from ADL.
9485 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9486 Args, 2,
9487 /*ExplicitTemplateArgs*/ 0,
9488 CandidateSet);
9489
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009490 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009491 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009492
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009493 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9494
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009495 // Perform overload resolution.
9496 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009497 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009498 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009499 // We found a built-in operator or an overloaded operator.
9500 FunctionDecl *FnDecl = Best->Function;
9501
9502 if (FnDecl) {
9503 // We matched an overloaded operator. Build a call to that
9504 // operator.
9505
Chandler Carruth30141632011-02-25 19:41:05 +00009506 MarkDeclarationReferenced(OpLoc, FnDecl);
9507
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009508 // Convert the arguments.
9509 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009510 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009511 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009512
Chandler Carruth8e543b32010-12-12 08:17:55 +00009513 ExprResult Arg1 =
9514 PerformCopyInitialization(
9515 InitializedEntity::InitializeParameter(Context,
9516 FnDecl->getParamDecl(0)),
9517 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009518 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009519 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009520
John Wiegley01296292011-04-08 18:41:53 +00009521 ExprResult Arg0 =
9522 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9523 Best->FoundDecl, Method);
9524 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009525 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009526 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009527 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009528 } else {
9529 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009530 ExprResult Arg0 = PerformCopyInitialization(
9531 InitializedEntity::InitializeParameter(Context,
9532 FnDecl->getParamDecl(0)),
9533 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009534 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009535 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009536
Chandler Carruth8e543b32010-12-12 08:17:55 +00009537 ExprResult Arg1 =
9538 PerformCopyInitialization(
9539 InitializedEntity::InitializeParameter(Context,
9540 FnDecl->getParamDecl(1)),
9541 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009542 if (Arg1.isInvalid())
9543 return ExprError();
9544 Args[0] = LHS = Arg0.takeAs<Expr>();
9545 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009546 }
9547
John McCall4fa0d5f2010-05-06 18:15:07 +00009548 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9549
John McCall7decc9e2010-11-18 06:31:45 +00009550 // Determine the result type.
9551 QualType ResultTy = FnDecl->getResultType();
9552 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9553 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009554
9555 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009556 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9557 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009558 if (FnExpr.isInvalid())
9559 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009560
John McCallb268a282010-08-23 23:25:46 +00009561 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009562 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009563 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009564
9565 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009566 FnDecl))
9567 return ExprError();
9568
John McCallb268a282010-08-23 23:25:46 +00009569 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009570 } else {
9571 // We matched a built-in operator. Convert the arguments, then
9572 // break out so that we will build the appropriate built-in
9573 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009574 ExprResult ArgsRes0 =
9575 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9576 Best->Conversions[0], AA_Passing);
9577 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009578 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009579 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009580
John Wiegley01296292011-04-08 18:41:53 +00009581 ExprResult ArgsRes1 =
9582 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9583 Best->Conversions[1], AA_Passing);
9584 if (ArgsRes1.isInvalid())
9585 return ExprError();
9586 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009587 break;
9588 }
9589 }
9590
Douglas Gregor66950a32009-09-30 21:46:01 +00009591 case OR_No_Viable_Function: {
9592 // C++ [over.match.oper]p9:
9593 // If the operator is the operator , [...] and there are no
9594 // viable functions, then the operator is assumed to be the
9595 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009596 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009597 break;
9598
Chandler Carruth8e543b32010-12-12 08:17:55 +00009599 // For class as left operand for assignment or compound assigment
9600 // operator do not fall through to handling in built-in, but report that
9601 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009602 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009603 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009604 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009605 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9606 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009607 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009608 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009609 // This is an erroneous use of an operator which can be overloaded by
9610 // a non-member function. Check for non-member operators which were
9611 // defined too late to be candidates.
9612 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9613 // FIXME: Recover by calling the found function.
9614 return ExprError();
9615
Douglas Gregor66950a32009-09-30 21:46:01 +00009616 // No viable function; try to create a built-in operation, which will
9617 // produce an error. Then, show the non-viable candidates.
9618 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009620 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009621 "C++ binary operator overloading is missing candidates!");
9622 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009623 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9624 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009625 return move(Result);
9626 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009627
9628 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009629 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009630 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009631 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009632 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009633 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9634 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009635 return ExprError();
9636
9637 case OR_Deleted:
9638 Diag(OpLoc, diag::err_ovl_deleted_oper)
9639 << Best->Function->isDeleted()
9640 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009641 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009642 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009643 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9644 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009645 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009646 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009647
Douglas Gregor66950a32009-09-30 21:46:01 +00009648 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009649 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009650}
9651
John McCalldadc5752010-08-24 06:29:42 +00009652ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009653Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9654 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009655 Expr *Base, Expr *Idx) {
9656 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009657 DeclarationName OpName =
9658 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9659
9660 // If either side is type-dependent, create an appropriate dependent
9661 // expression.
9662 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9663
John McCall58cc69d2010-01-27 01:50:18 +00009664 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009665 // CHECKME: no 'operator' keyword?
9666 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9667 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009668 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009669 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009670 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009671 /*ADL*/ true, /*Overloaded*/ false,
9672 UnresolvedSetIterator(),
9673 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009674 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009675
Sebastian Redladba46e2009-10-29 20:17:01 +00009676 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9677 Args, 2,
9678 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009679 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009680 RLoc));
9681 }
9682
John McCall4124c492011-10-17 18:40:02 +00009683 // Handle placeholders on both operands.
9684 if (checkPlaceholderForOverload(*this, Args[0]))
9685 return ExprError();
9686 if (checkPlaceholderForOverload(*this, Args[1]))
9687 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009688
Sebastian Redladba46e2009-10-29 20:17:01 +00009689 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009690 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009691
9692 // Subscript can only be overloaded as a member function.
9693
9694 // Add operator candidates that are member functions.
9695 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9696
9697 // Add builtin operator candidates.
9698 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9699
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009700 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9701
Sebastian Redladba46e2009-10-29 20:17:01 +00009702 // Perform overload resolution.
9703 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009704 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009705 case OR_Success: {
9706 // We found a built-in operator or an overloaded operator.
9707 FunctionDecl *FnDecl = Best->Function;
9708
9709 if (FnDecl) {
9710 // We matched an overloaded operator. Build a call to that
9711 // operator.
9712
Chandler Carruth30141632011-02-25 19:41:05 +00009713 MarkDeclarationReferenced(LLoc, FnDecl);
9714
John McCalla0296f72010-03-19 07:35:19 +00009715 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009716 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009717
Sebastian Redladba46e2009-10-29 20:17:01 +00009718 // Convert the arguments.
9719 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009720 ExprResult Arg0 =
9721 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9722 Best->FoundDecl, Method);
9723 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009724 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009725 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009726
Anders Carlssona68e51e2010-01-29 18:37:50 +00009727 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009728 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009729 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009730 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009731 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009732 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009733 Owned(Args[1]));
9734 if (InputInit.isInvalid())
9735 return ExprError();
9736
9737 Args[1] = InputInit.takeAs<Expr>();
9738
Sebastian Redladba46e2009-10-29 20:17:01 +00009739 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009740 QualType ResultTy = FnDecl->getResultType();
9741 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9742 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009743
9744 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009745 DeclarationNameLoc LocInfo;
9746 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9747 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009748 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9749 HadMultipleCandidates,
9750 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009751 if (FnExpr.isInvalid())
9752 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009753
John McCallb268a282010-08-23 23:25:46 +00009754 CXXOperatorCallExpr *TheCall =
9755 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009756 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009757 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009758
John McCallb268a282010-08-23 23:25:46 +00009759 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009760 FnDecl))
9761 return ExprError();
9762
John McCallb268a282010-08-23 23:25:46 +00009763 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009764 } else {
9765 // We matched a built-in operator. Convert the arguments, then
9766 // break out so that we will build the appropriate built-in
9767 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009768 ExprResult ArgsRes0 =
9769 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9770 Best->Conversions[0], AA_Passing);
9771 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009772 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009773 Args[0] = ArgsRes0.take();
9774
9775 ExprResult ArgsRes1 =
9776 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9777 Best->Conversions[1], AA_Passing);
9778 if (ArgsRes1.isInvalid())
9779 return ExprError();
9780 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009781
9782 break;
9783 }
9784 }
9785
9786 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009787 if (CandidateSet.empty())
9788 Diag(LLoc, diag::err_ovl_no_oper)
9789 << Args[0]->getType() << /*subscript*/ 0
9790 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9791 else
9792 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9793 << Args[0]->getType()
9794 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009795 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9796 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009797 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009798 }
9799
9800 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009801 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009802 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009803 << Args[0]->getType() << Args[1]->getType()
9804 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009805 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9806 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009807 return ExprError();
9808
9809 case OR_Deleted:
9810 Diag(LLoc, diag::err_ovl_deleted_oper)
9811 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009812 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9815 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009816 return ExprError();
9817 }
9818
9819 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009820 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009821}
9822
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009823/// BuildCallToMemberFunction - Build a call to a member
9824/// function. MemExpr is the expression that refers to the member
9825/// function (and includes the object parameter), Args/NumArgs are the
9826/// arguments to the function call (not including the object
9827/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009828/// expression refers to a non-static member function or an overloaded
9829/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009830ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009831Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9832 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009833 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009834 assert(MemExprE->getType() == Context.BoundMemberTy ||
9835 MemExprE->getType() == Context.OverloadTy);
9836
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009837 // Dig out the member expression. This holds both the object
9838 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009839 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009840
John McCall0009fcc2011-04-26 20:42:42 +00009841 // Determine whether this is a call to a pointer-to-member function.
9842 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9843 assert(op->getType() == Context.BoundMemberTy);
9844 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9845
9846 QualType fnType =
9847 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9848
9849 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9850 QualType resultType = proto->getCallResultType(Context);
9851 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9852
9853 // Check that the object type isn't more qualified than the
9854 // member function we're calling.
9855 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9856
9857 QualType objectType = op->getLHS()->getType();
9858 if (op->getOpcode() == BO_PtrMemI)
9859 objectType = objectType->castAs<PointerType>()->getPointeeType();
9860 Qualifiers objectQuals = objectType.getQualifiers();
9861
9862 Qualifiers difference = objectQuals - funcQuals;
9863 difference.removeObjCGCAttr();
9864 difference.removeAddressSpace();
9865 if (difference) {
9866 std::string qualsString = difference.getAsString();
9867 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9868 << fnType.getUnqualifiedType()
9869 << qualsString
9870 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9871 }
9872
9873 CXXMemberCallExpr *call
9874 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9875 resultType, valueKind, RParenLoc);
9876
9877 if (CheckCallReturnType(proto->getResultType(),
9878 op->getRHS()->getSourceRange().getBegin(),
9879 call, 0))
9880 return ExprError();
9881
9882 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9883 return ExprError();
9884
9885 return MaybeBindToTemporary(call);
9886 }
9887
John McCall4124c492011-10-17 18:40:02 +00009888 UnbridgedCastsSet UnbridgedCasts;
9889 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9890 return ExprError();
9891
John McCall10eae182009-11-30 22:42:35 +00009892 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009893 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009894 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009895 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009896 if (isa<MemberExpr>(NakedMemExpr)) {
9897 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009898 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009899 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009900 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009901 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009902 } else {
9903 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009904 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009905
John McCall6e9f8f62009-12-03 04:06:58 +00009906 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009907 Expr::Classification ObjectClassification
9908 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9909 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009910
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009911 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009912 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009913
John McCall2d74de92009-12-01 22:10:20 +00009914 // FIXME: avoid copy.
9915 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9916 if (UnresExpr->hasExplicitTemplateArgs()) {
9917 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9918 TemplateArgs = &TemplateArgsBuffer;
9919 }
9920
John McCall10eae182009-11-30 22:42:35 +00009921 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9922 E = UnresExpr->decls_end(); I != E; ++I) {
9923
John McCall6e9f8f62009-12-03 04:06:58 +00009924 NamedDecl *Func = *I;
9925 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9926 if (isa<UsingShadowDecl>(Func))
9927 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9928
Douglas Gregor02824322011-01-26 19:30:28 +00009929
Francois Pichet64225792011-01-18 05:04:39 +00009930 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009931 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009932 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9933 CandidateSet);
9934 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009935 // If explicit template arguments were provided, we can't call a
9936 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009937 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009938 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009939
John McCalla0296f72010-03-19 07:35:19 +00009940 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009941 ObjectClassification,
9942 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009943 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009944 } else {
John McCall10eae182009-11-30 22:42:35 +00009945 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009946 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009947 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009948 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009949 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009950 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009951 }
Mike Stump11289f42009-09-09 15:08:12 +00009952
John McCall10eae182009-11-30 22:42:35 +00009953 DeclarationName DeclName = UnresExpr->getMemberName();
9954
John McCall4124c492011-10-17 18:40:02 +00009955 UnbridgedCasts.restore();
9956
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009957 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009958 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009959 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009960 case OR_Success:
9961 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009962 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009963 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009964 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009965 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009966 break;
9967
9968 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009969 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009970 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009971 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009973 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009974 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009975
9976 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009977 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009978 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009979 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009980 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009981 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009982
9983 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009984 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009985 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009986 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009987 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009988 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009990 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009991 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009992 }
9993
John McCall16df1e52010-03-30 21:47:33 +00009994 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009995
John McCall2d74de92009-12-01 22:10:20 +00009996 // If overload resolution picked a static member, build a
9997 // non-member call based on that function.
9998 if (Method->isStatic()) {
9999 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10000 Args, NumArgs, RParenLoc);
10001 }
10002
John McCall10eae182009-11-30 22:42:35 +000010003 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010004 }
10005
John McCall7decc9e2010-11-18 06:31:45 +000010006 QualType ResultType = Method->getResultType();
10007 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10008 ResultType = ResultType.getNonLValueExprType(Context);
10009
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010010 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010011 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010012 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010013 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010014
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010015 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010016 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010017 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010018 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010019
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010020 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010021 // We only need to do this if there was actually an overload; otherwise
10022 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010023 if (!Method->isStatic()) {
10024 ExprResult ObjectArg =
10025 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10026 FoundDecl, Method);
10027 if (ObjectArg.isInvalid())
10028 return ExprError();
10029 MemExpr->setBase(ObjectArg.take());
10030 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010031
10032 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010033 const FunctionProtoType *Proto =
10034 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010035 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010036 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010037 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010038
John McCallb268a282010-08-23 23:25:46 +000010039 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010040 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010041
Anders Carlsson47061ee2011-05-06 14:25:31 +000010042 if ((isa<CXXConstructorDecl>(CurContext) ||
10043 isa<CXXDestructorDecl>(CurContext)) &&
10044 TheCall->getMethodDecl()->isPure()) {
10045 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10046
Chandler Carruth59259262011-06-27 08:31:58 +000010047 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010048 Diag(MemExpr->getLocStart(),
10049 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10050 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10051 << MD->getParent()->getDeclName();
10052
10053 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010054 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010055 }
John McCallb268a282010-08-23 23:25:46 +000010056 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010057}
10058
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010059/// BuildCallToObjectOfClassType - Build a call to an object of class
10060/// type (C++ [over.call.object]), which can end up invoking an
10061/// overloaded function call operator (@c operator()) or performing a
10062/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010063ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010064Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010065 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010066 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010067 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010068 if (checkPlaceholderForOverload(*this, Obj))
10069 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010070 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010071
10072 UnbridgedCastsSet UnbridgedCasts;
10073 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10074 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010075
John Wiegley01296292011-04-08 18:41:53 +000010076 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10077 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010078
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010079 // C++ [over.call.object]p1:
10080 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010081 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010082 // candidate functions includes at least the function call
10083 // operators of T. The function call operators of T are obtained by
10084 // ordinary lookup of the name operator() in the context of
10085 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010086 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010087 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010088
John Wiegley01296292011-04-08 18:41:53 +000010089 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010090 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010091 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010092 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010093
John McCall27b18f82009-11-17 02:14:36 +000010094 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10095 LookupQualifiedName(R, Record->getDecl());
10096 R.suppressDiagnostics();
10097
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010098 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010099 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010100 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10101 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010102 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010104
Douglas Gregorab7897a2008-11-19 22:57:39 +000010105 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010106 // In addition, for each (non-explicit in C++0x) conversion function
10107 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010108 //
10109 // operator conversion-type-id () cv-qualifier;
10110 //
10111 // where cv-qualifier is the same cv-qualification as, or a
10112 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010113 // denotes the type "pointer to function of (P1,...,Pn) returning
10114 // R", or the type "reference to pointer to function of
10115 // (P1,...,Pn) returning R", or the type "reference to function
10116 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010117 // is also considered as a candidate function. Similarly,
10118 // surrogate call functions are added to the set of candidate
10119 // functions for each conversion function declared in an
10120 // accessible base class provided the function is not hidden
10121 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010122 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010123 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010124 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010125 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010126 NamedDecl *D = *I;
10127 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10128 if (isa<UsingShadowDecl>(D))
10129 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010130
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010131 // Skip over templated conversion functions; they aren't
10132 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010133 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010134 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010135
John McCall6e9f8f62009-12-03 04:06:58 +000010136 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010137 if (!Conv->isExplicit()) {
10138 // Strip the reference type (if any) and then the pointer type (if
10139 // any) to get down to what might be a function type.
10140 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10141 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10142 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010143
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010144 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10145 {
10146 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10147 Object.get(), Args, NumArgs, CandidateSet);
10148 }
10149 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010150 }
Mike Stump11289f42009-09-09 15:08:12 +000010151
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010152 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10153
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010154 // Perform overload resolution.
10155 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010156 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010157 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010158 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010159 // Overload resolution succeeded; we'll build the appropriate call
10160 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010161 break;
10162
10163 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010164 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +000010165 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10166 << Object.get()->getType() << /*call*/ 1
10167 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010168 else
John Wiegley01296292011-04-08 18:41:53 +000010169 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +000010170 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010171 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010173 break;
10174
10175 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +000010176 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010177 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010178 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010179 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010180 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010181
10182 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010183 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010184 diag::err_ovl_deleted_object_call)
10185 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010186 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010187 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010188 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010189 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010190 break;
Mike Stump11289f42009-09-09 15:08:12 +000010191 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010192
Douglas Gregorb412e172010-07-25 18:17:45 +000010193 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010194 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010195
John McCall4124c492011-10-17 18:40:02 +000010196 UnbridgedCasts.restore();
10197
Douglas Gregorab7897a2008-11-19 22:57:39 +000010198 if (Best->Function == 0) {
10199 // Since there is no function declaration, this is one of the
10200 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010201 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010202 = cast<CXXConversionDecl>(
10203 Best->Conversions[0].UserDefined.ConversionFunction);
10204
John Wiegley01296292011-04-08 18:41:53 +000010205 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010206 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010207
Douglas Gregorab7897a2008-11-19 22:57:39 +000010208 // We selected one of the surrogate functions that converts the
10209 // object parameter to a function pointer. Perform the conversion
10210 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010211
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010212 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010213 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010214 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10215 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010216 if (Call.isInvalid())
10217 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010218 // Record usage of conversion in an implicit cast.
10219 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10220 CK_UserDefinedConversion,
10221 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010222
Douglas Gregor668443e2011-01-20 00:18:04 +000010223 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010224 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010225 }
10226
Chandler Carruth30141632011-02-25 19:41:05 +000010227 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010228 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010229 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010230
Douglas Gregorab7897a2008-11-19 22:57:39 +000010231 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10232 // that calls this method, using Object for the implicit object
10233 // parameter and passing along the remaining arguments.
10234 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010235 const FunctionProtoType *Proto =
10236 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010237
10238 unsigned NumArgsInProto = Proto->getNumArgs();
10239 unsigned NumArgsToCheck = NumArgs;
10240
10241 // Build the full argument list for the method call (the
10242 // implicit object parameter is placed at the beginning of the
10243 // list).
10244 Expr **MethodArgs;
10245 if (NumArgs < NumArgsInProto) {
10246 NumArgsToCheck = NumArgsInProto;
10247 MethodArgs = new Expr*[NumArgsInProto + 1];
10248 } else {
10249 MethodArgs = new Expr*[NumArgs + 1];
10250 }
John Wiegley01296292011-04-08 18:41:53 +000010251 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010252 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10253 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010254
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010255 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10256 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010257 if (NewFn.isInvalid())
10258 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010259
10260 // Once we've built TheCall, all of the expressions are properly
10261 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010262 QualType ResultTy = Method->getResultType();
10263 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10264 ResultTy = ResultTy.getNonLValueExprType(Context);
10265
John McCallb268a282010-08-23 23:25:46 +000010266 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010267 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010268 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010269 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010270 delete [] MethodArgs;
10271
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010272 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010273 Method))
10274 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010275
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010276 // We may have default arguments. If so, we need to allocate more
10277 // slots in the call for them.
10278 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010279 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010280 else if (NumArgs > NumArgsInProto)
10281 NumArgsToCheck = NumArgsInProto;
10282
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010283 bool IsError = false;
10284
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010285 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010286 ExprResult ObjRes =
10287 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10288 Best->FoundDecl, Method);
10289 if (ObjRes.isInvalid())
10290 IsError = true;
10291 else
10292 Object = move(ObjRes);
10293 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010294
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010295 // Check the argument types.
10296 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010297 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010298 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010299 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010300
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010301 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010302
John McCalldadc5752010-08-24 06:29:42 +000010303 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010304 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010305 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010306 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010307 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010308
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010309 IsError |= InputInit.isInvalid();
10310 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010311 } else {
John McCalldadc5752010-08-24 06:29:42 +000010312 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010313 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10314 if (DefArg.isInvalid()) {
10315 IsError = true;
10316 break;
10317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010318
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010319 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010320 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010321
10322 TheCall->setArg(i + 1, Arg);
10323 }
10324
10325 // If this is a variadic call, handle args passed through "...".
10326 if (Proto->isVariadic()) {
10327 // Promote the arguments (C99 6.5.2.2p7).
10328 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010329 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10330 IsError |= Arg.isInvalid();
10331 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010332 }
10333 }
10334
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010335 if (IsError) return true;
10336
John McCallb268a282010-08-23 23:25:46 +000010337 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010338 return true;
10339
John McCalle172be52010-08-24 06:09:16 +000010340 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010341}
10342
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010343/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010344/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010345/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010346ExprResult
John McCallb268a282010-08-23 23:25:46 +000010347Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010348 assert(Base->getType()->isRecordType() &&
10349 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010350
John McCall4124c492011-10-17 18:40:02 +000010351 if (checkPlaceholderForOverload(*this, Base))
10352 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010353
John McCallbc077cf2010-02-08 23:07:23 +000010354 SourceLocation Loc = Base->getExprLoc();
10355
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010356 // C++ [over.ref]p1:
10357 //
10358 // [...] An expression x->m is interpreted as (x.operator->())->m
10359 // for a class object x of type T if T::operator->() exists and if
10360 // the operator is selected as the best match function by the
10361 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010362 DeclarationName OpName =
10363 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010364 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010365 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010366
John McCallbc077cf2010-02-08 23:07:23 +000010367 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010368 PDiag(diag::err_typecheck_incomplete_tag)
10369 << Base->getSourceRange()))
10370 return ExprError();
10371
John McCall27b18f82009-11-17 02:14:36 +000010372 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10373 LookupQualifiedName(R, BaseRecord->getDecl());
10374 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010375
10376 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010377 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010378 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10379 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010380 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010381
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010382 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10383
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010384 // Perform overload resolution.
10385 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010386 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010387 case OR_Success:
10388 // Overload resolution succeeded; we'll build the call below.
10389 break;
10390
10391 case OR_No_Viable_Function:
10392 if (CandidateSet.empty())
10393 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010394 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010395 else
10396 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010397 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010399 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010400
10401 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010402 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10403 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010404 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010405 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010406
10407 case OR_Deleted:
10408 Diag(OpLoc, diag::err_ovl_deleted_oper)
10409 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010410 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010411 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010412 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010414 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010415 }
10416
Chandler Carruth30141632011-02-25 19:41:05 +000010417 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010418 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010419 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010420
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010421 // Convert the object parameter.
10422 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010423 ExprResult BaseResult =
10424 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10425 Best->FoundDecl, Method);
10426 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010427 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010428 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010429
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010430 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010431 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10432 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010433 if (FnExpr.isInvalid())
10434 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010435
John McCall7decc9e2010-11-18 06:31:45 +000010436 QualType ResultTy = Method->getResultType();
10437 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10438 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010439 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010440 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010441 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010442
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010443 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010444 Method))
10445 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010446
10447 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010448}
10449
Douglas Gregorcd695e52008-11-10 20:40:00 +000010450/// FixOverloadedFunctionReference - E is an expression that refers to
10451/// a C++ overloaded function (possibly with some parentheses and
10452/// perhaps a '&' around it). We have resolved the overloaded function
10453/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010454/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010455Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010456 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010457 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010458 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10459 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010460 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010461 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010462
Douglas Gregor51c538b2009-11-20 19:42:02 +000010463 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010464 }
10465
Douglas Gregor51c538b2009-11-20 19:42:02 +000010466 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010467 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10468 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010469 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010470 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010471 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010472 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010473 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010474 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010475
10476 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010477 ICE->getCastKind(),
10478 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010479 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010480 }
10481
Douglas Gregor51c538b2009-11-20 19:42:02 +000010482 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010483 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010484 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10486 if (Method->isStatic()) {
10487 // Do nothing: static member functions aren't any different
10488 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010489 } else {
John McCalle66edc12009-11-24 19:00:30 +000010490 // Fix the sub expression, which really has to be an
10491 // UnresolvedLookupExpr holding an overloaded member function
10492 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010493 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10494 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010495 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010496 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010497
John McCalld14a8642009-11-21 08:51:07 +000010498 assert(isa<DeclRefExpr>(SubExpr)
10499 && "fixed to something other than a decl ref");
10500 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10501 && "fixed to a member ref with no nested name qualifier");
10502
10503 // We have taken the address of a pointer to member
10504 // function. Perform the computation here so that we get the
10505 // appropriate pointer to member type.
10506 QualType ClassType
10507 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10508 QualType MemPtrType
10509 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10510
John McCall7decc9e2010-11-18 06:31:45 +000010511 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10512 VK_RValue, OK_Ordinary,
10513 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010514 }
10515 }
John McCall16df1e52010-03-30 21:47:33 +000010516 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10517 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010518 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010519 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010520
John McCalle3027922010-08-25 11:45:40 +000010521 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010522 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010523 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010524 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010525 }
John McCalld14a8642009-11-21 08:51:07 +000010526
10527 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010528 // FIXME: avoid copy.
10529 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010530 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010531 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10532 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010533 }
10534
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010535 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10536 ULE->getQualifierLoc(),
10537 Fn,
10538 ULE->getNameLoc(),
10539 Fn->getType(),
10540 VK_LValue,
10541 Found.getDecl(),
10542 TemplateArgs);
10543 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10544 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010545 }
10546
John McCall10eae182009-11-30 22:42:35 +000010547 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010548 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010549 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10550 if (MemExpr->hasExplicitTemplateArgs()) {
10551 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10552 TemplateArgs = &TemplateArgsBuffer;
10553 }
John McCall6b51f282009-11-23 01:53:49 +000010554
John McCall2d74de92009-12-01 22:10:20 +000010555 Expr *Base;
10556
John McCall7decc9e2010-11-18 06:31:45 +000010557 // If we're filling in a static method where we used to have an
10558 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010559 if (MemExpr->isImplicitAccess()) {
10560 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010561 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10562 MemExpr->getQualifierLoc(),
10563 Fn,
10564 MemExpr->getMemberLoc(),
10565 Fn->getType(),
10566 VK_LValue,
10567 Found.getDecl(),
10568 TemplateArgs);
10569 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10570 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010571 } else {
10572 SourceLocation Loc = MemExpr->getMemberLoc();
10573 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010574 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010575 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010576 Base = new (Context) CXXThisExpr(Loc,
10577 MemExpr->getBaseType(),
10578 /*isImplicit=*/true);
10579 }
John McCall2d74de92009-12-01 22:10:20 +000010580 } else
John McCallc3007a22010-10-26 07:05:15 +000010581 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010582
John McCall4adb38c2011-04-27 00:36:17 +000010583 ExprValueKind valueKind;
10584 QualType type;
10585 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10586 valueKind = VK_LValue;
10587 type = Fn->getType();
10588 } else {
10589 valueKind = VK_RValue;
10590 type = Context.BoundMemberTy;
10591 }
10592
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010593 MemberExpr *ME = MemberExpr::Create(Context, Base,
10594 MemExpr->isArrow(),
10595 MemExpr->getQualifierLoc(),
10596 Fn,
10597 Found,
10598 MemExpr->getMemberNameInfo(),
10599 TemplateArgs,
10600 type, valueKind, OK_Ordinary);
10601 ME->setHadMultipleCandidates(true);
10602 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010604
John McCallc3007a22010-10-26 07:05:15 +000010605 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000010606}
10607
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010608ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010609 DeclAccessPair Found,
10610 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010611 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010612}
10613
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010614} // end namespace clang