blob: c7f33943437b48b3f71a048233b3ac30b510f0a3 [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
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
Richard Smith66e05fe2012-01-18 05:21:49 +0000295 assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
301 switch (Second) {
302 // -- from a floating-point type to an integer type, or
303 //
304 // -- from an integer type or unscoped enumeration type to a floating-point
305 // type, except where the source is a constant expression and the actual
306 // value after conversion will fit into the target type and will produce
307 // the original value when converted back to the original type, or
308 case ICK_Floating_Integral:
309 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
310 return NK_Type_Narrowing;
311 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
312 llvm::APSInt IntConstantValue;
313 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
314 if (Initializer &&
315 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
316 // Convert the integer to the floating type.
317 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
318 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
319 llvm::APFloat::rmNearestTiesToEven);
320 // And back.
321 llvm::APSInt ConvertedValue = IntConstantValue;
322 bool ignored;
323 Result.convertToInteger(ConvertedValue,
324 llvm::APFloat::rmTowardZero, &ignored);
325 // If the resulting value is different, this was a narrowing conversion.
326 if (IntConstantValue != ConvertedValue) {
327 ConstantValue = APValue(IntConstantValue);
328 return NK_Constant_Narrowing;
329 }
330 } else {
331 // Variables are always narrowings.
332 return NK_Variable_Narrowing;
333 }
334 }
335 return NK_Not_Narrowing;
336
337 // -- from long double to double or float, or from double to float, except
338 // where the source is a constant expression and the actual value after
339 // conversion is within the range of values that can be represented (even
340 // if it cannot be represented exactly), or
341 case ICK_Floating_Conversion:
342 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
343 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
344 // FromType is larger than ToType.
345 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
346 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 // Constant!
348 assert(ConstantValue.isFloat());
349 llvm::APFloat FloatVal = ConstantValue.getFloat();
350 // Convert the source value into the target type.
351 bool ignored;
352 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
353 Ctx.getFloatTypeSemantics(ToType),
354 llvm::APFloat::rmNearestTiesToEven, &ignored);
355 // If there was no overflow, the source value is within the range of
356 // values that can be represented.
357 if (ConvertStatus & llvm::APFloat::opOverflow)
358 return NK_Constant_Narrowing;
359 } else {
360 return NK_Variable_Narrowing;
361 }
362 }
363 return NK_Not_Narrowing;
364
365 // -- from an integer type or unscoped enumeration type to an integer type
366 // that cannot represent all the values of the original type, except where
367 // the source is a constant expression and the actual value after
368 // conversion will fit into the target type and will produce the original
369 // value when converted back to the original type.
370 case ICK_Boolean_Conversion: // Bools are integers too.
371 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
372 // Boolean conversions can be from pointers and pointers to members
373 // [conv.bool], and those aren't considered narrowing conversions.
374 return NK_Not_Narrowing;
375 } // Otherwise, fall through to the integral case.
376 case ICK_Integral_Conversion: {
377 assert(FromType->isIntegralOrUnscopedEnumerationType());
378 assert(ToType->isIntegralOrUnscopedEnumerationType());
379 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
380 const unsigned FromWidth = Ctx.getIntWidth(FromType);
381 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
382 const unsigned ToWidth = Ctx.getIntWidth(ToType);
383
384 if (FromWidth > ToWidth ||
385 (FromWidth == ToWidth && FromSigned != ToSigned)) {
386 // Not all values of FromType can be represented in ToType.
387 llvm::APSInt InitializerValue;
388 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
389 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
390 ConstantValue = APValue(InitializerValue);
391
392 // Add a bit to the InitializerValue so we don't have to worry about
393 // signed vs. unsigned comparisons.
394 InitializerValue = InitializerValue.extend(
395 InitializerValue.getBitWidth() + 1);
396 // Convert the initializer to and from the target width and signed-ness.
397 llvm::APSInt ConvertedValue = InitializerValue;
398 ConvertedValue = ConvertedValue.trunc(ToWidth);
399 ConvertedValue.setIsSigned(ToSigned);
400 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
401 ConvertedValue.setIsSigned(InitializerValue.isSigned());
402 // If the result is different, this was a narrowing conversion.
403 if (ConvertedValue != InitializerValue)
404 return NK_Constant_Narrowing;
405 } else {
406 // Variables are always narrowings.
407 return NK_Variable_Narrowing;
408 }
409 }
410 return NK_Not_Narrowing;
411 }
412
413 default:
414 // Other kinds of conversions are not narrowings.
415 return NK_Not_Narrowing;
416 }
417}
418
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000419/// DebugPrint - Print this standard conversion sequence to standard
420/// error. Useful for debugging overloading issues.
421void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000422 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000423 bool PrintedSomething = false;
424 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000425 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000426 PrintedSomething = true;
427 }
428
429 if (Second != ICK_Identity) {
430 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000431 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000432 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434
435 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000436 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000437 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000439 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442 PrintedSomething = true;
443 }
444
445 if (Third != ICK_Identity) {
446 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000448 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
456}
457
458/// DebugPrint - Print this user-defined conversion sequence to standard
459/// error. Useful for debugging overloading issues.
460void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000461 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 if (Before.First || Before.Second || Before.Third) {
463 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000466 if (ConversionFunction)
467 OS << '\'' << *ConversionFunction << '\'';
468 else
469 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 After.DebugPrint();
473 }
474}
475
476/// DebugPrint - Print this implicit conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 switch (ConversionKind) {
481 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 Standard.DebugPrint();
484 break;
485 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 UserDefined.DebugPrint();
488 break;
489 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 break;
John McCall0d1da222010-01-12 00:44:57 +0000492 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000494 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 }
499
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000500 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501}
502
John McCall0d1da222010-01-12 00:44:57 +0000503void AmbiguousConversionSequence::construct() {
504 new (&conversions()) ConversionSet();
505}
506
507void AmbiguousConversionSequence::destruct() {
508 conversions().~ConversionSet();
509}
510
511void
512AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
513 FromTypePtr = O.FromTypePtr;
514 ToTypePtr = O.ToTypePtr;
515 new (&conversions()) ConversionSet(O.conversions());
516}
517
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518namespace {
519 // Structure used by OverloadCandidate::DeductionFailureInfo to store
520 // template parameter and template argument information.
521 struct DFIParamWithArguments {
522 TemplateParameter Param;
523 TemplateArgument FirstArg;
524 TemplateArgument SecondArg;
525 };
526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528/// \brief Convert from Sema's representation of template deduction information
529/// to the form used in overload-candidate information.
530OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000531static MakeDeductionFailureInfo(ASTContext &Context,
532 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000533 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534 OverloadCandidate::DeductionFailureInfo Result;
535 Result.Result = static_cast<unsigned>(TDK);
536 Result.Data = 0;
537 switch (TDK) {
538 case Sema::TDK_Success:
539 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000540 case Sema::TDK_TooManyArguments:
541 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000544 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000545 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546 Result.Data = Info.Param.getOpaqueValue();
547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000550 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000551 // FIXME: Should allocate from normal heap so that we can free this later.
552 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 Saved->Param = Info.Param;
554 Saved->FirstArg = Info.FirstArg;
555 Saved->SecondArg = Info.SecondArg;
556 Result.Data = Saved;
557 break;
558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000561 Result.Data = Info.take();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569 return Result;
570}
John McCall0d1da222010-01-12 00:44:57 +0000571
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572void OverloadCandidate::DeductionFailureInfo::Destroy() {
573 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
574 case Sema::TDK_Success:
575 case Sema::TDK_InstantiationDepth:
576 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000579 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000583 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000584 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 Data = 0;
586 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000587
588 case Sema::TDK_SubstitutionFailure:
589 // FIXME: Destroy the template arugment list?
590 Data = 0;
591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor461761d2010-05-08 18:20:53 +0000593 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000595 case Sema::TDK_FailedOverloadResolution:
596 break;
597 }
598}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
600TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
602 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
603 case Sema::TDK_Success:
604 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000611 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613
614 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000615 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000618 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
621 break;
622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 return TemplateParameter();
625}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregord09efd42010-05-08 20:07:26 +0000627TemplateArgumentList *
628OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
634 case Sema::TDK_Incomplete:
635 case Sema::TDK_InvalidExplicitArguments:
636 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000637 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000638 return 0;
639
640 case Sema::TDK_SubstitutionFailure:
641 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregord09efd42010-05-08 20:07:26 +0000643 // Unhandled
644 case Sema::TDK_NonDeducedMismatch:
645 case Sema::TDK_FailedOverloadResolution:
646 break;
647 }
648
649 return 0;
650}
651
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
655 case Sema::TDK_InstantiationDepth:
656 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000659 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000660 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 return 0;
662
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000666
Douglas Gregor461761d2010-05-08 18:20:53 +0000667 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 case Sema::TDK_FailedOverloadResolution:
670 break;
671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675
676const TemplateArgument *
677OverloadCandidate::DeductionFailureInfo::getSecondArg() {
678 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679 case Sema::TDK_Success:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000682 case Sema::TDK_TooManyArguments:
683 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000685 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686 return 0;
687
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
Douglas Gregor461761d2010-05-08 18:20:53 +0000692 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 case Sema::TDK_FailedOverloadResolution:
695 break;
696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return 0;
699}
700
701void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000702 for (iterator i = begin(), e = end(); i != e; ++i)
703 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
704 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000705 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000706 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 Functions.clear();
708}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
John McCall4124c492011-10-17 18:40:02 +0000710namespace {
711 class UnbridgedCastsSet {
712 struct Entry {
713 Expr **Addr;
714 Expr *Saved;
715 };
716 SmallVector<Entry, 2> Entries;
717
718 public:
719 void save(Sema &S, Expr *&E) {
720 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
721 Entry entry = { &E, E };
722 Entries.push_back(entry);
723 E = S.stripARCUnbridgedCast(E);
724 }
725
726 void restore() {
727 for (SmallVectorImpl<Entry>::iterator
728 i = Entries.begin(), e = Entries.end(); i != e; ++i)
729 *i->Addr = i->Saved;
730 }
731 };
732}
733
734/// checkPlaceholderForOverload - Do any interesting placeholder-like
735/// preprocessing on the given expression.
736///
737/// \param unbridgedCasts a collection to which to add unbridged casts;
738/// without this, they will be immediately diagnosed as errors
739///
740/// Return true on unrecoverable error.
741static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
742 UnbridgedCastsSet *unbridgedCasts = 0) {
Richard Smithfd555f62012-02-22 02:04:18 +0000743 S.RequireCompleteType(E->getExprLoc(), E->getType(), 0);
744
John McCall4124c492011-10-17 18:40:02 +0000745 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
746 // We can't handle overloaded expressions here because overload
747 // resolution might reasonably tweak them.
748 if (placeholder->getKind() == BuiltinType::Overload) return false;
749
750 // If the context potentially accepts unbridged ARC casts, strip
751 // the unbridged cast and add it to the collection for later restoration.
752 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
753 unbridgedCasts) {
754 unbridgedCasts->save(S, E);
755 return false;
756 }
757
758 // Go ahead and check everything else.
759 ExprResult result = S.CheckPlaceholderExpr(E);
760 if (result.isInvalid())
761 return true;
762
763 E = result.take();
764 return false;
765 }
766
767 // Nothing to do.
768 return false;
769}
770
771/// checkArgPlaceholdersForOverload - Check a set of call operands for
772/// placeholders.
773static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
774 unsigned numArgs,
775 UnbridgedCastsSet &unbridged) {
776 for (unsigned i = 0; i != numArgs; ++i)
777 if (checkPlaceholderForOverload(S, args[i], &unbridged))
778 return true;
779
780 return false;
781}
782
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000783// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000784// overload of the declarations in Old. This routine returns false if
785// New and Old cannot be overloaded, e.g., if New has the same
786// signature as some function in Old (C++ 1.3.10) or if the Old
787// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000788// it does return false, MatchedDecl will point to the decl that New
789// cannot be overloaded with. This decl may be a UsingShadowDecl on
790// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000791//
792// Example: Given the following input:
793//
794// void f(int, float); // #1
795// void f(int, int); // #2
796// int f(int, int); // #3
797//
798// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000799// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000800//
John McCall3d988d92009-12-02 08:47:38 +0000801// When we process #2, Old contains only the FunctionDecl for #1. By
802// comparing the parameter types, we see that #1 and #2 are overloaded
803// (since they have different signatures), so this routine returns
804// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805//
John McCall3d988d92009-12-02 08:47:38 +0000806// When we process #3, Old is an overload set containing #1 and #2. We
807// compare the signatures of #3 to #1 (they're overloaded, so we do
808// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
809// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000810// signature), IsOverload returns false and MatchedDecl will be set to
811// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000812//
813// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
814// into a class by a using declaration. The rules for whether to hide
815// shadow declarations ignore some properties which otherwise figure
816// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000817Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000818Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
819 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000820 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000821 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000822 NamedDecl *OldD = *I;
823
824 bool OldIsUsingDecl = false;
825 if (isa<UsingShadowDecl>(OldD)) {
826 OldIsUsingDecl = true;
827
828 // We can always introduce two using declarations into the same
829 // context, even if they have identical signatures.
830 if (NewIsUsingDecl) continue;
831
832 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
833 }
834
835 // If either declaration was introduced by a using declaration,
836 // we'll need to use slightly different rules for matching.
837 // Essentially, these rules are the normal rules, except that
838 // function templates hide function templates with different
839 // return types or template parameter lists.
840 bool UseMemberUsingDeclRules =
841 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
842
John McCall3d988d92009-12-02 08:47:38 +0000843 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000844 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
845 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
846 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
847 continue;
848 }
849
John McCalldaa3d6b2009-12-09 03:35:25 +0000850 Match = *I;
851 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000852 }
John McCall3d988d92009-12-02 08:47:38 +0000853 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000854 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
855 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
856 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
857 continue;
858 }
859
John McCalldaa3d6b2009-12-09 03:35:25 +0000860 Match = *I;
861 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000862 }
John McCalla8987a2942010-11-10 03:01:53 +0000863 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000864 // We can overload with these, which can show up when doing
865 // redeclaration checks for UsingDecls.
866 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000867 } else if (isa<TagDecl>(OldD)) {
868 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000869 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
870 // Optimistically assume that an unresolved using decl will
871 // overload; if it doesn't, we'll have to diagnose during
872 // template instantiation.
873 } else {
John McCall1f82f242009-11-18 22:49:29 +0000874 // (C++ 13p1):
875 // Only function declarations can be overloaded; object and type
876 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000877 Match = *I;
878 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000879 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880 }
John McCall1f82f242009-11-18 22:49:29 +0000881
John McCalldaa3d6b2009-12-09 03:35:25 +0000882 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000883}
884
John McCalle9cccd82010-06-16 08:42:20 +0000885bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
886 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000887 // If both of the functions are extern "C", then they are not
888 // overloads.
889 if (Old->isExternC() && New->isExternC())
890 return false;
891
John McCall1f82f242009-11-18 22:49:29 +0000892 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
893 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
894
895 // C++ [temp.fct]p2:
896 // A function template can be overloaded with other function templates
897 // and with normal (non-template) functions.
898 if ((OldTemplate == 0) != (NewTemplate == 0))
899 return true;
900
901 // Is the function New an overload of the function Old?
902 QualType OldQType = Context.getCanonicalType(Old->getType());
903 QualType NewQType = Context.getCanonicalType(New->getType());
904
905 // Compare the signatures (C++ 1.3.10) of the two functions to
906 // determine whether they are overloads. If we find any mismatch
907 // in the signature, they are overloads.
908
909 // If either of these functions is a K&R-style function (no
910 // prototype), then we consider them to have matching signatures.
911 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
912 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
913 return false;
914
John McCall424cec92011-01-19 06:33:43 +0000915 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
916 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000917
918 // The signature of a function includes the types of its
919 // parameters (C++ 1.3.10), which includes the presence or absence
920 // of the ellipsis; see C++ DR 357).
921 if (OldQType != NewQType &&
922 (OldType->getNumArgs() != NewType->getNumArgs() ||
923 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000924 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000925 return true;
926
927 // C++ [temp.over.link]p4:
928 // The signature of a function template consists of its function
929 // signature, its return type and its template parameter list. The names
930 // of the template parameters are significant only for establishing the
931 // relationship between the template parameters and the rest of the
932 // signature.
933 //
934 // We check the return type and template parameter lists for function
935 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000936 //
937 // However, we don't consider either of these when deciding whether
938 // a member introduced by a shadow declaration is hidden.
939 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000940 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
941 OldTemplate->getTemplateParameters(),
942 false, TPL_TemplateMatch) ||
943 OldType->getResultType() != NewType->getResultType()))
944 return true;
945
946 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000947 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000948 //
949 // As part of this, also check whether one of the member functions
950 // is static, in which case they are not overloads (C++
951 // 13.1p2). While not part of the definition of the signature,
952 // this check is important to determine whether these functions
953 // can be overloaded.
954 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
955 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
956 if (OldMethod && NewMethod &&
957 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000958 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
960 if (!UseUsingDeclRules &&
961 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
962 (OldMethod->getRefQualifier() == RQ_None ||
963 NewMethod->getRefQualifier() == RQ_None)) {
964 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000965 // - Member function declarations with the same name and the same
966 // parameter-type-list as well as member function template
967 // declarations with the same name, the same parameter-type-list, and
968 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000969 // them, but not all, have a ref-qualifier (8.3.5).
970 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
971 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
972 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
John McCall1f82f242009-11-18 22:49:29 +0000975 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977
John McCall1f82f242009-11-18 22:49:29 +0000978 // The signatures match; this is not an overload.
979 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000980}
981
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000982/// \brief Checks availability of the function depending on the current
983/// function context. Inside an unavailable function, unavailability is ignored.
984///
985/// \returns true if \arg FD is unavailable and current context is inside
986/// an available function, false otherwise.
987bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
988 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
989}
990
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000991/// \brief Tries a user-defined conversion from From to ToType.
992///
993/// Produces an implicit conversion sequence for when a standard conversion
994/// is not an option. See TryImplicitConversion for more information.
995static ImplicitConversionSequence
996TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
997 bool SuppressUserConversions,
998 bool AllowExplicit,
999 bool InOverloadResolution,
1000 bool CStyle,
1001 bool AllowObjCWritebackConversion) {
1002 ImplicitConversionSequence ICS;
1003
1004 if (SuppressUserConversions) {
1005 // We're not in the case above, so there is no conversion that
1006 // we can perform.
1007 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1008 return ICS;
1009 }
1010
1011 // Attempt user-defined conversion.
1012 OverloadCandidateSet Conversions(From->getExprLoc());
1013 OverloadingResult UserDefResult
1014 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1015 AllowExplicit);
1016
1017 if (UserDefResult == OR_Success) {
1018 ICS.setUserDefined();
1019 // C++ [over.ics.user]p4:
1020 // A conversion of an expression of class type to the same class
1021 // type is given Exact Match rank, and a conversion of an
1022 // expression of class type to a base class of that type is
1023 // given Conversion rank, in spite of the fact that a copy
1024 // constructor (i.e., a user-defined conversion function) is
1025 // called for those cases.
1026 if (CXXConstructorDecl *Constructor
1027 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1028 QualType FromCanon
1029 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1030 QualType ToCanon
1031 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1032 if (Constructor->isCopyConstructor() &&
1033 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1034 // Turn this into a "standard" conversion sequence, so that it
1035 // gets ranked with standard conversion sequences.
1036 ICS.setStandard();
1037 ICS.Standard.setAsIdentityConversion();
1038 ICS.Standard.setFromType(From->getType());
1039 ICS.Standard.setAllToTypes(ToType);
1040 ICS.Standard.CopyConstructor = Constructor;
1041 if (ToCanon != FromCanon)
1042 ICS.Standard.Second = ICK_Derived_To_Base;
1043 }
1044 }
1045
1046 // C++ [over.best.ics]p4:
1047 // However, when considering the argument of a user-defined
1048 // conversion function that is a candidate by 13.3.1.3 when
1049 // invoked for the copying of the temporary in the second step
1050 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1051 // 13.3.1.6 in all cases, only standard conversion sequences and
1052 // ellipsis conversion sequences are allowed.
1053 if (SuppressUserConversions && ICS.isUserDefined()) {
1054 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1055 }
1056 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1057 ICS.setAmbiguous();
1058 ICS.Ambiguous.setFromType(From->getType());
1059 ICS.Ambiguous.setToType(ToType);
1060 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1061 Cand != Conversions.end(); ++Cand)
1062 if (Cand->Viable)
1063 ICS.Ambiguous.addConversion(Cand->Function);
1064 } else {
1065 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1066 }
1067
1068 return ICS;
1069}
1070
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001071/// TryImplicitConversion - Attempt to perform an implicit conversion
1072/// from the given expression (Expr) to the given type (ToType). This
1073/// function returns an implicit conversion sequence that can be used
1074/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001075///
1076/// void f(float f);
1077/// void g(int i) { f(i); }
1078///
1079/// this routine would produce an implicit conversion sequence to
1080/// describe the initialization of f from i, which will be a standard
1081/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1082/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1083//
1084/// Note that this routine only determines how the conversion can be
1085/// performed; it does not actually perform the conversion. As such,
1086/// it will not produce any diagnostics if no conversion is available,
1087/// but will instead return an implicit conversion sequence of kind
1088/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001089///
1090/// If @p SuppressUserConversions, then user-defined conversions are
1091/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001092/// If @p AllowExplicit, then explicit user-defined conversions are
1093/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001094///
1095/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1096/// writeback conversion, which allows __autoreleasing id* parameters to
1097/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001098static ImplicitConversionSequence
1099TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1100 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001102 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001103 bool CStyle,
1104 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001105 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001106 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001107 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001108 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001109 return ICS;
1110 }
1111
John McCall5c32be02010-08-24 20:38:10 +00001112 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001114 return ICS;
1115 }
1116
Douglas Gregor836a7e82010-08-11 02:15:33 +00001117 // C++ [over.ics.user]p4:
1118 // A conversion of an expression of class type to the same class
1119 // type is given Exact Match rank, and a conversion of an
1120 // expression of class type to a base class of that type is
1121 // given Conversion rank, in spite of the fact that a copy/move
1122 // constructor (i.e., a user-defined conversion function) is
1123 // called for those cases.
1124 QualType FromType = From->getType();
1125 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001126 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1127 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001128 ICS.setStandard();
1129 ICS.Standard.setAsIdentityConversion();
1130 ICS.Standard.setFromType(FromType);
1131 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregor5ab11652010-04-17 22:01:05 +00001133 // We don't actually check at this point whether there is a valid
1134 // copy/move constructor, since overloading just assumes that it
1135 // exists. When we actually perform initialization, we'll find the
1136 // appropriate constructor to copy the returned object, if needed.
1137 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregor5ab11652010-04-17 22:01:05 +00001139 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001140 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001141 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Douglas Gregor836a7e82010-08-11 02:15:33 +00001143 return ICS;
1144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001146 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1147 AllowExplicit, InOverloadResolution, CStyle,
1148 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001149}
1150
John McCall31168b02011-06-15 23:02:42 +00001151ImplicitConversionSequence
1152Sema::TryImplicitConversion(Expr *From, QualType ToType,
1153 bool SuppressUserConversions,
1154 bool AllowExplicit,
1155 bool InOverloadResolution,
1156 bool CStyle,
1157 bool AllowObjCWritebackConversion) {
1158 return clang::TryImplicitConversion(*this, From, ToType,
1159 SuppressUserConversions, AllowExplicit,
1160 InOverloadResolution, CStyle,
1161 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001162}
1163
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001164/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001165/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001166/// converted expression. Flavor is the kind of conversion we're
1167/// performing, used in the error message. If @p AllowExplicit,
1168/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001169ExprResult
1170Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001171 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001172 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001173 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001174}
1175
John Wiegley01296292011-04-08 18:41:53 +00001176ExprResult
1177Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001178 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001179 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001180 if (checkPlaceholderForOverload(*this, From))
1181 return ExprError();
1182
John McCall31168b02011-06-15 23:02:42 +00001183 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1184 bool AllowObjCWritebackConversion
1185 = getLangOptions().ObjCAutoRefCount &&
1186 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001187
John McCall5c32be02010-08-24 20:38:10 +00001188 ICS = clang::TryImplicitConversion(*this, From, ToType,
1189 /*SuppressUserConversions=*/false,
1190 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001191 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001192 /*CStyle=*/false,
1193 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001194 return PerformImplicitConversion(From, ToType, ICS, Action);
1195}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001196
1197/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001198/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001199bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1200 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001201 if (Context.hasSameUnqualifiedType(FromType, ToType))
1202 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203
John McCall991eb4b2010-12-21 00:44:39 +00001204 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1205 // where F adds one of the following at most once:
1206 // - a pointer
1207 // - a member pointer
1208 // - a block pointer
1209 CanQualType CanTo = Context.getCanonicalType(ToType);
1210 CanQualType CanFrom = Context.getCanonicalType(FromType);
1211 Type::TypeClass TyClass = CanTo->getTypeClass();
1212 if (TyClass != CanFrom->getTypeClass()) return false;
1213 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1214 if (TyClass == Type::Pointer) {
1215 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1216 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1217 } else if (TyClass == Type::BlockPointer) {
1218 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1219 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1220 } else if (TyClass == Type::MemberPointer) {
1221 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1223 } else {
1224 return false;
1225 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001226
John McCall991eb4b2010-12-21 00:44:39 +00001227 TyClass = CanTo->getTypeClass();
1228 if (TyClass != CanFrom->getTypeClass()) return false;
1229 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1230 return false;
1231 }
1232
1233 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1234 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1235 if (!EInfo.getNoReturn()) return false;
1236
1237 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1238 assert(QualType(FromFn, 0).isCanonical());
1239 if (QualType(FromFn, 0) != CanTo) return false;
1240
1241 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001242 return true;
1243}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
Douglas Gregor46188682010-05-18 22:42:18 +00001245/// \brief Determine whether the conversion from FromType to ToType is a valid
1246/// vector conversion.
1247///
1248/// \param ICK Will be set to the vector conversion kind, if this is a vector
1249/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1251 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001252 // We need at least one of these types to be a vector type to have a vector
1253 // conversion.
1254 if (!ToType->isVectorType() && !FromType->isVectorType())
1255 return false;
1256
1257 // Identical types require no conversions.
1258 if (Context.hasSameUnqualifiedType(FromType, ToType))
1259 return false;
1260
1261 // There are no conversions between extended vector types, only identity.
1262 if (ToType->isExtVectorType()) {
1263 // There are no conversions between extended vector types other than the
1264 // identity conversion.
1265 if (FromType->isExtVectorType())
1266 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001267
Douglas Gregor46188682010-05-18 22:42:18 +00001268 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001269 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001270 ICK = ICK_Vector_Splat;
1271 return true;
1272 }
1273 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001274
1275 // We can perform the conversion between vector types in the following cases:
1276 // 1)vector types are equivalent AltiVec and GCC vector types
1277 // 2)lax vector conversions are permitted and the vector types are of the
1278 // same size
1279 if (ToType->isVectorType() && FromType->isVectorType()) {
1280 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001281 (Context.getLangOptions().LaxVectorConversions &&
1282 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001283 ICK = ICK_Vector_Conversion;
1284 return true;
1285 }
Douglas Gregor46188682010-05-18 22:42:18 +00001286 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001287
Douglas Gregor46188682010-05-18 22:42:18 +00001288 return false;
1289}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001291/// IsStandardConversion - Determines whether there is a standard
1292/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1293/// expression From to the type ToType. Standard conversion sequences
1294/// only consider non-class types; for conversions that involve class
1295/// types, use TryImplicitConversion. If a conversion exists, SCS will
1296/// contain the standard conversion sequence required to perform this
1297/// conversion and this routine will return true. Otherwise, this
1298/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001299static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1300 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001301 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001302 bool CStyle,
1303 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001306 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001307 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001308 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001309 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001310 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001311 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001312
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001313 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001314 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001315 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001316 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001317 return false;
1318
Mike Stump11289f42009-09-09 15:08:12 +00001319 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001320 }
1321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 // The first conversion can be an lvalue-to-rvalue conversion,
1323 // array-to-pointer conversion, or function-to-pointer conversion
1324 // (C++ 4p1).
1325
John McCall5c32be02010-08-24 20:38:10 +00001326 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001327 DeclAccessPair AccessPair;
1328 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001330 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001331 // We were able to resolve the address of the overloaded function,
1332 // so we can convert to the type of that function.
1333 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001334
1335 // we can sometimes resolve &foo<int> regardless of ToType, so check
1336 // if the type matches (identity) or we are converting to bool
1337 if (!S.Context.hasSameUnqualifiedType(
1338 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1339 QualType resultTy;
1340 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001341 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001342 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1343 // otherwise, only a boolean conversion is standard
1344 if (!ToType->isBooleanType())
1345 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347
Chandler Carruthffce2452011-03-29 08:08:18 +00001348 // Check if the "from" expression is taking the address of an overloaded
1349 // function and recompute the FromType accordingly. Take advantage of the
1350 // fact that non-static member functions *must* have such an address-of
1351 // expression.
1352 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1353 if (Method && !Method->isStatic()) {
1354 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1355 "Non-unary operator on non-static member address");
1356 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1357 == UO_AddrOf &&
1358 "Non-address-of operator on non-static member address");
1359 const Type *ClassType
1360 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1361 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001362 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1363 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1364 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001365 "Non-address-of operator for overloaded function expression");
1366 FromType = S.Context.getPointerType(FromType);
1367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368
Douglas Gregor980fb162010-04-29 18:24:40 +00001369 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001370 assert(S.Context.hasSameType(
1371 FromType,
1372 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001373 } else {
1374 return false;
1375 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001376 }
John McCall154a2fd2011-08-30 00:57:29 +00001377 // Lvalue-to-rvalue conversion (C++11 4.1):
1378 // A glvalue (3.10) of a non-function, non-array type T can
1379 // be converted to a prvalue.
1380 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001381 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001382 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001383 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001384 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385
1386 // If T is a non-class type, the type of the rvalue is the
1387 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001388 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1389 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001390 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001391 } else if (FromType->isArrayType()) {
1392 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001393 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001394
1395 // An lvalue or rvalue of type "array of N T" or "array of unknown
1396 // bound of T" can be converted to an rvalue of type "pointer to
1397 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001398 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399
John McCall5c32be02010-08-24 20:38:10 +00001400 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001401 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001402 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001403
1404 // For the purpose of ranking in overload resolution
1405 // (13.3.3.1.1), this conversion is considered an
1406 // array-to-pointer conversion followed by a qualification
1407 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001408 SCS.Second = ICK_Identity;
1409 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001410 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001411 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001412 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001413 }
John McCall086a4642010-11-24 05:12:34 +00001414 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001415 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001416 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001417
1418 // An lvalue of function type T can be converted to an rvalue of
1419 // type "pointer to T." The result is a pointer to the
1420 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001421 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001422 } else {
1423 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001424 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001426 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001427
1428 // The second conversion can be an integral promotion, floating
1429 // point promotion, integral conversion, floating point conversion,
1430 // floating-integral conversion, pointer conversion,
1431 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001432 // For overloading in C, this can also be a "compatible-type"
1433 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001434 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001435 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001436 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001437 // The unqualified versions of the types are the same: there's no
1438 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001439 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001440 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001441 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001442 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001444 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001445 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001446 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001447 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001448 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001449 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001450 SCS.Second = ICK_Complex_Promotion;
1451 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001452 } else if (ToType->isBooleanType() &&
1453 (FromType->isArithmeticType() ||
1454 FromType->isAnyPointerType() ||
1455 FromType->isBlockPointerType() ||
1456 FromType->isMemberPointerType() ||
1457 FromType->isNullPtrType())) {
1458 // Boolean conversions (C++ 4.12).
1459 SCS.Second = ICK_Boolean_Conversion;
1460 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001461 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001462 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001463 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001464 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001465 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001466 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001467 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001468 SCS.Second = ICK_Complex_Conversion;
1469 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001470 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1471 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001472 // Complex-real conversions (C99 6.3.1.7)
1473 SCS.Second = ICK_Complex_Real;
1474 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001475 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001476 // Floating point conversions (C++ 4.8).
1477 SCS.Second = ICK_Floating_Conversion;
1478 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001480 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001481 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001482 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001483 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001486 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001487 SCS.Second = ICK_Block_Pointer_Conversion;
1488 } else if (AllowObjCWritebackConversion &&
1489 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1490 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001491 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1492 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001493 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001494 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001495 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001496 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001497 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001498 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001499 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001500 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001501 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001502 SCS.Second = SecondICK;
1503 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001504 } else if (!S.getLangOptions().CPlusPlus &&
1505 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001506 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001507 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001508 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001509 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001510 // Treat a conversion that strips "noreturn" as an identity conversion.
1511 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001512 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1513 InOverloadResolution,
1514 SCS, CStyle)) {
1515 SCS.Second = ICK_TransparentUnionConversion;
1516 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001517 } else {
1518 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001521 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001523 QualType CanonFrom;
1524 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001525 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001526 bool ObjCLifetimeConversion;
1527 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1528 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001530 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001532 CanonFrom = S.Context.getCanonicalType(FromType);
1533 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534 } else {
1535 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.Third = ICK_Identity;
1537
Mike Stump11289f42009-09-09 15:08:12 +00001538 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 // [...] Any difference in top-level cv-qualification is
1540 // subsumed by the initialization itself and does not constitute
1541 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001542 CanonFrom = S.Context.getCanonicalType(FromType);
1543 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001544 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001545 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001546 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001547 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1548 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001549 FromType = ToType;
1550 CanonFrom = CanonTo;
1551 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001553 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554
1555 // If we have not converted the argument type to the parameter type,
1556 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001557 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001562
1563static bool
1564IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1565 QualType &ToType,
1566 bool InOverloadResolution,
1567 StandardConversionSequence &SCS,
1568 bool CStyle) {
1569
1570 const RecordType *UT = ToType->getAsUnionType();
1571 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1572 return false;
1573 // The field to initialize within the transparent union.
1574 RecordDecl *UD = UT->getDecl();
1575 // It's compatible if the expression matches any of the fields.
1576 for (RecordDecl::field_iterator it = UD->field_begin(),
1577 itend = UD->field_end();
1578 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001579 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1580 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001581 ToType = it->getType();
1582 return true;
1583 }
1584 }
1585 return false;
1586}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587
1588/// IsIntegralPromotion - Determines whether the conversion from the
1589/// expression From (whose potentially-adjusted type is FromType) to
1590/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1591/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001592bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001593 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001594 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001595 if (!To) {
1596 return false;
1597 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001598
1599 // An rvalue of type char, signed char, unsigned char, short int, or
1600 // unsigned short int can be converted to an rvalue of type int if
1601 // int can represent all the values of the source type; otherwise,
1602 // the source rvalue can be converted to an rvalue of type unsigned
1603 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1605 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001606 if (// We can promote any signed, promotable integer type to an int
1607 (FromType->isSignedIntegerType() ||
1608 // We can promote any unsigned integer type whose size is
1609 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001610 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001611 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001613 }
1614
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 return To->getKind() == BuiltinType::UInt;
1616 }
1617
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001618 // C++0x [conv.prom]p3:
1619 // A prvalue of an unscoped enumeration type whose underlying type is not
1620 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1621 // following types that can represent all the values of the enumeration
1622 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1623 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001624 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001625 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001626 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627 // with lowest integer conversion rank (4.13) greater than the rank of long
1628 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001629 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001630 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1631 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1632 // provided for a scoped enumeration.
1633 if (FromEnumType->getDecl()->isScoped())
1634 return false;
1635
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001636 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001638 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001639 return Context.hasSameUnqualifiedType(ToType,
1640 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001641 }
John McCall56774992009-12-09 09:09:27 +00001642
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001643 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001644 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1645 // to an rvalue a prvalue of the first of the following types that can
1646 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001647 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001651 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001653 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 // Determine whether the type we're converting from is signed or
1655 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001656 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 // The types we'll try to promote to, in the appropriate
1660 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001661 QualType PromoteTypes[6] = {
1662 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001663 Context.LongTy, Context.UnsignedLongTy ,
1664 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001666 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1668 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001669 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1671 // We found the type that we can promote to. If this is the
1672 // type we wanted, we have a promotion. Otherwise, no
1673 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001674 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 }
1676 }
1677 }
1678
1679 // An rvalue for an integral bit-field (9.6) can be converted to an
1680 // rvalue of type int if int can represent all the values of the
1681 // bit-field; otherwise, it can be converted to unsigned int if
1682 // unsigned int can represent all the values of the bit-field. If
1683 // the bit-field is larger yet, no integral promotion applies to
1684 // it. If the bit-field has an enumerated type, it is treated as any
1685 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001686 // FIXME: We should delay checking of bit-fields until we actually perform the
1687 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001688 using llvm::APSInt;
1689 if (From)
1690 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001691 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001692 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001693 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1694 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1695 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001696
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001697 // Are we promoting to an int from a bitfield that fits in an int?
1698 if (BitWidth < ToSize ||
1699 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1700 return To->getKind() == BuiltinType::Int;
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001703 // Are we promoting to an unsigned int from an unsigned bitfield
1704 // that fits into an unsigned int?
1705 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1706 return To->getKind() == BuiltinType::UInt;
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001709 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001710 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 // An rvalue of type bool can be converted to an rvalue of type int,
1714 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001715 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001717 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718
1719 return false;
1720}
1721
1722/// IsFloatingPointPromotion - Determines whether the conversion from
1723/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1724/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001725bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001726 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1727 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001728 /// An rvalue of type float can be converted to an rvalue of type
1729 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 if (FromBuiltin->getKind() == BuiltinType::Float &&
1731 ToBuiltin->getKind() == BuiltinType::Double)
1732 return true;
1733
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001734 // C99 6.3.1.5p1:
1735 // When a float is promoted to double or long double, or a
1736 // double is promoted to long double [...].
1737 if (!getLangOptions().CPlusPlus &&
1738 (FromBuiltin->getKind() == BuiltinType::Float ||
1739 FromBuiltin->getKind() == BuiltinType::Double) &&
1740 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1741 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001742
1743 // Half can be promoted to float.
1744 if (FromBuiltin->getKind() == BuiltinType::Half &&
1745 ToBuiltin->getKind() == BuiltinType::Float)
1746 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001747 }
1748
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749 return false;
1750}
1751
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001752/// \brief Determine if a conversion is a complex promotion.
1753///
1754/// A complex promotion is defined as a complex -> complex conversion
1755/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001756/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001757bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001758 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001759 if (!FromComplex)
1760 return false;
1761
John McCall9dd450b2009-09-21 23:43:11 +00001762 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001763 if (!ToComplex)
1764 return false;
1765
1766 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001767 ToComplex->getElementType()) ||
1768 IsIntegralPromotion(0, FromComplex->getElementType(),
1769 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001770}
1771
Douglas Gregor237f96c2008-11-26 23:31:11 +00001772/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1773/// the pointer type FromPtr to a pointer to type ToPointee, with the
1774/// same type qualifiers as FromPtr has on its pointee type. ToType,
1775/// if non-empty, will be a pointer to ToType that may or may not have
1776/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001777///
Mike Stump11289f42009-09-09 15:08:12 +00001778static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001779BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001780 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001781 ASTContext &Context,
1782 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001783 assert((FromPtr->getTypeClass() == Type::Pointer ||
1784 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1785 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
John McCall31168b02011-06-15 23:02:42 +00001787 /// Conversions to 'id' subsume cv-qualifier conversions.
1788 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001789 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001790
1791 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001792 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001793 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001794 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001795
John McCall31168b02011-06-15 23:02:42 +00001796 if (StripObjCLifetime)
1797 Quals.removeObjCLifetime();
1798
Mike Stump11289f42009-09-09 15:08:12 +00001799 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001800 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001801 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001802 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001803 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001804
1805 // Build a pointer to ToPointee. It has the right qualifiers
1806 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001807 if (isa<ObjCObjectPointerType>(ToType))
1808 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001809 return Context.getPointerType(ToPointee);
1810 }
1811
1812 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001813 QualType QualifiedCanonToPointee
1814 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001816 if (isa<ObjCObjectPointerType>(ToType))
1817 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1818 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001819}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820
Mike Stump11289f42009-09-09 15:08:12 +00001821static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001822 bool InOverloadResolution,
1823 ASTContext &Context) {
1824 // Handle value-dependent integral null pointer constants correctly.
1825 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1826 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001827 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001828 return !InOverloadResolution;
1829
Douglas Gregor56751b52009-09-25 04:25:58 +00001830 return Expr->isNullPointerConstant(Context,
1831 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1832 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001833}
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001835/// IsPointerConversion - Determines whether the conversion of the
1836/// expression From, which has the (possibly adjusted) type FromType,
1837/// can be converted to the type ToType via a pointer conversion (C++
1838/// 4.10). If so, returns true and places the converted type (that
1839/// might differ from ToType in its cv-qualifiers at some level) into
1840/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001841///
Douglas Gregora29dc052008-11-27 01:19:21 +00001842/// This routine also supports conversions to and from block pointers
1843/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1844/// pointers to interfaces. FIXME: Once we've determined the
1845/// appropriate overloading rules for Objective-C, we may want to
1846/// split the Objective-C checks into a different routine; however,
1847/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001848/// conversions, so for now they live here. IncompatibleObjC will be
1849/// set if the conversion is an allowed Objective-C conversion that
1850/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001851bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001852 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001853 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001854 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001855 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001856 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1857 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001858 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001859
Mike Stump11289f42009-09-09 15:08:12 +00001860 // Conversion from a null pointer constant to any Objective-C pointer type.
1861 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001862 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001863 ConvertedType = ToType;
1864 return true;
1865 }
1866
Douglas Gregor231d1c62008-11-27 00:15:41 +00001867 // Blocks: Block pointers can be converted to void*.
1868 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001869 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001870 ConvertedType = ToType;
1871 return true;
1872 }
1873 // Blocks: A null pointer constant can be converted to a block
1874 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001875 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001876 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001877 ConvertedType = ToType;
1878 return true;
1879 }
1880
Sebastian Redl576fd422009-05-10 18:38:11 +00001881 // If the left-hand-side is nullptr_t, the right side can be a null
1882 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001883 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001889 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001890 if (!ToTypePtr)
1891 return false;
1892
1893 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001894 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001895 ConvertedType = ToType;
1896 return true;
1897 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001898
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001900 // , including objective-c pointers.
1901 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001902 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1903 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001904 ConvertedType = BuildSimilarlyQualifiedPointerType(
1905 FromType->getAs<ObjCObjectPointerType>(),
1906 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001907 ToType, Context);
1908 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001909 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001910 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001911 if (!FromTypePtr)
1912 return false;
1913
1914 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001916 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001917 // pointer conversion, so don't do all of the work below.
1918 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1919 return false;
1920
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001921 // An rvalue of type "pointer to cv T," where T is an object type,
1922 // can be converted to an rvalue of type "pointer to cv void" (C++
1923 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001924 if (FromPointeeType->isIncompleteOrObjectType() &&
1925 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001927 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001928 ToType, Context,
1929 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930 return true;
1931 }
1932
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001933 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001934 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001935 ToPointeeType->isVoidType()) {
1936 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1937 ToPointeeType,
1938 ToType, Context);
1939 return true;
1940 }
1941
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001942 // When we're overloading in C, we allow a special kind of pointer
1943 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001944 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001945 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001946 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001947 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001948 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001949 return true;
1950 }
1951
Douglas Gregor5c407d92008-10-23 00:40:37 +00001952 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001953 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001954 // An rvalue of type "pointer to cv D," where D is a class type,
1955 // can be converted to an rvalue of type "pointer to cv B," where
1956 // B is a base class (clause 10) of D. If B is an inaccessible
1957 // (clause 11) or ambiguous (10.2) base class of D, a program that
1958 // necessitates this conversion is ill-formed. The result of the
1959 // conversion is a pointer to the base class sub-object of the
1960 // derived class object. The null pointer value is converted to
1961 // the null pointer value of the destination type.
1962 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001963 // Note that we do not check for ambiguity or inaccessibility
1964 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001965 if (getLangOptions().CPlusPlus &&
1966 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001967 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001968 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001969 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001970 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001971 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001972 ToType, Context);
1973 return true;
1974 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001975
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001976 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1977 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1978 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1979 ToPointeeType,
1980 ToType, Context);
1981 return true;
1982 }
1983
Douglas Gregora119f102008-12-19 19:13:09 +00001984 return false;
1985}
Douglas Gregoraec25842011-04-26 23:16:46 +00001986
1987/// \brief Adopt the given qualifiers for the given type.
1988static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1989 Qualifiers TQs = T.getQualifiers();
1990
1991 // Check whether qualifiers already match.
1992 if (TQs == Qs)
1993 return T;
1994
1995 if (Qs.compatiblyIncludes(TQs))
1996 return Context.getQualifiedType(T, Qs);
1997
1998 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1999}
Douglas Gregora119f102008-12-19 19:13:09 +00002000
2001/// isObjCPointerConversion - Determines whether this is an
2002/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2003/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002004bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002005 QualType& ConvertedType,
2006 bool &IncompatibleObjC) {
2007 if (!getLangOptions().ObjC1)
2008 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
Douglas Gregoraec25842011-04-26 23:16:46 +00002010 // The set of qualifiers on the type we're converting from.
2011 Qualifiers FromQualifiers = FromType.getQualifiers();
2012
Steve Naroff7cae42b2009-07-10 23:34:53 +00002013 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002014 const ObjCObjectPointerType* ToObjCPtr =
2015 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002016 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002017 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002018
Steve Naroff7cae42b2009-07-10 23:34:53 +00002019 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002020 // If the pointee types are the same (ignoring qualifications),
2021 // then this is not a pointer conversion.
2022 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2023 FromObjCPtr->getPointeeType()))
2024 return false;
2025
Douglas Gregoraec25842011-04-26 23:16:46 +00002026 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002027 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002028 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002029 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002030 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002031 return true;
2032 }
2033 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002034 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002035 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002036 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002037 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002038 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002039 return true;
2040 }
2041 // Objective C++: We're able to convert from a pointer to an
2042 // interface to a pointer to a different interface.
2043 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002044 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2045 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2046 if (getLangOptions().CPlusPlus && LHS && RHS &&
2047 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2048 FromObjCPtr->getPointeeType()))
2049 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002051 ToObjCPtr->getPointeeType(),
2052 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002053 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002054 return true;
2055 }
2056
2057 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2058 // Okay: this is some kind of implicit downcast of Objective-C
2059 // interfaces, which is permitted. However, we're going to
2060 // complain about it.
2061 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002062 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002063 ToObjCPtr->getPointeeType(),
2064 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002065 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002066 return true;
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002069 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002070 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002071 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002072 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002074 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002075 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002076 // to a block pointer type.
2077 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002078 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002079 return true;
2080 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002081 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002084 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002086 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002088 return true;
2089 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002090 else
Douglas Gregora119f102008-12-19 19:13:09 +00002091 return false;
2092
Douglas Gregor033f56d2008-12-23 00:53:59 +00002093 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002094 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002095 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002096 else if (const BlockPointerType *FromBlockPtr =
2097 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002098 FromPointeeType = FromBlockPtr->getPointeeType();
2099 else
Douglas Gregora119f102008-12-19 19:13:09 +00002100 return false;
2101
Douglas Gregora119f102008-12-19 19:13:09 +00002102 // If we have pointers to pointers, recursively check whether this
2103 // is an Objective-C conversion.
2104 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2105 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2106 IncompatibleObjC)) {
2107 // We always complain about this conversion.
2108 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002109 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002110 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002111 return true;
2112 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002113 // Allow conversion of pointee being objective-c pointer to another one;
2114 // as in I* to id.
2115 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2116 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2117 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2118 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002119
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002120 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002121 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002122 return true;
2123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregor033f56d2008-12-23 00:53:59 +00002125 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002126 // differences in the argument and result types are in Objective-C
2127 // pointer conversions. If so, we permit the conversion (but
2128 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002129 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002130 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002132 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002133 if (FromFunctionType && ToFunctionType) {
2134 // If the function types are exactly the same, this isn't an
2135 // Objective-C pointer conversion.
2136 if (Context.getCanonicalType(FromPointeeType)
2137 == Context.getCanonicalType(ToPointeeType))
2138 return false;
2139
2140 // Perform the quick checks that will tell us whether these
2141 // function types are obviously different.
2142 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2143 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2144 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2145 return false;
2146
2147 bool HasObjCConversion = false;
2148 if (Context.getCanonicalType(FromFunctionType->getResultType())
2149 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2150 // Okay, the types match exactly. Nothing to do.
2151 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2152 ToFunctionType->getResultType(),
2153 ConvertedType, IncompatibleObjC)) {
2154 // Okay, we have an Objective-C pointer conversion.
2155 HasObjCConversion = true;
2156 } else {
2157 // Function types are too different. Abort.
2158 return false;
2159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregora119f102008-12-19 19:13:09 +00002161 // Check argument types.
2162 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2163 ArgIdx != NumArgs; ++ArgIdx) {
2164 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2165 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2166 if (Context.getCanonicalType(FromArgType)
2167 == Context.getCanonicalType(ToArgType)) {
2168 // Okay, the types match exactly. Nothing to do.
2169 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2170 ConvertedType, IncompatibleObjC)) {
2171 // Okay, we have an Objective-C pointer conversion.
2172 HasObjCConversion = true;
2173 } else {
2174 // Argument types are too different. Abort.
2175 return false;
2176 }
2177 }
2178
2179 if (HasObjCConversion) {
2180 // We had an Objective-C conversion. Allow this pointer
2181 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002182 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002183 IncompatibleObjC = true;
2184 return true;
2185 }
2186 }
2187
Sebastian Redl72b597d2009-01-25 19:43:20 +00002188 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002189}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002190
John McCall31168b02011-06-15 23:02:42 +00002191/// \brief Determine whether this is an Objective-C writeback conversion,
2192/// used for parameter passing when performing automatic reference counting.
2193///
2194/// \param FromType The type we're converting form.
2195///
2196/// \param ToType The type we're converting to.
2197///
2198/// \param ConvertedType The type that will be produced after applying
2199/// this conversion.
2200bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2201 QualType &ConvertedType) {
2202 if (!getLangOptions().ObjCAutoRefCount ||
2203 Context.hasSameUnqualifiedType(FromType, ToType))
2204 return false;
2205
2206 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2207 QualType ToPointee;
2208 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2209 ToPointee = ToPointer->getPointeeType();
2210 else
2211 return false;
2212
2213 Qualifiers ToQuals = ToPointee.getQualifiers();
2214 if (!ToPointee->isObjCLifetimeType() ||
2215 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002216 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002217 return false;
2218
2219 // Argument must be a pointer to __strong to __weak.
2220 QualType FromPointee;
2221 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2222 FromPointee = FromPointer->getPointeeType();
2223 else
2224 return false;
2225
2226 Qualifiers FromQuals = FromPointee.getQualifiers();
2227 if (!FromPointee->isObjCLifetimeType() ||
2228 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2229 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2230 return false;
2231
2232 // Make sure that we have compatible qualifiers.
2233 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2234 if (!ToQuals.compatiblyIncludes(FromQuals))
2235 return false;
2236
2237 // Remove qualifiers from the pointee type we're converting from; they
2238 // aren't used in the compatibility check belong, and we'll be adding back
2239 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2240 FromPointee = FromPointee.getUnqualifiedType();
2241
2242 // The unqualified form of the pointee types must be compatible.
2243 ToPointee = ToPointee.getUnqualifiedType();
2244 bool IncompatibleObjC;
2245 if (Context.typesAreCompatible(FromPointee, ToPointee))
2246 FromPointee = ToPointee;
2247 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2248 IncompatibleObjC))
2249 return false;
2250
2251 /// \brief Construct the type we're converting to, which is a pointer to
2252 /// __autoreleasing pointee.
2253 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2254 ConvertedType = Context.getPointerType(FromPointee);
2255 return true;
2256}
2257
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002258bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2259 QualType& ConvertedType) {
2260 QualType ToPointeeType;
2261 if (const BlockPointerType *ToBlockPtr =
2262 ToType->getAs<BlockPointerType>())
2263 ToPointeeType = ToBlockPtr->getPointeeType();
2264 else
2265 return false;
2266
2267 QualType FromPointeeType;
2268 if (const BlockPointerType *FromBlockPtr =
2269 FromType->getAs<BlockPointerType>())
2270 FromPointeeType = FromBlockPtr->getPointeeType();
2271 else
2272 return false;
2273 // We have pointer to blocks, check whether the only
2274 // differences in the argument and result types are in Objective-C
2275 // pointer conversions. If so, we permit the conversion.
2276
2277 const FunctionProtoType *FromFunctionType
2278 = FromPointeeType->getAs<FunctionProtoType>();
2279 const FunctionProtoType *ToFunctionType
2280 = ToPointeeType->getAs<FunctionProtoType>();
2281
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002282 if (!FromFunctionType || !ToFunctionType)
2283 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002284
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002285 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002286 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002287
2288 // Perform the quick checks that will tell us whether these
2289 // function types are obviously different.
2290 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2291 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2292 return false;
2293
2294 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2295 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2296 if (FromEInfo != ToEInfo)
2297 return false;
2298
2299 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002300 if (Context.hasSameType(FromFunctionType->getResultType(),
2301 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002302 // Okay, the types match exactly. Nothing to do.
2303 } else {
2304 QualType RHS = FromFunctionType->getResultType();
2305 QualType LHS = ToFunctionType->getResultType();
2306 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2307 !RHS.hasQualifiers() && LHS.hasQualifiers())
2308 LHS = LHS.getUnqualifiedType();
2309
2310 if (Context.hasSameType(RHS,LHS)) {
2311 // OK exact match.
2312 } else if (isObjCPointerConversion(RHS, LHS,
2313 ConvertedType, IncompatibleObjC)) {
2314 if (IncompatibleObjC)
2315 return false;
2316 // Okay, we have an Objective-C pointer conversion.
2317 }
2318 else
2319 return false;
2320 }
2321
2322 // Check argument types.
2323 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2324 ArgIdx != NumArgs; ++ArgIdx) {
2325 IncompatibleObjC = false;
2326 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2327 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2328 if (Context.hasSameType(FromArgType, ToArgType)) {
2329 // Okay, the types match exactly. Nothing to do.
2330 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2331 ConvertedType, IncompatibleObjC)) {
2332 if (IncompatibleObjC)
2333 return false;
2334 // Okay, we have an Objective-C pointer conversion.
2335 } else
2336 // Argument types are too different. Abort.
2337 return false;
2338 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002339 if (LangOpts.ObjCAutoRefCount &&
2340 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2341 ToFunctionType))
2342 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002343
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002344 ConvertedType = ToType;
2345 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002346}
2347
Richard Trieucaff2472011-11-23 22:32:32 +00002348enum {
2349 ft_default,
2350 ft_different_class,
2351 ft_parameter_arity,
2352 ft_parameter_mismatch,
2353 ft_return_type,
2354 ft_qualifer_mismatch
2355};
2356
2357/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2358/// function types. Catches different number of parameter, mismatch in
2359/// parameter types, and different return types.
2360void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2361 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002362 // If either type is not valid, include no extra info.
2363 if (FromType.isNull() || ToType.isNull()) {
2364 PDiag << ft_default;
2365 return;
2366 }
2367
Richard Trieucaff2472011-11-23 22:32:32 +00002368 // Get the function type from the pointers.
2369 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2370 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2371 *ToMember = ToType->getAs<MemberPointerType>();
2372 if (FromMember->getClass() != ToMember->getClass()) {
2373 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2374 << QualType(FromMember->getClass(), 0);
2375 return;
2376 }
2377 FromType = FromMember->getPointeeType();
2378 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002379 }
2380
Richard Trieu96ed5b62011-12-13 23:19:45 +00002381 if (FromType->isPointerType())
2382 FromType = FromType->getPointeeType();
2383 if (ToType->isPointerType())
2384 ToType = ToType->getPointeeType();
2385
2386 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002387 FromType = FromType.getNonReferenceType();
2388 ToType = ToType.getNonReferenceType();
2389
Richard Trieucaff2472011-11-23 22:32:32 +00002390 // Don't print extra info for non-specialized template functions.
2391 if (FromType->isInstantiationDependentType() &&
2392 !FromType->getAs<TemplateSpecializationType>()) {
2393 PDiag << ft_default;
2394 return;
2395 }
2396
Richard Trieu96ed5b62011-12-13 23:19:45 +00002397 // No extra info for same types.
2398 if (Context.hasSameType(FromType, ToType)) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieucaff2472011-11-23 22:32:32 +00002403 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2404 *ToFunction = ToType->getAs<FunctionProtoType>();
2405
2406 // Both types need to be function types.
2407 if (!FromFunction || !ToFunction) {
2408 PDiag << ft_default;
2409 return;
2410 }
2411
2412 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2413 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2414 << FromFunction->getNumArgs();
2415 return;
2416 }
2417
2418 // Handle different parameter types.
2419 unsigned ArgPos;
2420 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2421 PDiag << ft_parameter_mismatch << ArgPos + 1
2422 << ToFunction->getArgType(ArgPos)
2423 << FromFunction->getArgType(ArgPos);
2424 return;
2425 }
2426
2427 // Handle different return type.
2428 if (!Context.hasSameType(FromFunction->getResultType(),
2429 ToFunction->getResultType())) {
2430 PDiag << ft_return_type << ToFunction->getResultType()
2431 << FromFunction->getResultType();
2432 return;
2433 }
2434
2435 unsigned FromQuals = FromFunction->getTypeQuals(),
2436 ToQuals = ToFunction->getTypeQuals();
2437 if (FromQuals != ToQuals) {
2438 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2439 return;
2440 }
2441
2442 // Unable to find a difference, so add no extra info.
2443 PDiag << ft_default;
2444}
2445
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002446/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002447/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002448/// they have same number of arguments. This routine assumes that Objective-C
2449/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002450/// If the parameters are different, ArgPos will have the the parameter index
2451/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002453 const FunctionProtoType *NewType,
2454 unsigned *ArgPos) {
2455 if (!getLangOptions().ObjC1) {
2456 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2457 N = NewType->arg_type_begin(),
2458 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2459 if (!Context.hasSameType(*O, *N)) {
2460 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2461 return false;
2462 }
2463 }
2464 return true;
2465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002467 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2468 N = NewType->arg_type_begin(),
2469 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2470 QualType ToType = (*O);
2471 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002472 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002473 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2474 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002475 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2477 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2478 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002479 continue;
2480 }
John McCall8b07ec22010-05-15 11:32:37 +00002481 else if (const ObjCObjectPointerType *PTTo =
2482 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002483 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002484 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002485 if (Context.hasSameUnqualifiedType(
2486 PTTo->getObjectType()->getBaseType(),
2487 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002488 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002489 }
Richard Trieucaff2472011-11-23 22:32:32 +00002490 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002492 }
2493 }
2494 return true;
2495}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002496
Douglas Gregor39c16d42008-10-24 04:54:22 +00002497/// CheckPointerConversion - Check the pointer conversion from the
2498/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002499/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002500/// conversions for which IsPointerConversion has already returned
2501/// true. It returns true and produces a diagnostic if there was an
2502/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002503bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002504 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002505 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002506 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002507 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002508 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002509
John McCall8cb679e2010-11-15 09:13:47 +00002510 Kind = CK_BitCast;
2511
Chandler Carruthffab8732011-04-09 07:32:05 +00002512 if (!IsCStyleOrFunctionalCast &&
2513 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2514 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2515 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002516 PDiag(diag::warn_impcast_bool_to_null_pointer)
2517 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002518
John McCall9320b872011-09-09 05:25:32 +00002519 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2520 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002521 QualType FromPointeeType = FromPtrType->getPointeeType(),
2522 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002523
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002524 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2525 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002526 // We must have a derived-to-base conversion. Check an
2527 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002528 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2529 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002530 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002531 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002532 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002534 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002535 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002536 }
2537 }
John McCall9320b872011-09-09 05:25:32 +00002538 } else if (const ObjCObjectPointerType *ToPtrType =
2539 ToType->getAs<ObjCObjectPointerType>()) {
2540 if (const ObjCObjectPointerType *FromPtrType =
2541 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002542 // Objective-C++ conversions are always okay.
2543 // FIXME: We should have a different class of conversions for the
2544 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002545 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002546 return false;
John McCall9320b872011-09-09 05:25:32 +00002547 } else if (FromType->isBlockPointerType()) {
2548 Kind = CK_BlockPointerToObjCPointerCast;
2549 } else {
2550 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002551 }
John McCall9320b872011-09-09 05:25:32 +00002552 } else if (ToType->isBlockPointerType()) {
2553 if (!FromType->isBlockPointerType())
2554 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002555 }
John McCall8cb679e2010-11-15 09:13:47 +00002556
2557 // We shouldn't fall into this case unless it's valid for other
2558 // reasons.
2559 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2560 Kind = CK_NullToPointer;
2561
Douglas Gregor39c16d42008-10-24 04:54:22 +00002562 return false;
2563}
2564
Sebastian Redl72b597d2009-01-25 19:43:20 +00002565/// IsMemberPointerConversion - Determines whether the conversion of the
2566/// expression From, which has the (possibly adjusted) type FromType, can be
2567/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2568/// If so, returns true and places the converted type (that might differ from
2569/// ToType in its cv-qualifiers at some level) into ConvertedType.
2570bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002571 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002572 bool InOverloadResolution,
2573 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002574 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002575 if (!ToTypePtr)
2576 return false;
2577
2578 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002579 if (From->isNullPointerConstant(Context,
2580 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2581 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002582 ConvertedType = ToType;
2583 return true;
2584 }
2585
2586 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002587 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002588 if (!FromTypePtr)
2589 return false;
2590
2591 // A pointer to member of B can be converted to a pointer to member of D,
2592 // where D is derived from B (C++ 4.11p2).
2593 QualType FromClass(FromTypePtr->getClass(), 0);
2594 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002595
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002596 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2597 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2598 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002599 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2600 ToClass.getTypePtr());
2601 return true;
2602 }
2603
2604 return false;
2605}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606
Sebastian Redl72b597d2009-01-25 19:43:20 +00002607/// CheckMemberPointerConversion - Check the member pointer conversion from the
2608/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002609/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002610/// for which IsMemberPointerConversion has already returned true. It returns
2611/// true and produces a diagnostic if there was an error, or returns false
2612/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002613bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002614 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002615 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002616 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002617 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002618 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002619 if (!FromPtrType) {
2620 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002621 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002622 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002623 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002624 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002625 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002626 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002627
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002628 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002629 assert(ToPtrType && "No member pointer cast has a target type "
2630 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002631
Sebastian Redled8f2002009-01-28 18:33:18 +00002632 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2633 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002634
Sebastian Redled8f2002009-01-28 18:33:18 +00002635 // FIXME: What about dependent types?
2636 assert(FromClass->isRecordType() && "Pointer into non-class.");
2637 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002638
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002639 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002640 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002641 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2642 assert(DerivationOkay &&
2643 "Should not have been called if derivation isn't OK.");
2644 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002645
Sebastian Redled8f2002009-01-28 18:33:18 +00002646 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2647 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002648 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2649 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2650 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2651 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002652 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002653
Douglas Gregor89ee6822009-02-28 01:32:25 +00002654 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002655 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2656 << FromClass << ToClass << QualType(VBase, 0)
2657 << From->getSourceRange();
2658 return true;
2659 }
2660
John McCall5b0829a2010-02-10 09:31:12 +00002661 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002662 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2663 Paths.front(),
2664 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002665
Anders Carlssond7923c62009-08-22 23:33:40 +00002666 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002667 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002668 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002669 return false;
2670}
2671
Douglas Gregor9a657932008-10-21 23:43:52 +00002672/// IsQualificationConversion - Determines whether the conversion from
2673/// an rvalue of type FromType to ToType is a qualification conversion
2674/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002675///
2676/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2677/// when the qualification conversion involves a change in the Objective-C
2678/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002679bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002681 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002682 FromType = Context.getCanonicalType(FromType);
2683 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002684 ObjCLifetimeConversion = false;
2685
Douglas Gregor9a657932008-10-21 23:43:52 +00002686 // If FromType and ToType are the same type, this is not a
2687 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002688 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002689 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002690
Douglas Gregor9a657932008-10-21 23:43:52 +00002691 // (C++ 4.4p4):
2692 // A conversion can add cv-qualifiers at levels other than the first
2693 // in multi-level pointers, subject to the following rules: [...]
2694 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002696 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002697 // Within each iteration of the loop, we check the qualifiers to
2698 // determine if this still looks like a qualification
2699 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002700 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002701 // until there are no more pointers or pointers-to-members left to
2702 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002703 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002704
Douglas Gregor90609aa2011-04-25 18:40:17 +00002705 Qualifiers FromQuals = FromType.getQualifiers();
2706 Qualifiers ToQuals = ToType.getQualifiers();
2707
John McCall31168b02011-06-15 23:02:42 +00002708 // Objective-C ARC:
2709 // Check Objective-C lifetime conversions.
2710 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2711 UnwrappedAnyPointer) {
2712 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2713 ObjCLifetimeConversion = true;
2714 FromQuals.removeObjCLifetime();
2715 ToQuals.removeObjCLifetime();
2716 } else {
2717 // Qualification conversions cannot cast between different
2718 // Objective-C lifetime qualifiers.
2719 return false;
2720 }
2721 }
2722
Douglas Gregorf30053d2011-05-08 06:09:53 +00002723 // Allow addition/removal of GC attributes but not changing GC attributes.
2724 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2725 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2726 FromQuals.removeObjCGCAttr();
2727 ToQuals.removeObjCGCAttr();
2728 }
2729
Douglas Gregor9a657932008-10-21 23:43:52 +00002730 // -- for every j > 0, if const is in cv 1,j then const is in cv
2731 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002732 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002733 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002734
Douglas Gregor9a657932008-10-21 23:43:52 +00002735 // -- if the cv 1,j and cv 2,j are different, then const is in
2736 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002737 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002738 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Douglas Gregor9a657932008-10-21 23:43:52 +00002741 // Keep track of whether all prior cv-qualifiers in the "to" type
2742 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002743 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002744 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002745 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002746
2747 // We are left with FromType and ToType being the pointee types
2748 // after unwrapping the original FromType and ToType the same number
2749 // of types. If we unwrapped any pointers, and if FromType and
2750 // ToType have the same unqualified type (since we checked
2751 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002752 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002753}
2754
Sebastian Redl82ace982012-02-11 23:51:08 +00002755static OverloadingResult
2756IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2757 CXXRecordDecl *To,
2758 UserDefinedConversionSequence &User,
2759 OverloadCandidateSet &CandidateSet,
2760 bool AllowExplicit) {
2761 DeclContext::lookup_iterator Con, ConEnd;
2762 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2763 Con != ConEnd; ++Con) {
2764 NamedDecl *D = *Con;
2765 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2766
2767 // Find the constructor (which may be a template).
2768 CXXConstructorDecl *Constructor = 0;
2769 FunctionTemplateDecl *ConstructorTmpl
2770 = dyn_cast<FunctionTemplateDecl>(D);
2771 if (ConstructorTmpl)
2772 Constructor
2773 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2774 else
2775 Constructor = cast<CXXConstructorDecl>(D);
2776
2777 bool Usable = !Constructor->isInvalidDecl() &&
2778 S.isInitListConstructor(Constructor) &&
2779 (AllowExplicit || !Constructor->isExplicit());
2780 if (Usable) {
2781 if (ConstructorTmpl)
2782 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2783 /*ExplicitArgs*/ 0,
2784 &From, 1, CandidateSet,
2785 /*SuppressUserConversions=*/true);
2786 else
2787 S.AddOverloadCandidate(Constructor, FoundDecl,
2788 &From, 1, CandidateSet,
2789 /*SuppressUserConversions=*/true);
2790 }
2791 }
2792
2793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2794
2795 OverloadCandidateSet::iterator Best;
2796 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2797 case OR_Success: {
2798 // Record the standard conversion we used and the conversion function.
2799 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2800 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2801
2802 QualType ThisType = Constructor->getThisType(S.Context);
2803 // Initializer lists don't have conversions as such.
2804 User.Before.setAsIdentityConversion();
2805 User.HadMultipleCandidates = HadMultipleCandidates;
2806 User.ConversionFunction = Constructor;
2807 User.FoundConversionFunction = Best->FoundDecl;
2808 User.After.setAsIdentityConversion();
2809 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2810 User.After.setAllToTypes(ToType);
2811 return OR_Success;
2812 }
2813
2814 case OR_No_Viable_Function:
2815 return OR_No_Viable_Function;
2816 case OR_Deleted:
2817 return OR_Deleted;
2818 case OR_Ambiguous:
2819 return OR_Ambiguous;
2820 }
2821
2822 llvm_unreachable("Invalid OverloadResult!");
2823}
2824
Douglas Gregor576e98c2009-01-30 23:27:23 +00002825/// Determines whether there is a user-defined conversion sequence
2826/// (C++ [over.ics.user]) that converts expression From to the type
2827/// ToType. If such a conversion exists, User will contain the
2828/// user-defined conversion sequence that performs such a conversion
2829/// and this routine will return true. Otherwise, this routine returns
2830/// false and User is unspecified.
2831///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002832/// \param AllowExplicit true if the conversion should consider C++0x
2833/// "explicit" conversion functions as well as non-explicit conversion
2834/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002835static OverloadingResult
2836IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002837 UserDefinedConversionSequence &User,
2838 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002839 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002840 // Whether we will only visit constructors.
2841 bool ConstructorsOnly = false;
2842
2843 // If the type we are conversion to is a class type, enumerate its
2844 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002846 // C++ [over.match.ctor]p1:
2847 // When objects of class type are direct-initialized (8.5), or
2848 // copy-initialized from an expression of the same or a
2849 // derived class type (8.5), overload resolution selects the
2850 // constructor. [...] For copy-initialization, the candidate
2851 // functions are all the converting constructors (12.3.1) of
2852 // that class. The argument list is the expression-list within
2853 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002855 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002856 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002857 ConstructorsOnly = true;
2858
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002859 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2860 // RequireCompleteType may have returned true due to some invalid decl
2861 // during template instantiation, but ToType may be complete enough now
2862 // to try to recover.
2863 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002864 // We're not going to find any constructors.
2865 } else if (CXXRecordDecl *ToRecordDecl
2866 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002867
2868 Expr **Args = &From;
2869 unsigned NumArgs = 1;
2870 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002871 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002872 // But first, see if there is an init-list-contructor that will work.
2873 OverloadingResult Result = IsInitializerListConstructorConversion(
2874 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2875 if (Result != OR_No_Viable_Function)
2876 return Result;
2877 // Never mind.
2878 CandidateSet.clear();
2879
2880 // If we're list-initializing, we pass the individual elements as
2881 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002882 Args = InitList->getInits();
2883 NumArgs = InitList->getNumInits();
2884 ListInitializing = true;
2885 }
2886
Douglas Gregor89ee6822009-02-28 01:32:25 +00002887 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002888 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002889 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002890 NamedDecl *D = *Con;
2891 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2892
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002893 // Find the constructor (which may be a template).
2894 CXXConstructorDecl *Constructor = 0;
2895 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002896 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002897 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002898 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002899 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2900 else
John McCalla0296f72010-03-19 07:35:19 +00002901 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002903 bool Usable = !Constructor->isInvalidDecl();
2904 if (ListInitializing)
2905 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2906 else
2907 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2908 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002909 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002910 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2911 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002912 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002913 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002914 !ConstructorsOnly &&
2915 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002916 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002917 // Allow one user-defined conversion when user specifies a
2918 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002919 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002920 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002921 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002922 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002923 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002924 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002925 }
2926 }
2927
Douglas Gregor5ab11652010-04-17 22:01:05 +00002928 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002929 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002930 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2931 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002932 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002933 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002934 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002935 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2937 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002938 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002939 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002940 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002941 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002942 DeclAccessPair FoundDecl = I.getPair();
2943 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2945 if (isa<UsingShadowDecl>(D))
2946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2947
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002948 CXXConversionDecl *Conv;
2949 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2951 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002952 else
John McCallda4458e2010-03-31 01:36:47 +00002953 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002954
2955 if (AllowExplicit || !Conv->isExplicit()) {
2956 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002957 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2958 ActingContext, From, ToType,
2959 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002960 else
John McCall5c32be02010-08-24 20:38:10 +00002961 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2962 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002963 }
2964 }
2965 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002966 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002967
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2969
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002970 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002972 case OR_Success:
2973 // Record the standard conversion we used and the conversion function.
2974 if (CXXConstructorDecl *Constructor
2975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002976 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00002977
John McCall5c32be02010-08-24 20:38:10 +00002978 // C++ [over.ics.user]p1:
2979 // If the user-defined conversion is specified by a
2980 // constructor (12.3.1), the initial standard conversion
2981 // sequence converts the source type to the type required by
2982 // the argument of the constructor.
2983 //
2984 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002985 if (isa<InitListExpr>(From)) {
2986 // Initializer lists don't have conversions as such.
2987 User.Before.setAsIdentityConversion();
2988 } else {
2989 if (Best->Conversions[0].isEllipsis())
2990 User.EllipsisConversion = true;
2991 else {
2992 User.Before = Best->Conversions[0].Standard;
2993 User.EllipsisConversion = false;
2994 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002995 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002996 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002997 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002998 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002999 User.After.setAsIdentityConversion();
3000 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3001 User.After.setAllToTypes(ToType);
3002 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003003 }
3004 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003005 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003006 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003007
John McCall5c32be02010-08-24 20:38:10 +00003008 // C++ [over.ics.user]p1:
3009 //
3010 // [...] If the user-defined conversion is specified by a
3011 // conversion function (12.3.2), the initial standard
3012 // conversion sequence converts the source type to the
3013 // implicit object parameter of the conversion function.
3014 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003015 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003016 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003017 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003018 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003019
John McCall5c32be02010-08-24 20:38:10 +00003020 // C++ [over.ics.user]p2:
3021 // The second standard conversion sequence converts the
3022 // result of the user-defined conversion to the target type
3023 // for the sequence. Since an implicit conversion sequence
3024 // is an initialization, the special rules for
3025 // initialization by user-defined conversion apply when
3026 // selecting the best user-defined conversion for a
3027 // user-defined conversion sequence (see 13.3.3 and
3028 // 13.3.3.1).
3029 User.After = Best->FinalConversion;
3030 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003031 }
David Blaikie8a40f702012-01-17 06:56:22 +00003032 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003033
John McCall5c32be02010-08-24 20:38:10 +00003034 case OR_No_Viable_Function:
3035 return OR_No_Viable_Function;
3036 case OR_Deleted:
3037 // No conversion here! We're done.
3038 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
John McCall5c32be02010-08-24 20:38:10 +00003040 case OR_Ambiguous:
3041 return OR_Ambiguous;
3042 }
3043
David Blaikie8a40f702012-01-17 06:56:22 +00003044 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003045}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003047bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003048Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003049 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003050 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003052 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003053 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003054 if (OvResult == OR_Ambiguous)
3055 Diag(From->getSourceRange().getBegin(),
3056 diag::err_typecheck_ambiguous_condition)
3057 << From->getType() << ToType << From->getSourceRange();
3058 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3059 Diag(From->getSourceRange().getBegin(),
3060 diag::err_typecheck_nonviable_condition)
3061 << From->getType() << ToType << From->getSourceRange();
3062 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003063 return false;
John McCall5c32be02010-08-24 20:38:10 +00003064 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003066}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003067
Douglas Gregor2837aa22012-02-22 17:32:19 +00003068/// \brief Compare the user-defined conversion functions or constructors
3069/// of two user-defined conversion sequences to determine whether any ordering
3070/// is possible.
3071static ImplicitConversionSequence::CompareKind
3072compareConversionFunctions(Sema &S,
3073 FunctionDecl *Function1,
3074 FunctionDecl *Function2) {
3075 if (!S.getLangOptions().ObjC1 || !S.getLangOptions().CPlusPlus0x)
3076 return ImplicitConversionSequence::Indistinguishable;
3077
3078 // Objective-C++:
3079 // If both conversion functions are implicitly-declared conversions from
3080 // a lambda closure type to a function pointer and a block pointer,
3081 // respectively, always prefer the conversion to a function pointer,
3082 // because the function pointer is more lightweight and is more likely
3083 // to keep code working.
3084 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3085 if (!Conv1)
3086 return ImplicitConversionSequence::Indistinguishable;
3087
3088 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3089 if (!Conv2)
3090 return ImplicitConversionSequence::Indistinguishable;
3091
3092 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3093 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3094 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3095 if (Block1 != Block2)
3096 return Block1? ImplicitConversionSequence::Worse
3097 : ImplicitConversionSequence::Better;
3098 }
3099
3100 return ImplicitConversionSequence::Indistinguishable;
3101}
3102
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003103/// CompareImplicitConversionSequences - Compare two implicit
3104/// conversion sequences to determine whether one is better than the
3105/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003106static ImplicitConversionSequence::CompareKind
3107CompareImplicitConversionSequences(Sema &S,
3108 const ImplicitConversionSequence& ICS1,
3109 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003110{
3111 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3112 // conversion sequences (as defined in 13.3.3.1)
3113 // -- a standard conversion sequence (13.3.3.1.1) is a better
3114 // conversion sequence than a user-defined conversion sequence or
3115 // an ellipsis conversion sequence, and
3116 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3117 // conversion sequence than an ellipsis conversion sequence
3118 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003119 //
John McCall0d1da222010-01-12 00:44:57 +00003120 // C++0x [over.best.ics]p10:
3121 // For the purpose of ranking implicit conversion sequences as
3122 // described in 13.3.3.2, the ambiguous conversion sequence is
3123 // treated as a user-defined sequence that is indistinguishable
3124 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003125 if (ICS1.getKindRank() < ICS2.getKindRank())
3126 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003127 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003128 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003129
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003130 // The following checks require both conversion sequences to be of
3131 // the same kind.
3132 if (ICS1.getKind() != ICS2.getKind())
3133 return ImplicitConversionSequence::Indistinguishable;
3134
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003135 ImplicitConversionSequence::CompareKind Result =
3136 ImplicitConversionSequence::Indistinguishable;
3137
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003138 // Two implicit conversion sequences of the same form are
3139 // indistinguishable conversion sequences unless one of the
3140 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003141 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003142 Result = CompareStandardConversionSequences(S,
3143 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003144 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003145 // User-defined conversion sequence U1 is a better conversion
3146 // sequence than another user-defined conversion sequence U2 if
3147 // they contain the same user-defined conversion function or
3148 // constructor and if the second standard conversion sequence of
3149 // U1 is better than the second standard conversion sequence of
3150 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003151 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003152 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003153 Result = CompareStandardConversionSequences(S,
3154 ICS1.UserDefined.After,
3155 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003156 else
3157 Result = compareConversionFunctions(S,
3158 ICS1.UserDefined.ConversionFunction,
3159 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003160 }
3161
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003162 // List-initialization sequence L1 is a better conversion sequence than
3163 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3164 // for some X and L2 does not.
3165 if (Result == ImplicitConversionSequence::Indistinguishable &&
3166 ICS1.isListInitializationSequence() &&
3167 ICS2.isListInitializationSequence()) {
3168 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3169 }
3170
3171 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003172}
3173
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003174static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3175 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3176 Qualifiers Quals;
3177 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003181 return Context.hasSameUnqualifiedType(T1, T2);
3182}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003184// Per 13.3.3.2p3, compare the given standard conversion sequences to
3185// determine if one is a proper subset of the other.
3186static ImplicitConversionSequence::CompareKind
3187compareStandardConversionSubsets(ASTContext &Context,
3188 const StandardConversionSequence& SCS1,
3189 const StandardConversionSequence& SCS2) {
3190 ImplicitConversionSequence::CompareKind Result
3191 = ImplicitConversionSequence::Indistinguishable;
3192
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003194 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003195 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3196 return ImplicitConversionSequence::Better;
3197 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3198 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003200 if (SCS1.Second != SCS2.Second) {
3201 if (SCS1.Second == ICK_Identity)
3202 Result = ImplicitConversionSequence::Better;
3203 else if (SCS2.Second == ICK_Identity)
3204 Result = ImplicitConversionSequence::Worse;
3205 else
3206 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003207 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003208 return ImplicitConversionSequence::Indistinguishable;
3209
3210 if (SCS1.Third == SCS2.Third) {
3211 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3212 : ImplicitConversionSequence::Indistinguishable;
3213 }
3214
3215 if (SCS1.Third == ICK_Identity)
3216 return Result == ImplicitConversionSequence::Worse
3217 ? ImplicitConversionSequence::Indistinguishable
3218 : ImplicitConversionSequence::Better;
3219
3220 if (SCS2.Third == ICK_Identity)
3221 return Result == ImplicitConversionSequence::Better
3222 ? ImplicitConversionSequence::Indistinguishable
3223 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003225 return ImplicitConversionSequence::Indistinguishable;
3226}
3227
Douglas Gregore696ebb2011-01-26 14:52:12 +00003228/// \brief Determine whether one of the given reference bindings is better
3229/// than the other based on what kind of bindings they are.
3230static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3231 const StandardConversionSequence &SCS2) {
3232 // C++0x [over.ics.rank]p3b4:
3233 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3234 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003236 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003238 // reference*.
3239 //
3240 // FIXME: Rvalue references. We're going rogue with the above edits,
3241 // because the semantics in the current C++0x working paper (N3225 at the
3242 // time of this writing) break the standard definition of std::forward
3243 // and std::reference_wrapper when dealing with references to functions.
3244 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003245 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3246 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3247 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregore696ebb2011-01-26 14:52:12 +00003249 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3250 SCS2.IsLvalueReference) ||
3251 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3252 !SCS2.IsLvalueReference);
3253}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003255/// CompareStandardConversionSequences - Compare two standard
3256/// conversion sequences to determine whether one is better than the
3257/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003258static ImplicitConversionSequence::CompareKind
3259CompareStandardConversionSequences(Sema &S,
3260 const StandardConversionSequence& SCS1,
3261 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003262{
3263 // Standard conversion sequence S1 is a better conversion sequence
3264 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3265
3266 // -- S1 is a proper subsequence of S2 (comparing the conversion
3267 // sequences in the canonical form defined by 13.3.3.1.1,
3268 // excluding any Lvalue Transformation; the identity conversion
3269 // sequence is considered to be a subsequence of any
3270 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003271 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003272 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003273 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003274
3275 // -- the rank of S1 is better than the rank of S2 (by the rules
3276 // defined below), or, if not that,
3277 ImplicitConversionRank Rank1 = SCS1.getRank();
3278 ImplicitConversionRank Rank2 = SCS2.getRank();
3279 if (Rank1 < Rank2)
3280 return ImplicitConversionSequence::Better;
3281 else if (Rank2 < Rank1)
3282 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003283
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003284 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3285 // are indistinguishable unless one of the following rules
3286 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003287
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003288 // A conversion that is not a conversion of a pointer, or
3289 // pointer to member, to bool is better than another conversion
3290 // that is such a conversion.
3291 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3292 return SCS2.isPointerConversionToBool()
3293 ? ImplicitConversionSequence::Better
3294 : ImplicitConversionSequence::Worse;
3295
Douglas Gregor5c407d92008-10-23 00:40:37 +00003296 // C++ [over.ics.rank]p4b2:
3297 //
3298 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003299 // conversion of B* to A* is better than conversion of B* to
3300 // void*, and conversion of A* to void* is better than conversion
3301 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003302 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003303 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003304 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003305 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003306 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3307 // Exactly one of the conversion sequences is a conversion to
3308 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003309 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3310 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003311 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3312 // Neither conversion sequence converts to a void pointer; compare
3313 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003314 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003315 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003316 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003317 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3318 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003319 // Both conversion sequences are conversions to void
3320 // pointers. Compare the source types to determine if there's an
3321 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003322 QualType FromType1 = SCS1.getFromType();
3323 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003324
3325 // Adjust the types we're converting from via the array-to-pointer
3326 // conversion, if we need to.
3327 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003328 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003329 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003330 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003331
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003332 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3333 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003334
John McCall5c32be02010-08-24 20:38:10 +00003335 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003336 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003337 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003338 return ImplicitConversionSequence::Worse;
3339
3340 // Objective-C++: If one interface is more specific than the
3341 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003342 const ObjCObjectPointerType* FromObjCPtr1
3343 = FromType1->getAs<ObjCObjectPointerType>();
3344 const ObjCObjectPointerType* FromObjCPtr2
3345 = FromType2->getAs<ObjCObjectPointerType>();
3346 if (FromObjCPtr1 && FromObjCPtr2) {
3347 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3348 FromObjCPtr2);
3349 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3350 FromObjCPtr1);
3351 if (AssignLeft != AssignRight) {
3352 return AssignLeft? ImplicitConversionSequence::Better
3353 : ImplicitConversionSequence::Worse;
3354 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003355 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003356 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003357
3358 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3359 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003360 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003361 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003362 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003363
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003364 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003365 // Check for a better reference binding based on the kind of bindings.
3366 if (isBetterReferenceBindingKind(SCS1, SCS2))
3367 return ImplicitConversionSequence::Better;
3368 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3369 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370
Sebastian Redlb28b4072009-03-22 23:49:27 +00003371 // C++ [over.ics.rank]p3b4:
3372 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3373 // which the references refer are the same type except for
3374 // top-level cv-qualifiers, and the type to which the reference
3375 // initialized by S2 refers is more cv-qualified than the type
3376 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003377 QualType T1 = SCS1.getToType(2);
3378 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003379 T1 = S.Context.getCanonicalType(T1);
3380 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003381 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003382 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3383 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003384 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003385 // Objective-C++ ARC: If the references refer to objects with different
3386 // lifetimes, prefer bindings that don't change lifetime.
3387 if (SCS1.ObjCLifetimeConversionBinding !=
3388 SCS2.ObjCLifetimeConversionBinding) {
3389 return SCS1.ObjCLifetimeConversionBinding
3390 ? ImplicitConversionSequence::Worse
3391 : ImplicitConversionSequence::Better;
3392 }
3393
Chandler Carruth8e543b32010-12-12 08:17:55 +00003394 // If the type is an array type, promote the element qualifiers to the
3395 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003396 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003397 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003398 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003399 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003400 if (T2.isMoreQualifiedThan(T1))
3401 return ImplicitConversionSequence::Better;
3402 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003403 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003404 }
3405 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003406
Francois Pichet08d2fa02011-09-18 21:37:37 +00003407 // In Microsoft mode, prefer an integral conversion to a
3408 // floating-to-integral conversion if the integral conversion
3409 // is between types of the same size.
3410 // For example:
3411 // void f(float);
3412 // void f(int);
3413 // int main {
3414 // long a;
3415 // f(a);
3416 // }
3417 // Here, MSVC will call f(int) instead of generating a compile error
3418 // as clang will do in standard mode.
3419 if (S.getLangOptions().MicrosoftMode &&
3420 SCS1.Second == ICK_Integral_Conversion &&
3421 SCS2.Second == ICK_Floating_Integral &&
3422 S.Context.getTypeSize(SCS1.getFromType()) ==
3423 S.Context.getTypeSize(SCS1.getToType(2)))
3424 return ImplicitConversionSequence::Better;
3425
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003426 return ImplicitConversionSequence::Indistinguishable;
3427}
3428
3429/// CompareQualificationConversions - Compares two standard conversion
3430/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003431/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3432ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003433CompareQualificationConversions(Sema &S,
3434 const StandardConversionSequence& SCS1,
3435 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003436 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003437 // -- S1 and S2 differ only in their qualification conversion and
3438 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3439 // cv-qualification signature of type T1 is a proper subset of
3440 // the cv-qualification signature of type T2, and S1 is not the
3441 // deprecated string literal array-to-pointer conversion (4.2).
3442 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3443 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3444 return ImplicitConversionSequence::Indistinguishable;
3445
3446 // FIXME: the example in the standard doesn't use a qualification
3447 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003448 QualType T1 = SCS1.getToType(2);
3449 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003450 T1 = S.Context.getCanonicalType(T1);
3451 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003452 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003453 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3454 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003455
3456 // If the types are the same, we won't learn anything by unwrapped
3457 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003458 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003459 return ImplicitConversionSequence::Indistinguishable;
3460
Chandler Carruth607f38e2009-12-29 07:16:59 +00003461 // If the type is an array type, promote the element qualifiers to the type
3462 // for comparison.
3463 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003464 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003465 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003466 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003467
Mike Stump11289f42009-09-09 15:08:12 +00003468 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003469 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003470
3471 // Objective-C++ ARC:
3472 // Prefer qualification conversions not involving a change in lifetime
3473 // to qualification conversions that do not change lifetime.
3474 if (SCS1.QualificationIncludesObjCLifetime !=
3475 SCS2.QualificationIncludesObjCLifetime) {
3476 Result = SCS1.QualificationIncludesObjCLifetime
3477 ? ImplicitConversionSequence::Worse
3478 : ImplicitConversionSequence::Better;
3479 }
3480
John McCall5c32be02010-08-24 20:38:10 +00003481 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003482 // Within each iteration of the loop, we check the qualifiers to
3483 // determine if this still looks like a qualification
3484 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003485 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003486 // until there are no more pointers or pointers-to-members left
3487 // to unwrap. This essentially mimics what
3488 // IsQualificationConversion does, but here we're checking for a
3489 // strict subset of qualifiers.
3490 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3491 // The qualifiers are the same, so this doesn't tell us anything
3492 // about how the sequences rank.
3493 ;
3494 else if (T2.isMoreQualifiedThan(T1)) {
3495 // T1 has fewer qualifiers, so it could be the better sequence.
3496 if (Result == ImplicitConversionSequence::Worse)
3497 // Neither has qualifiers that are a subset of the other's
3498 // qualifiers.
3499 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003501 Result = ImplicitConversionSequence::Better;
3502 } else if (T1.isMoreQualifiedThan(T2)) {
3503 // T2 has fewer qualifiers, so it could be the better sequence.
3504 if (Result == ImplicitConversionSequence::Better)
3505 // Neither has qualifiers that are a subset of the other's
3506 // qualifiers.
3507 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003509 Result = ImplicitConversionSequence::Worse;
3510 } else {
3511 // Qualifiers are disjoint.
3512 return ImplicitConversionSequence::Indistinguishable;
3513 }
3514
3515 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003516 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003517 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003518 }
3519
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003520 // Check that the winning standard conversion sequence isn't using
3521 // the deprecated string literal array to pointer conversion.
3522 switch (Result) {
3523 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003524 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003525 Result = ImplicitConversionSequence::Indistinguishable;
3526 break;
3527
3528 case ImplicitConversionSequence::Indistinguishable:
3529 break;
3530
3531 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003532 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003533 Result = ImplicitConversionSequence::Indistinguishable;
3534 break;
3535 }
3536
3537 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003538}
3539
Douglas Gregor5c407d92008-10-23 00:40:37 +00003540/// CompareDerivedToBaseConversions - Compares two standard conversion
3541/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003542/// various kinds of derived-to-base conversions (C++
3543/// [over.ics.rank]p4b3). As part of these checks, we also look at
3544/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003545ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003546CompareDerivedToBaseConversions(Sema &S,
3547 const StandardConversionSequence& SCS1,
3548 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003549 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003550 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003551 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003552 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003553
3554 // Adjust the types we're converting from via the array-to-pointer
3555 // conversion, if we need to.
3556 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003557 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003558 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003559 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003560
3561 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003562 FromType1 = S.Context.getCanonicalType(FromType1);
3563 ToType1 = S.Context.getCanonicalType(ToType1);
3564 FromType2 = S.Context.getCanonicalType(FromType2);
3565 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003566
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003567 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003568 //
3569 // If class B is derived directly or indirectly from class A and
3570 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003571 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003572 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003573 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003574 SCS2.Second == ICK_Pointer_Conversion &&
3575 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3576 FromType1->isPointerType() && FromType2->isPointerType() &&
3577 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003578 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003579 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003580 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003581 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003582 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003583 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003584 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003585 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003586
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003587 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003588 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003589 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003590 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003591 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003592 return ImplicitConversionSequence::Worse;
3593 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003594
3595 // -- conversion of B* to A* is better than conversion of C* to A*,
3596 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003597 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003598 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003599 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003601 }
3602 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3603 SCS2.Second == ICK_Pointer_Conversion) {
3604 const ObjCObjectPointerType *FromPtr1
3605 = FromType1->getAs<ObjCObjectPointerType>();
3606 const ObjCObjectPointerType *FromPtr2
3607 = FromType2->getAs<ObjCObjectPointerType>();
3608 const ObjCObjectPointerType *ToPtr1
3609 = ToType1->getAs<ObjCObjectPointerType>();
3610 const ObjCObjectPointerType *ToPtr2
3611 = ToType2->getAs<ObjCObjectPointerType>();
3612
3613 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3614 // Apply the same conversion ranking rules for Objective-C pointer types
3615 // that we do for C++ pointers to class types. However, we employ the
3616 // Objective-C pseudo-subtyping relationship used for assignment of
3617 // Objective-C pointer types.
3618 bool FromAssignLeft
3619 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3620 bool FromAssignRight
3621 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3622 bool ToAssignLeft
3623 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3624 bool ToAssignRight
3625 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3626
3627 // A conversion to an a non-id object pointer type or qualified 'id'
3628 // type is better than a conversion to 'id'.
3629 if (ToPtr1->isObjCIdType() &&
3630 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3631 return ImplicitConversionSequence::Worse;
3632 if (ToPtr2->isObjCIdType() &&
3633 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3634 return ImplicitConversionSequence::Better;
3635
3636 // A conversion to a non-id object pointer type is better than a
3637 // conversion to a qualified 'id' type
3638 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3639 return ImplicitConversionSequence::Worse;
3640 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3641 return ImplicitConversionSequence::Better;
3642
3643 // A conversion to an a non-Class object pointer type or qualified 'Class'
3644 // type is better than a conversion to 'Class'.
3645 if (ToPtr1->isObjCClassType() &&
3646 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3647 return ImplicitConversionSequence::Worse;
3648 if (ToPtr2->isObjCClassType() &&
3649 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3650 return ImplicitConversionSequence::Better;
3651
3652 // A conversion to a non-Class object pointer type is better than a
3653 // conversion to a qualified 'Class' type.
3654 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3655 return ImplicitConversionSequence::Worse;
3656 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3657 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003658
Douglas Gregor058d3de2011-01-31 18:51:41 +00003659 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3660 if (S.Context.hasSameType(FromType1, FromType2) &&
3661 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3662 (ToAssignLeft != ToAssignRight))
3663 return ToAssignLeft? ImplicitConversionSequence::Worse
3664 : ImplicitConversionSequence::Better;
3665
3666 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3667 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3668 (FromAssignLeft != FromAssignRight))
3669 return FromAssignLeft? ImplicitConversionSequence::Better
3670 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003671 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003672 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003673
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003674 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003675 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3676 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3677 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003679 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003681 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003683 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003685 ToType2->getAs<MemberPointerType>();
3686 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3687 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3688 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3689 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3690 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3691 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3692 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3693 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003694 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003696 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003697 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003698 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003699 return ImplicitConversionSequence::Better;
3700 }
3701 // conversion of B::* to C::* is better than conversion of A::* to C::*
3702 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003703 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003704 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003705 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003706 return ImplicitConversionSequence::Worse;
3707 }
3708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709
Douglas Gregor5ab11652010-04-17 22:01:05 +00003710 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003711 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003712 // -- binding of an expression of type C to a reference of type
3713 // B& is better than binding an expression of type C to a
3714 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003715 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3716 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3717 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003718 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003719 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003720 return ImplicitConversionSequence::Worse;
3721 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003722
Douglas Gregor2fe98832008-11-03 19:09:14 +00003723 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003724 // -- binding of an expression of type B to a reference of type
3725 // A& is better than binding an expression of type C to a
3726 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003727 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3728 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3729 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003730 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003731 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003732 return ImplicitConversionSequence::Worse;
3733 }
3734 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003735
Douglas Gregor5c407d92008-10-23 00:40:37 +00003736 return ImplicitConversionSequence::Indistinguishable;
3737}
3738
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003739/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3740/// determine whether they are reference-related,
3741/// reference-compatible, reference-compatible with added
3742/// qualification, or incompatible, for use in C++ initialization by
3743/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3744/// type, and the first type (T1) is the pointee type of the reference
3745/// type being initialized.
3746Sema::ReferenceCompareResult
3747Sema::CompareReferenceRelationship(SourceLocation Loc,
3748 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003749 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003750 bool &ObjCConversion,
3751 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003752 assert(!OrigT1->isReferenceType() &&
3753 "T1 must be the pointee type of the reference type");
3754 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3755
3756 QualType T1 = Context.getCanonicalType(OrigT1);
3757 QualType T2 = Context.getCanonicalType(OrigT2);
3758 Qualifiers T1Quals, T2Quals;
3759 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3760 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3761
3762 // C++ [dcl.init.ref]p4:
3763 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3764 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3765 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003766 DerivedToBase = false;
3767 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003768 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003769 if (UnqualT1 == UnqualT2) {
3770 // Nothing to do.
3771 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003772 IsDerivedFrom(UnqualT2, UnqualT1))
3773 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003774 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3775 UnqualT2->isObjCObjectOrInterfaceType() &&
3776 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3777 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003778 else
3779 return Ref_Incompatible;
3780
3781 // At this point, we know that T1 and T2 are reference-related (at
3782 // least).
3783
3784 // If the type is an array type, promote the element qualifiers to the type
3785 // for comparison.
3786 if (isa<ArrayType>(T1) && T1Quals)
3787 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3788 if (isa<ArrayType>(T2) && T2Quals)
3789 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3790
3791 // C++ [dcl.init.ref]p4:
3792 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3793 // reference-related to T2 and cv1 is the same cv-qualification
3794 // as, or greater cv-qualification than, cv2. For purposes of
3795 // overload resolution, cases for which cv1 is greater
3796 // cv-qualification than cv2 are identified as
3797 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003798 //
3799 // Note that we also require equivalence of Objective-C GC and address-space
3800 // qualifiers when performing these computations, so that e.g., an int in
3801 // address space 1 is not reference-compatible with an int in address
3802 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003803 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3804 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3805 T1Quals.removeObjCLifetime();
3806 T2Quals.removeObjCLifetime();
3807 ObjCLifetimeConversion = true;
3808 }
3809
Douglas Gregord517d552011-04-28 17:56:11 +00003810 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003811 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003812 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003813 return Ref_Compatible_With_Added_Qualification;
3814 else
3815 return Ref_Related;
3816}
3817
Douglas Gregor836a7e82010-08-11 02:15:33 +00003818/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003819/// with DeclType. Return true if something definite is found.
3820static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003821FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3822 QualType DeclType, SourceLocation DeclLoc,
3823 Expr *Init, QualType T2, bool AllowRvalues,
3824 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003825 assert(T2->isRecordType() && "Can only find conversions of record types.");
3826 CXXRecordDecl *T2RecordDecl
3827 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3828
3829 OverloadCandidateSet CandidateSet(DeclLoc);
3830 const UnresolvedSetImpl *Conversions
3831 = T2RecordDecl->getVisibleConversionFunctions();
3832 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3833 E = Conversions->end(); I != E; ++I) {
3834 NamedDecl *D = *I;
3835 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3836 if (isa<UsingShadowDecl>(D))
3837 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3838
3839 FunctionTemplateDecl *ConvTemplate
3840 = dyn_cast<FunctionTemplateDecl>(D);
3841 CXXConversionDecl *Conv;
3842 if (ConvTemplate)
3843 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3844 else
3845 Conv = cast<CXXConversionDecl>(D);
3846
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003848 // explicit conversions, skip it.
3849 if (!AllowExplicit && Conv->isExplicit())
3850 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851
Douglas Gregor836a7e82010-08-11 02:15:33 +00003852 if (AllowRvalues) {
3853 bool DerivedToBase = false;
3854 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003855 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003856
3857 // If we are initializing an rvalue reference, don't permit conversion
3858 // functions that return lvalues.
3859 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3860 const ReferenceType *RefType
3861 = Conv->getConversionType()->getAs<LValueReferenceType>();
3862 if (RefType && !RefType->getPointeeType()->isFunctionType())
3863 continue;
3864 }
3865
Douglas Gregor836a7e82010-08-11 02:15:33 +00003866 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003867 S.CompareReferenceRelationship(
3868 DeclLoc,
3869 Conv->getConversionType().getNonReferenceType()
3870 .getUnqualifiedType(),
3871 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003872 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003873 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003874 continue;
3875 } else {
3876 // If the conversion function doesn't return a reference type,
3877 // it can't be considered for this conversion. An rvalue reference
3878 // is only acceptable if its referencee is a function type.
3879
3880 const ReferenceType *RefType =
3881 Conv->getConversionType()->getAs<ReferenceType>();
3882 if (!RefType ||
3883 (!RefType->isLValueReferenceType() &&
3884 !RefType->getPointeeType()->isFunctionType()))
3885 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor836a7e82010-08-11 02:15:33 +00003888 if (ConvTemplate)
3889 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003890 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003891 else
3892 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003893 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003894 }
3895
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003896 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3897
Sebastian Redld92badf2010-06-30 18:13:39 +00003898 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003899 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003900 case OR_Success:
3901 // C++ [over.ics.ref]p1:
3902 //
3903 // [...] If the parameter binds directly to the result of
3904 // applying a conversion function to the argument
3905 // expression, the implicit conversion sequence is a
3906 // user-defined conversion sequence (13.3.3.1.2), with the
3907 // second standard conversion sequence either an identity
3908 // conversion or, if the conversion function returns an
3909 // entity of a type that is a derived class of the parameter
3910 // type, a derived-to-base Conversion.
3911 if (!Best->FinalConversion.DirectBinding)
3912 return false;
3913
Chandler Carruth30141632011-02-25 19:41:05 +00003914 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003915 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003916 ICS.setUserDefined();
3917 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3918 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003919 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003920 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003921 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003922 ICS.UserDefined.EllipsisConversion = false;
3923 assert(ICS.UserDefined.After.ReferenceBinding &&
3924 ICS.UserDefined.After.DirectBinding &&
3925 "Expected a direct reference binding!");
3926 return true;
3927
3928 case OR_Ambiguous:
3929 ICS.setAmbiguous();
3930 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3931 Cand != CandidateSet.end(); ++Cand)
3932 if (Cand->Viable)
3933 ICS.Ambiguous.addConversion(Cand->Function);
3934 return true;
3935
3936 case OR_No_Viable_Function:
3937 case OR_Deleted:
3938 // There was no suitable conversion, or we found a deleted
3939 // conversion; continue with other checks.
3940 return false;
3941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942
David Blaikie8a40f702012-01-17 06:56:22 +00003943 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003944}
3945
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003946/// \brief Compute an implicit conversion sequence for reference
3947/// initialization.
3948static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003949TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003950 SourceLocation DeclLoc,
3951 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003952 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003953 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3954
3955 // Most paths end in a failed conversion.
3956 ImplicitConversionSequence ICS;
3957 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3958
3959 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3960 QualType T2 = Init->getType();
3961
3962 // If the initializer is the address of an overloaded function, try
3963 // to resolve the overloaded function. If all goes well, T2 is the
3964 // type of the resulting function.
3965 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3966 DeclAccessPair Found;
3967 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3968 false, Found))
3969 T2 = Fn->getType();
3970 }
3971
3972 // Compute some basic properties of the types and the initializer.
3973 bool isRValRef = DeclType->isRValueReferenceType();
3974 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003975 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003976 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003977 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003978 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003979 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003980 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003981
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003982
Sebastian Redld92badf2010-06-30 18:13:39 +00003983 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003984 // A reference to type "cv1 T1" is initialized by an expression
3985 // of type "cv2 T2" as follows:
3986
Sebastian Redld92badf2010-06-30 18:13:39 +00003987 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003988 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003989 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3990 // reference-compatible with "cv2 T2," or
3991 //
3992 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3993 if (InitCategory.isLValue() &&
3994 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003995 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003996 // When a parameter of reference type binds directly (8.5.3)
3997 // to an argument expression, the implicit conversion sequence
3998 // is the identity conversion, unless the argument expression
3999 // has a type that is a derived class of the parameter type,
4000 // in which case the implicit conversion sequence is a
4001 // derived-to-base Conversion (13.3.3.1).
4002 ICS.setStandard();
4003 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004004 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4005 : ObjCConversion? ICK_Compatible_Conversion
4006 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004007 ICS.Standard.Third = ICK_Identity;
4008 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4009 ICS.Standard.setToType(0, T2);
4010 ICS.Standard.setToType(1, T1);
4011 ICS.Standard.setToType(2, T1);
4012 ICS.Standard.ReferenceBinding = true;
4013 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004014 ICS.Standard.IsLvalueReference = !isRValRef;
4015 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4016 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004017 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004018 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004019 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004020
Sebastian Redld92badf2010-06-30 18:13:39 +00004021 // Nothing more to do: the inaccessibility/ambiguity check for
4022 // derived-to-base conversions is suppressed when we're
4023 // computing the implicit conversion sequence (C++
4024 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004026 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004027
Sebastian Redld92badf2010-06-30 18:13:39 +00004028 // -- has a class type (i.e., T2 is a class type), where T1 is
4029 // not reference-related to T2, and can be implicitly
4030 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4031 // is reference-compatible with "cv3 T3" 92) (this
4032 // conversion is selected by enumerating the applicable
4033 // conversion functions (13.3.1.6) and choosing the best
4034 // one through overload resolution (13.3)),
4035 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004037 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004038 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4039 Init, T2, /*AllowRvalues=*/false,
4040 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004041 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004042 }
4043 }
4044
Sebastian Redld92badf2010-06-30 18:13:39 +00004045 // -- Otherwise, the reference shall be an lvalue reference to a
4046 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004047 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004049 // We actually handle one oddity of C++ [over.ics.ref] at this
4050 // point, which is that, due to p2 (which short-circuits reference
4051 // binding by only attempting a simple conversion for non-direct
4052 // bindings) and p3's strange wording, we allow a const volatile
4053 // reference to bind to an rvalue. Hence the check for the presence
4054 // of "const" rather than checking for "const" being the only
4055 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004056 // This is also the point where rvalue references and lvalue inits no longer
4057 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004058 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004059 return ICS;
4060
Douglas Gregorf143cd52011-01-24 16:14:37 +00004061 // -- If the initializer expression
4062 //
4063 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004064 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004065 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4066 (InitCategory.isXValue() ||
4067 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4068 (InitCategory.isLValue() && T2->isFunctionType()))) {
4069 ICS.setStandard();
4070 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004071 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004072 : ObjCConversion? ICK_Compatible_Conversion
4073 : ICK_Identity;
4074 ICS.Standard.Third = ICK_Identity;
4075 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4076 ICS.Standard.setToType(0, T2);
4077 ICS.Standard.setToType(1, T1);
4078 ICS.Standard.setToType(2, T1);
4079 ICS.Standard.ReferenceBinding = true;
4080 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4081 // binding unless we're binding to a class prvalue.
4082 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4083 // allow the use of rvalue references in C++98/03 for the benefit of
4084 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085 ICS.Standard.DirectBinding =
4086 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004087 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004088 ICS.Standard.IsLvalueReference = !isRValRef;
4089 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004091 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004092 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004093 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096
Douglas Gregorf143cd52011-01-24 16:14:37 +00004097 // -- has a class type (i.e., T2 is a class type), where T1 is not
4098 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099 // an xvalue, class prvalue, or function lvalue of type
4100 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004101 // "cv3 T3",
4102 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004104 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004106 // class subobject).
4107 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004109 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4110 Init, T2, /*AllowRvalues=*/true,
4111 AllowExplicit)) {
4112 // In the second case, if the reference is an rvalue reference
4113 // and the second standard conversion sequence of the
4114 // user-defined conversion sequence includes an lvalue-to-rvalue
4115 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004117 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4118 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4119
Douglas Gregor95273c32011-01-21 16:36:05 +00004120 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004123 // -- Otherwise, a temporary of type "cv1 T1" is created and
4124 // initialized from the initializer expression using the
4125 // rules for a non-reference copy initialization (8.5). The
4126 // reference is then bound to the temporary. If T1 is
4127 // reference-related to T2, cv1 must be the same
4128 // cv-qualification as, or greater cv-qualification than,
4129 // cv2; otherwise, the program is ill-formed.
4130 if (RefRelationship == Sema::Ref_Related) {
4131 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4132 // we would be reference-compatible or reference-compatible with
4133 // added qualification. But that wasn't the case, so the reference
4134 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004135 //
4136 // Note that we only want to check address spaces and cvr-qualifiers here.
4137 // ObjC GC and lifetime qualifiers aren't important.
4138 Qualifiers T1Quals = T1.getQualifiers();
4139 Qualifiers T2Quals = T2.getQualifiers();
4140 T1Quals.removeObjCGCAttr();
4141 T1Quals.removeObjCLifetime();
4142 T2Quals.removeObjCGCAttr();
4143 T2Quals.removeObjCLifetime();
4144 if (!T1Quals.compatiblyIncludes(T2Quals))
4145 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004146 }
4147
4148 // If at least one of the types is a class type, the types are not
4149 // related, and we aren't allowed any user conversions, the
4150 // reference binding fails. This case is important for breaking
4151 // recursion, since TryImplicitConversion below will attempt to
4152 // create a temporary through the use of a copy constructor.
4153 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4154 (T1->isRecordType() || T2->isRecordType()))
4155 return ICS;
4156
Douglas Gregorcba72b12011-01-21 05:18:22 +00004157 // If T1 is reference-related to T2 and the reference is an rvalue
4158 // reference, the initializer expression shall not be an lvalue.
4159 if (RefRelationship >= Sema::Ref_Related &&
4160 isRValRef && Init->Classify(S.Context).isLValue())
4161 return ICS;
4162
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004163 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004164 // When a parameter of reference type is not bound directly to
4165 // an argument expression, the conversion sequence is the one
4166 // required to convert the argument expression to the
4167 // underlying type of the reference according to
4168 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4169 // to copy-initializing a temporary of the underlying type with
4170 // the argument expression. Any difference in top-level
4171 // cv-qualification is subsumed by the initialization itself
4172 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004173 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4174 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004175 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004176 /*CStyle=*/false,
4177 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004178
4179 // Of course, that's still a reference binding.
4180 if (ICS.isStandard()) {
4181 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004182 ICS.Standard.IsLvalueReference = !isRValRef;
4183 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4184 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004185 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004186 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004187 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004188 // Don't allow rvalue references to bind to lvalues.
4189 if (DeclType->isRValueReferenceType()) {
4190 if (const ReferenceType *RefType
4191 = ICS.UserDefined.ConversionFunction->getResultType()
4192 ->getAs<LValueReferenceType>()) {
4193 if (!RefType->getPointeeType()->isFunctionType()) {
4194 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4195 DeclType);
4196 return ICS;
4197 }
4198 }
4199 }
4200
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004202 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4203 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4204 ICS.UserDefined.After.BindsToRvalue = true;
4205 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4206 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004207 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004208
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004209 return ICS;
4210}
4211
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004212static ImplicitConversionSequence
4213TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4214 bool SuppressUserConversions,
4215 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004216 bool AllowObjCWritebackConversion,
4217 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004218
4219/// TryListConversion - Try to copy-initialize a value of type ToType from the
4220/// initializer list From.
4221static ImplicitConversionSequence
4222TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4223 bool SuppressUserConversions,
4224 bool InOverloadResolution,
4225 bool AllowObjCWritebackConversion) {
4226 // C++11 [over.ics.list]p1:
4227 // When an argument is an initializer list, it is not an expression and
4228 // special rules apply for converting it to a parameter type.
4229
4230 ImplicitConversionSequence Result;
4231 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004232 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004233
Sebastian Redl09edce02012-01-23 22:09:39 +00004234 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004235 // initialized from init lists.
4236 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4237 return Result;
4238
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004239 // C++11 [over.ics.list]p2:
4240 // If the parameter type is std::initializer_list<X> or "array of X" and
4241 // all the elements can be implicitly converted to X, the implicit
4242 // conversion sequence is the worst conversion necessary to convert an
4243 // element of the list to X.
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004244 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004245 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004246 X = S.Context.getBaseElementType(ToType);
4247 else
4248 (void)S.isStdInitializerList(ToType, &X);
4249 if (!X.isNull()) {
4250 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4251 Expr *Init = From->getInit(i);
4252 ImplicitConversionSequence ICS =
4253 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4254 InOverloadResolution,
4255 AllowObjCWritebackConversion);
4256 // If a single element isn't convertible, fail.
4257 if (ICS.isBad()) {
4258 Result = ICS;
4259 break;
4260 }
4261 // Otherwise, look for the worst conversion.
4262 if (Result.isBad() ||
4263 CompareImplicitConversionSequences(S, ICS, Result) ==
4264 ImplicitConversionSequence::Worse)
4265 Result = ICS;
4266 }
4267 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004268 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004269 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004270
4271 // C++11 [over.ics.list]p3:
4272 // Otherwise, if the parameter is a non-aggregate class X and overload
4273 // resolution chooses a single best constructor [...] the implicit
4274 // conversion sequence is a user-defined conversion sequence. If multiple
4275 // constructors are viable but none is better than the others, the
4276 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004277 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4278 // This function can deal with initializer lists.
4279 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4280 /*AllowExplicit=*/false,
4281 InOverloadResolution, /*CStyle=*/false,
4282 AllowObjCWritebackConversion);
4283 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004284 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004285 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004286
4287 // C++11 [over.ics.list]p4:
4288 // Otherwise, if the parameter has an aggregate type which can be
4289 // initialized from the initializer list [...] the implicit conversion
4290 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004291 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004292 // Type is an aggregate, argument is an init list. At this point it comes
4293 // down to checking whether the initialization works.
4294 // FIXME: Find out whether this parameter is consumed or not.
4295 InitializedEntity Entity =
4296 InitializedEntity::InitializeParameter(S.Context, ToType,
4297 /*Consumed=*/false);
4298 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4299 Result.setUserDefined();
4300 Result.UserDefined.Before.setAsIdentityConversion();
4301 // Initializer lists don't have a type.
4302 Result.UserDefined.Before.setFromType(QualType());
4303 Result.UserDefined.Before.setAllToTypes(QualType());
4304
4305 Result.UserDefined.After.setAsIdentityConversion();
4306 Result.UserDefined.After.setFromType(ToType);
4307 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004308 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004309 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004310 return Result;
4311 }
4312
4313 // C++11 [over.ics.list]p5:
4314 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004315 if (ToType->isReferenceType()) {
4316 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4317 // mention initializer lists in any way. So we go by what list-
4318 // initialization would do and try to extrapolate from that.
4319
4320 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4321
4322 // If the initializer list has a single element that is reference-related
4323 // to the parameter type, we initialize the reference from that.
4324 if (From->getNumInits() == 1) {
4325 Expr *Init = From->getInit(0);
4326
4327 QualType T2 = Init->getType();
4328
4329 // If the initializer is the address of an overloaded function, try
4330 // to resolve the overloaded function. If all goes well, T2 is the
4331 // type of the resulting function.
4332 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4333 DeclAccessPair Found;
4334 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4335 Init, ToType, false, Found))
4336 T2 = Fn->getType();
4337 }
4338
4339 // Compute some basic properties of the types and the initializer.
4340 bool dummy1 = false;
4341 bool dummy2 = false;
4342 bool dummy3 = false;
4343 Sema::ReferenceCompareResult RefRelationship
4344 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4345 dummy2, dummy3);
4346
4347 if (RefRelationship >= Sema::Ref_Related)
4348 return TryReferenceInit(S, Init, ToType,
4349 /*FIXME:*/From->getLocStart(),
4350 SuppressUserConversions,
4351 /*AllowExplicit=*/false);
4352 }
4353
4354 // Otherwise, we bind the reference to a temporary created from the
4355 // initializer list.
4356 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4357 InOverloadResolution,
4358 AllowObjCWritebackConversion);
4359 if (Result.isFailure())
4360 return Result;
4361 assert(!Result.isEllipsis() &&
4362 "Sub-initialization cannot result in ellipsis conversion.");
4363
4364 // Can we even bind to a temporary?
4365 if (ToType->isRValueReferenceType() ||
4366 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4367 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4368 Result.UserDefined.After;
4369 SCS.ReferenceBinding = true;
4370 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4371 SCS.BindsToRvalue = true;
4372 SCS.BindsToFunctionLvalue = false;
4373 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4374 SCS.ObjCLifetimeConversionBinding = false;
4375 } else
4376 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4377 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004378 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004379 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004380
4381 // C++11 [over.ics.list]p6:
4382 // Otherwise, if the parameter type is not a class:
4383 if (!ToType->isRecordType()) {
4384 // - if the initializer list has one element, the implicit conversion
4385 // sequence is the one required to convert the element to the
4386 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004387 unsigned NumInits = From->getNumInits();
4388 if (NumInits == 1)
4389 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4390 SuppressUserConversions,
4391 InOverloadResolution,
4392 AllowObjCWritebackConversion);
4393 // - if the initializer list has no elements, the implicit conversion
4394 // sequence is the identity conversion.
4395 else if (NumInits == 0) {
4396 Result.setStandard();
4397 Result.Standard.setAsIdentityConversion();
4398 }
4399 return Result;
4400 }
4401
4402 // C++11 [over.ics.list]p7:
4403 // In all cases other than those enumerated above, no conversion is possible
4404 return Result;
4405}
4406
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004407/// TryCopyInitialization - Try to copy-initialize a value of type
4408/// ToType from the expression From. Return the implicit conversion
4409/// sequence required to pass this argument, which may be a bad
4410/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004411/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004412/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004413static ImplicitConversionSequence
4414TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004416 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004417 bool AllowObjCWritebackConversion,
4418 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004419 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4420 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4421 InOverloadResolution,AllowObjCWritebackConversion);
4422
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004423 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004424 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004425 /*FIXME:*/From->getLocStart(),
4426 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004427 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004428
John McCall5c32be02010-08-24 20:38:10 +00004429 return TryImplicitConversion(S, From, ToType,
4430 SuppressUserConversions,
4431 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004432 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004433 /*CStyle=*/false,
4434 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004435}
4436
Anna Zaks1b068122011-07-28 19:46:48 +00004437static bool TryCopyInitialization(const CanQualType FromQTy,
4438 const CanQualType ToQTy,
4439 Sema &S,
4440 SourceLocation Loc,
4441 ExprValueKind FromVK) {
4442 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4443 ImplicitConversionSequence ICS =
4444 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4445
4446 return !ICS.isBad();
4447}
4448
Douglas Gregor436424c2008-11-18 23:14:02 +00004449/// TryObjectArgumentInitialization - Try to initialize the object
4450/// parameter of the given member function (@c Method) from the
4451/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004452static ImplicitConversionSequence
4453TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004454 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004455 CXXMethodDecl *Method,
4456 CXXRecordDecl *ActingContext) {
4457 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004458 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4459 // const volatile object.
4460 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4461 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004462 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004463
4464 // Set up the conversion sequence as a "bad" conversion, to allow us
4465 // to exit early.
4466 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004467
4468 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004469 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004470 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004471 FromType = PT->getPointeeType();
4472
Douglas Gregor02824322011-01-26 19:30:28 +00004473 // When we had a pointer, it's implicitly dereferenced, so we
4474 // better have an lvalue.
4475 assert(FromClassification.isLValue());
4476 }
4477
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004478 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004479
Douglas Gregor02824322011-01-26 19:30:28 +00004480 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004482 // parameter is
4483 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004484 // - "lvalue reference to cv X" for functions declared without a
4485 // ref-qualifier or with the & ref-qualifier
4486 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004487 // ref-qualifier
4488 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004490 // cv-qualification on the member function declaration.
4491 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004493 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004494 // (C++ [over.match.funcs]p5). We perform a simplified version of
4495 // reference binding here, that allows class rvalues to bind to
4496 // non-constant references.
4497
Douglas Gregor02824322011-01-26 19:30:28 +00004498 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004499 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004501 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004502 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004503 ICS.setBad(BadConversionSequence::bad_qualifiers,
4504 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004505 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004506 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004507
4508 // Check that we have either the same type or a derived type. It
4509 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004510 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004511 ImplicitConversionKind SecondKind;
4512 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4513 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004514 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004515 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004516 else {
John McCall65eb8792010-02-25 01:37:24 +00004517 ICS.setBad(BadConversionSequence::unrelated_class,
4518 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004519 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004520 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004521
Douglas Gregor02824322011-01-26 19:30:28 +00004522 // Check the ref-qualifier.
4523 switch (Method->getRefQualifier()) {
4524 case RQ_None:
4525 // Do nothing; we don't care about lvalueness or rvalueness.
4526 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527
Douglas Gregor02824322011-01-26 19:30:28 +00004528 case RQ_LValue:
4529 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4530 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004532 ImplicitParamType);
4533 return ICS;
4534 }
4535 break;
4536
4537 case RQ_RValue:
4538 if (!FromClassification.isRValue()) {
4539 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004541 ImplicitParamType);
4542 return ICS;
4543 }
4544 break;
4545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Douglas Gregor436424c2008-11-18 23:14:02 +00004547 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004548 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004549 ICS.Standard.setAsIdentityConversion();
4550 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004551 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004552 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004553 ICS.Standard.ReferenceBinding = true;
4554 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004556 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004557 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4558 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4559 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004560 return ICS;
4561}
4562
4563/// PerformObjectArgumentInitialization - Perform initialization of
4564/// the implicit object parameter for the given Method with the given
4565/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004566ExprResult
4567Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004569 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004570 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004571 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004572 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004573 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004574
Douglas Gregor02824322011-01-26 19:30:28 +00004575 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004576 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004577 FromRecordType = PT->getPointeeType();
4578 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004579 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004580 } else {
4581 FromRecordType = From->getType();
4582 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004583 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004584 }
4585
John McCall6e9f8f62009-12-03 04:06:58 +00004586 // Note that we always use the true parent context when performing
4587 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004588 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004589 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4590 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004591 if (ICS.isBad()) {
4592 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4593 Qualifiers FromQs = FromRecordType.getQualifiers();
4594 Qualifiers ToQs = DestType.getQualifiers();
4595 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4596 if (CVR) {
4597 Diag(From->getSourceRange().getBegin(),
4598 diag::err_member_function_call_bad_cvr)
4599 << Method->getDeclName() << FromRecordType << (CVR - 1)
4600 << From->getSourceRange();
4601 Diag(Method->getLocation(), diag::note_previous_decl)
4602 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004603 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004604 }
4605 }
4606
Douglas Gregor436424c2008-11-18 23:14:02 +00004607 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004608 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004609 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
John Wiegley01296292011-04-08 18:41:53 +00004612 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4613 ExprResult FromRes =
4614 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4615 if (FromRes.isInvalid())
4616 return ExprError();
4617 From = FromRes.take();
4618 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004619
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004620 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004621 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004622 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004623 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004624}
4625
Douglas Gregor5fb53972009-01-14 15:45:31 +00004626/// TryContextuallyConvertToBool - Attempt to contextually convert the
4627/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004628static ImplicitConversionSequence
4629TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004630 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004631 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004632 // FIXME: Are these flags correct?
4633 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004634 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004635 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004636 /*CStyle=*/false,
4637 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004638}
4639
4640/// PerformContextuallyConvertToBool - Perform a contextual conversion
4641/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004642ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004643 if (checkPlaceholderForOverload(*this, From))
4644 return ExprError();
4645
John McCall5c32be02010-08-24 20:38:10 +00004646 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004647 if (!ICS.isBad())
4648 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Fariborz Jahanian76197412009-11-18 18:26:29 +00004650 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004651 return Diag(From->getSourceRange().getBegin(),
4652 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004653 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004654 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004655}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Richard Smithf8379a02012-01-18 23:55:52 +00004657/// Check that the specified conversion is permitted in a converted constant
4658/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4659/// is acceptable.
4660static bool CheckConvertedConstantConversions(Sema &S,
4661 StandardConversionSequence &SCS) {
4662 // Since we know that the target type is an integral or unscoped enumeration
4663 // type, most conversion kinds are impossible. All possible First and Third
4664 // conversions are fine.
4665 switch (SCS.Second) {
4666 case ICK_Identity:
4667 case ICK_Integral_Promotion:
4668 case ICK_Integral_Conversion:
4669 return true;
4670
4671 case ICK_Boolean_Conversion:
4672 // Conversion from an integral or unscoped enumeration type to bool is
4673 // classified as ICK_Boolean_Conversion, but it's also an integral
4674 // conversion, so it's permitted in a converted constant expression.
4675 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4676 SCS.getToType(2)->isBooleanType();
4677
4678 case ICK_Floating_Integral:
4679 case ICK_Complex_Real:
4680 return false;
4681
4682 case ICK_Lvalue_To_Rvalue:
4683 case ICK_Array_To_Pointer:
4684 case ICK_Function_To_Pointer:
4685 case ICK_NoReturn_Adjustment:
4686 case ICK_Qualification:
4687 case ICK_Compatible_Conversion:
4688 case ICK_Vector_Conversion:
4689 case ICK_Vector_Splat:
4690 case ICK_Derived_To_Base:
4691 case ICK_Pointer_Conversion:
4692 case ICK_Pointer_Member:
4693 case ICK_Block_Pointer_Conversion:
4694 case ICK_Writeback_Conversion:
4695 case ICK_Floating_Promotion:
4696 case ICK_Complex_Promotion:
4697 case ICK_Complex_Conversion:
4698 case ICK_Floating_Conversion:
4699 case ICK_TransparentUnionConversion:
4700 llvm_unreachable("unexpected second conversion kind");
4701
4702 case ICK_Num_Conversion_Kinds:
4703 break;
4704 }
4705
4706 llvm_unreachable("unknown conversion kind");
4707}
4708
4709/// CheckConvertedConstantExpression - Check that the expression From is a
4710/// converted constant expression of type T, perform the conversion and produce
4711/// the converted expression, per C++11 [expr.const]p3.
4712ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4713 llvm::APSInt &Value,
4714 CCEKind CCE) {
4715 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4716 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4717
4718 if (checkPlaceholderForOverload(*this, From))
4719 return ExprError();
4720
4721 // C++11 [expr.const]p3 with proposed wording fixes:
4722 // A converted constant expression of type T is a core constant expression,
4723 // implicitly converted to a prvalue of type T, where the converted
4724 // expression is a literal constant expression and the implicit conversion
4725 // sequence contains only user-defined conversions, lvalue-to-rvalue
4726 // conversions, integral promotions, and integral conversions other than
4727 // narrowing conversions.
4728 ImplicitConversionSequence ICS =
4729 TryImplicitConversion(From, T,
4730 /*SuppressUserConversions=*/false,
4731 /*AllowExplicit=*/false,
4732 /*InOverloadResolution=*/false,
4733 /*CStyle=*/false,
4734 /*AllowObjcWritebackConversion=*/false);
4735 StandardConversionSequence *SCS = 0;
4736 switch (ICS.getKind()) {
4737 case ImplicitConversionSequence::StandardConversion:
4738 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4739 return Diag(From->getSourceRange().getBegin(),
4740 diag::err_typecheck_converted_constant_expression_disallowed)
4741 << From->getType() << From->getSourceRange() << T;
4742 SCS = &ICS.Standard;
4743 break;
4744 case ImplicitConversionSequence::UserDefinedConversion:
4745 // We are converting from class type to an integral or enumeration type, so
4746 // the Before sequence must be trivial.
4747 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4748 return Diag(From->getSourceRange().getBegin(),
4749 diag::err_typecheck_converted_constant_expression_disallowed)
4750 << From->getType() << From->getSourceRange() << T;
4751 SCS = &ICS.UserDefined.After;
4752 break;
4753 case ImplicitConversionSequence::AmbiguousConversion:
4754 case ImplicitConversionSequence::BadConversion:
4755 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4756 return Diag(From->getSourceRange().getBegin(),
4757 diag::err_typecheck_converted_constant_expression)
4758 << From->getType() << From->getSourceRange() << T;
4759 return ExprError();
4760
4761 case ImplicitConversionSequence::EllipsisConversion:
4762 llvm_unreachable("ellipsis conversion in converted constant expression");
4763 }
4764
4765 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4766 if (Result.isInvalid())
4767 return Result;
4768
4769 // Check for a narrowing implicit conversion.
4770 APValue PreNarrowingValue;
Richard Smith911e1422012-01-30 22:27:01 +00004771 bool Diagnosed = false;
Richard Smithf8379a02012-01-18 23:55:52 +00004772 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4773 case NK_Variable_Narrowing:
4774 // Implicit conversion to a narrower type, and the value is not a constant
4775 // expression. We'll diagnose this in a moment.
4776 case NK_Not_Narrowing:
4777 break;
4778
4779 case NK_Constant_Narrowing:
4780 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4781 << CCE << /*Constant*/1
4782 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smith911e1422012-01-30 22:27:01 +00004783 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004784 break;
4785
4786 case NK_Type_Narrowing:
4787 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4788 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smith911e1422012-01-30 22:27:01 +00004789 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004790 break;
4791 }
4792
4793 // Check the expression is a constant expression.
4794 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4795 Expr::EvalResult Eval;
4796 Eval.Diag = &Notes;
4797
4798 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4799 // The expression can't be folded, so we can't keep it at this position in
4800 // the AST.
4801 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004802 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004803 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004804
4805 if (Notes.empty()) {
4806 // It's a constant expression.
4807 return Result;
4808 }
Richard Smithf8379a02012-01-18 23:55:52 +00004809 }
4810
Richard Smith911e1422012-01-30 22:27:01 +00004811 // Only issue one narrowing diagnostic.
4812 if (Diagnosed)
4813 return Result;
4814
Richard Smithf8379a02012-01-18 23:55:52 +00004815 // It's not a constant expression. Produce an appropriate diagnostic.
4816 if (Notes.size() == 1 &&
4817 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4818 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4819 else {
4820 Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4821 << CCE << From->getSourceRange();
4822 for (unsigned I = 0; I < Notes.size(); ++I)
4823 Diag(Notes[I].first, Notes[I].second);
4824 }
Richard Smith911e1422012-01-30 22:27:01 +00004825 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004826}
4827
John McCallfec112d2011-09-09 06:11:02 +00004828/// dropPointerConversions - If the given standard conversion sequence
4829/// involves any pointer conversions, remove them. This may change
4830/// the result type of the conversion sequence.
4831static void dropPointerConversion(StandardConversionSequence &SCS) {
4832 if (SCS.Second == ICK_Pointer_Conversion) {
4833 SCS.Second = ICK_Identity;
4834 SCS.Third = ICK_Identity;
4835 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4836 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004837}
John McCall5c32be02010-08-24 20:38:10 +00004838
John McCallfec112d2011-09-09 06:11:02 +00004839/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4840/// convert the expression From to an Objective-C pointer type.
4841static ImplicitConversionSequence
4842TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4843 // Do an implicit conversion to 'id'.
4844 QualType Ty = S.Context.getObjCIdType();
4845 ImplicitConversionSequence ICS
4846 = TryImplicitConversion(S, From, Ty,
4847 // FIXME: Are these flags correct?
4848 /*SuppressUserConversions=*/false,
4849 /*AllowExplicit=*/true,
4850 /*InOverloadResolution=*/false,
4851 /*CStyle=*/false,
4852 /*AllowObjCWritebackConversion=*/false);
4853
4854 // Strip off any final conversions to 'id'.
4855 switch (ICS.getKind()) {
4856 case ImplicitConversionSequence::BadConversion:
4857 case ImplicitConversionSequence::AmbiguousConversion:
4858 case ImplicitConversionSequence::EllipsisConversion:
4859 break;
4860
4861 case ImplicitConversionSequence::UserDefinedConversion:
4862 dropPointerConversion(ICS.UserDefined.After);
4863 break;
4864
4865 case ImplicitConversionSequence::StandardConversion:
4866 dropPointerConversion(ICS.Standard);
4867 break;
4868 }
4869
4870 return ICS;
4871}
4872
4873/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4874/// conversion of the expression From to an Objective-C pointer type.
4875ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004876 if (checkPlaceholderForOverload(*this, From))
4877 return ExprError();
4878
John McCall8b07ec22010-05-15 11:32:37 +00004879 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004880 ImplicitConversionSequence ICS =
4881 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004882 if (!ICS.isBad())
4883 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004884 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004885}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004886
Richard Smith8dd34252012-02-04 07:07:42 +00004887/// Determine whether the provided type is an integral type, or an enumeration
4888/// type of a permitted flavor.
4889static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4890 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4891 : T->isIntegralOrUnscopedEnumerationType();
4892}
4893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004895/// enumeration type.
4896///
4897/// This routine will attempt to convert an expression of class type to an
4898/// integral or enumeration type, if that class type only has a single
4899/// conversion to an integral or enumeration type.
4900///
Douglas Gregor4799d032010-06-30 00:20:43 +00004901/// \param Loc The source location of the construct that requires the
4902/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004903///
Douglas Gregor4799d032010-06-30 00:20:43 +00004904/// \param FromE The expression we're converting from.
4905///
4906/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4907/// have integral or enumeration type.
4908///
4909/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4910/// incomplete class type.
4911///
4912/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4913/// explicit conversion function (because no implicit conversion functions
4914/// were available). This is a recovery mode.
4915///
4916/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4917/// showing which conversion was picked.
4918///
4919/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4920/// conversion function that could convert to integral or enumeration type.
4921///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004923/// usable conversion function.
4924///
4925/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4926/// function, which may be an extension in this case.
4927///
Richard Smith8dd34252012-02-04 07:07:42 +00004928/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4929/// enumerations should be considered.
4930///
Douglas Gregor4799d032010-06-30 00:20:43 +00004931/// \returns The expression, converted to an integral or enumeration type if
4932/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933ExprResult
John McCallb268a282010-08-23 23:25:46 +00004934Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004935 const PartialDiagnostic &NotIntDiag,
4936 const PartialDiagnostic &IncompleteDiag,
4937 const PartialDiagnostic &ExplicitConvDiag,
4938 const PartialDiagnostic &ExplicitConvNote,
4939 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004940 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004941 const PartialDiagnostic &ConvDiag,
4942 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004943 // We can't perform any more checking for type-dependent expressions.
4944 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004945 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946
Eli Friedman1da70392012-01-26 00:26:18 +00004947 // Process placeholders immediately.
4948 if (From->hasPlaceholderType()) {
4949 ExprResult result = CheckPlaceholderExpr(From);
4950 if (result.isInvalid()) return result;
4951 From = result.take();
4952 }
4953
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004954 // If the expression already has integral or enumeration type, we're golden.
4955 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00004956 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00004957 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004958
4959 // FIXME: Check for missing '()' if T is a function type?
4960
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961 // 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 +00004962 // expression of integral or enumeration type.
4963 const RecordType *RecordTy = T->getAs<RecordType>();
4964 if (!RecordTy || !getLangOptions().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00004965 if (NotIntDiag.getDiagID())
4966 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004967 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004970 // We must have a complete class type.
4971 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004972 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004974 // Look for a conversion to an integral or enumeration type.
4975 UnresolvedSet<4> ViableConversions;
4976 UnresolvedSet<4> ExplicitConversions;
4977 const UnresolvedSetImpl *Conversions
4978 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004980 bool HadMultipleCandidates = (Conversions->size() > 1);
4981
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004982 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983 E = Conversions->end();
4984 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004985 ++I) {
4986 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00004987 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
4988 if (isIntegralOrEnumerationType(
4989 Conversion->getConversionType().getNonReferenceType(),
4990 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004991 if (Conversion->isExplicit())
4992 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4993 else
4994 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4995 }
Richard Smith8dd34252012-02-04 07:07:42 +00004996 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004999 switch (ViableConversions.size()) {
5000 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005001 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005002 DeclAccessPair Found = ExplicitConversions[0];
5003 CXXConversionDecl *Conversion
5004 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005006 // The user probably meant to invoke the given explicit
5007 // conversion; use it.
5008 QualType ConvTy
5009 = Conversion->getConversionType().getNonReferenceType();
5010 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005011 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005013 Diag(Loc, ExplicitConvDiag)
5014 << T << ConvTy
5015 << FixItHint::CreateInsertion(From->getLocStart(),
5016 "static_cast<" + TypeStr + ">(")
5017 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5018 ")");
5019 Diag(Conversion->getLocation(), ExplicitConvNote)
5020 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021
5022 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005023 // explicit conversion function.
5024 if (isSFINAEContext())
5025 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005027 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005028 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5029 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005030 if (Result.isInvalid())
5031 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005032 // Record usage of conversion in an implicit cast.
5033 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5034 CK_UserDefinedConversion,
5035 Result.get(), 0,
5036 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005039 // We'll complain below about a non-integral condition type.
5040 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005042 case 1: {
5043 // Apply this conversion.
5044 DeclAccessPair Found = ViableConversions[0];
5045 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046
Douglas Gregor4799d032010-06-30 00:20:43 +00005047 CXXConversionDecl *Conversion
5048 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5049 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005051 if (ConvDiag.getDiagID()) {
5052 if (isSFINAEContext())
5053 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054
Douglas Gregor4799d032010-06-30 00:20:43 +00005055 Diag(Loc, ConvDiag)
5056 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005059 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5060 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005061 if (Result.isInvalid())
5062 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005063 // Record usage of conversion in an implicit cast.
5064 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5065 CK_UserDefinedConversion,
5066 Result.get(), 0,
5067 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005068 break;
5069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005070
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005071 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005072 if (!AmbigDiag.getDiagID())
5073 return Owned(From);
5074
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005075 Diag(Loc, AmbigDiag)
5076 << T << From->getSourceRange();
5077 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5078 CXXConversionDecl *Conv
5079 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5080 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5081 Diag(Conv->getLocation(), AmbigNote)
5082 << ConvTy->isEnumeralType() << ConvTy;
5083 }
John McCallb268a282010-08-23 23:25:46 +00005084 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Richard Smithf4c51d92012-02-04 09:53:13 +00005087 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5088 NotIntDiag.getDiagID())
5089 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005090
Eli Friedman1da70392012-01-26 00:26:18 +00005091 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005092}
5093
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005094/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005095/// candidate functions, using the given function call arguments. If
5096/// @p SuppressUserConversions, then don't allow user-defined
5097/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005098///
5099/// \para PartialOverloading true if we are performing "partial" overloading
5100/// based on an incomplete set of function arguments. This feature is used by
5101/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005102void
5103Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005104 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005105 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005106 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005107 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005108 bool PartialOverloading,
5109 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005110 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005111 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005112 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005113 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005114 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005115
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005116 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005117 if (!isa<CXXConstructorDecl>(Method)) {
5118 // If we get here, it's because we're calling a member function
5119 // that is named without a member access expression (e.g.,
5120 // "this->f") that was either written explicitly or created
5121 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005122 // function, e.g., X::f(). We use an empty type for the implied
5123 // object argument (C++ [over.call.func]p3), and the acting context
5124 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005125 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00005127 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005128 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005129 return;
5130 }
5131 // We treat a constructor like a non-member function, since its object
5132 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005133 }
5134
Douglas Gregorff7028a2009-11-13 23:59:09 +00005135 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005136 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005137
Douglas Gregor27381f32009-11-23 12:27:39 +00005138 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005139 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005140
Douglas Gregorffe14e32009-11-14 01:20:54 +00005141 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5142 // C++ [class.copy]p3:
5143 // A member function template is never instantiated to perform the copy
5144 // of a class object to an object of its class type.
5145 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005146 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005147 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005148 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5149 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005150 return;
5151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005153 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005154 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005155 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005156 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005157 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005158 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005159 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005160 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005162 unsigned NumArgsInProto = Proto->getNumArgs();
5163
5164 // (C++ 13.3.2p2): A candidate function having fewer than m
5165 // parameters is viable only if it has an ellipsis in its parameter
5166 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005168 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005169 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005170 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005171 return;
5172 }
5173
5174 // (C++ 13.3.2p2): A candidate function having more than m parameters
5175 // is viable only if the (m+1)st parameter has a default argument
5176 // (8.3.6). For the purposes of overload resolution, the
5177 // parameter list is truncated on the right, so that there are
5178 // exactly m parameters.
5179 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00005180 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005181 // Not enough arguments.
5182 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005183 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005184 return;
5185 }
5186
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005187 // (CUDA B.1): Check for invalid calls between targets.
5188 if (getLangOptions().CUDA)
5189 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5190 if (CheckCUDATarget(Caller, Function)) {
5191 Candidate.Viable = false;
5192 Candidate.FailureKind = ovl_fail_bad_target;
5193 return;
5194 }
5195
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005196 // Determine the implicit conversion sequences for each of the
5197 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005198 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5199 if (ArgIdx < NumArgsInProto) {
5200 // (C++ 13.3.2p3): for F to be a viable function, there shall
5201 // exist for each argument an implicit conversion sequence
5202 // (13.3.3.1) that converts that argument to the corresponding
5203 // parameter of F.
5204 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005205 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005206 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005208 /*InOverloadResolution=*/true,
5209 /*AllowObjCWritebackConversion=*/
Douglas Gregor6073dca2012-02-24 23:56:31 +00005210 getLangOptions().ObjCAutoRefCount,
5211 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005212 if (Candidate.Conversions[ArgIdx].isBad()) {
5213 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005214 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005215 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005216 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005217 } else {
5218 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5219 // argument for which there is no corresponding parameter is
5220 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005221 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005222 }
5223 }
5224}
5225
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005226/// \brief Add all of the function declarations in the given function set to
5227/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005228void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005229 Expr **Args, unsigned NumArgs,
5230 OverloadCandidateSet& CandidateSet,
5231 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00005232 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005233 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5234 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005235 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005236 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005237 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005238 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005239 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005240 CandidateSet, SuppressUserConversions);
5241 else
John McCalla0296f72010-03-19 07:35:19 +00005242 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005243 SuppressUserConversions);
5244 } else {
John McCalla0296f72010-03-19 07:35:19 +00005245 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005246 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5247 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005248 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005249 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00005250 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005251 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005252 Args[0]->Classify(Context),
5253 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005254 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00005255 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005256 else
John McCalla0296f72010-03-19 07:35:19 +00005257 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00005258 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005259 Args, NumArgs, CandidateSet,
5260 SuppressUserConversions);
5261 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005262 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005263}
5264
John McCallf0f1cf02009-11-17 07:50:12 +00005265/// AddMethodCandidate - Adds a named decl (which is some kind of
5266/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005267void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005268 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005269 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005270 Expr **Args, unsigned NumArgs,
5271 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005272 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005273 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005274 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005275
5276 if (isa<UsingShadowDecl>(Decl))
5277 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
John McCallf0f1cf02009-11-17 07:50:12 +00005279 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5280 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5281 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005282 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5283 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00005284 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00005285 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005286 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005287 } else {
John McCalla0296f72010-03-19 07:35:19 +00005288 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00005289 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005290 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005291 }
5292}
5293
Douglas Gregor436424c2008-11-18 23:14:02 +00005294/// AddMethodCandidate - Adds the given C++ member function to the set
5295/// of candidate functions, using the given function call arguments
5296/// and the object argument (@c Object). For example, in a call
5297/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5298/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5299/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005300/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005301void
John McCalla0296f72010-03-19 07:35:19 +00005302Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005303 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005304 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00005305 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00005306 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005307 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005308 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005309 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005310 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005311 assert(!isa<CXXConstructorDecl>(Method) &&
5312 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005313
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005314 if (!CandidateSet.isNewCandidate(Method))
5315 return;
5316
Douglas Gregor27381f32009-11-23 12:27:39 +00005317 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005318 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005319
Douglas Gregor436424c2008-11-18 23:14:02 +00005320 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005321 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005322 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005323 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005324 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005325 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005326 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00005327
5328 unsigned NumArgsInProto = Proto->getNumArgs();
5329
5330 // (C++ 13.3.2p2): A candidate function having fewer than m
5331 // parameters is viable only if it has an ellipsis in its parameter
5332 // list (8.3.5).
5333 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5334 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005335 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005336 return;
5337 }
5338
5339 // (C++ 13.3.2p2): A candidate function having more than m parameters
5340 // is viable only if the (m+1)st parameter has a default argument
5341 // (8.3.6). For the purposes of overload resolution, the
5342 // parameter list is truncated on the right, so that there are
5343 // exactly m parameters.
5344 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5345 if (NumArgs < MinRequiredArgs) {
5346 // Not enough arguments.
5347 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005348 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005349 return;
5350 }
5351
5352 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005353
John McCall6e9f8f62009-12-03 04:06:58 +00005354 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005355 // The implicit object argument is ignored.
5356 Candidate.IgnoreObjectArgument = true;
5357 else {
5358 // Determine the implicit conversion sequence for the object
5359 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005360 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005361 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5362 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005363 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005364 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005365 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005366 return;
5367 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005368 }
5369
5370 // Determine the implicit conversion sequences for each of the
5371 // arguments.
5372 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5373 if (ArgIdx < NumArgsInProto) {
5374 // (C++ 13.3.2p3): for F to be a viable function, there shall
5375 // exist for each argument an implicit conversion sequence
5376 // (13.3.3.1) that converts that argument to the corresponding
5377 // parameter of F.
5378 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005379 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005380 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005381 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005382 /*InOverloadResolution=*/true,
5383 /*AllowObjCWritebackConversion=*/
5384 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005385 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005386 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005387 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005388 break;
5389 }
5390 } else {
5391 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5392 // argument for which there is no corresponding parameter is
5393 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005394 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005395 }
5396 }
5397}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Douglas Gregor97628d62009-08-21 00:16:32 +00005399/// \brief Add a C++ member function template as a candidate to the candidate
5400/// set, using template argument deduction to produce an appropriate member
5401/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005402void
Douglas Gregor97628d62009-08-21 00:16:32 +00005403Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005404 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005405 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005406 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005407 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005408 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00005409 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005410 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005411 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005412 if (!CandidateSet.isNewCandidate(MethodTmpl))
5413 return;
5414
Douglas Gregor97628d62009-08-21 00:16:32 +00005415 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005416 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005417 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005418 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005419 // candidate functions in the usual way.113) A given name can refer to one
5420 // or more function templates and also to a set of overloaded non-template
5421 // functions. In such a case, the candidate functions generated from each
5422 // function template are combined with the set of non-template candidate
5423 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005424 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005425 FunctionDecl *Specialization = 0;
5426 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005427 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00005428 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005429 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005430 Candidate.FoundDecl = FoundDecl;
5431 Candidate.Function = MethodTmpl->getTemplatedDecl();
5432 Candidate.Viable = false;
5433 Candidate.FailureKind = ovl_fail_bad_deduction;
5434 Candidate.IsSurrogate = false;
5435 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005436 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005437 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005438 Info);
5439 return;
5440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Douglas Gregor97628d62009-08-21 00:16:32 +00005442 // Add the function template specialization produced by template argument
5443 // deduction as a candidate.
5444 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005445 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005446 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005447 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00005448 ActingContext, ObjectType, ObjectClassification,
5449 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005450}
5451
Douglas Gregor05155d82009-08-21 23:19:43 +00005452/// \brief Add a C++ function template specialization as a candidate
5453/// in the candidate set, using template argument deduction to produce
5454/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005455void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005456Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005457 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005458 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005459 Expr **Args, unsigned NumArgs,
5460 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005461 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005462 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5463 return;
5464
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005465 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005466 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005467 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005468 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005469 // candidate functions in the usual way.113) A given name can refer to one
5470 // or more function templates and also to a set of overloaded non-template
5471 // functions. In such a case, the candidate functions generated from each
5472 // function template are combined with the set of non-template candidate
5473 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005474 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005475 FunctionDecl *Specialization = 0;
5476 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00005477 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005478 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005479 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005480 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005481 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5482 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005483 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005484 Candidate.IsSurrogate = false;
5485 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005486 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005488 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005489 return;
5490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005492 // Add the function template specialization produced by template argument
5493 // deduction as a candidate.
5494 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005495 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005496 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005497}
Mike Stump11289f42009-09-09 15:08:12 +00005498
Douglas Gregora1f013e2008-11-07 22:36:19 +00005499/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005500/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005501/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005502/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005503/// (which may or may not be the same type as the type that the
5504/// conversion function produces).
5505void
5506Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005507 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005508 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005509 Expr *From, QualType ToType,
5510 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005511 assert(!Conversion->getDescribedFunctionTemplate() &&
5512 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005513 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005514 if (!CandidateSet.isNewCandidate(Conversion))
5515 return;
5516
Douglas Gregor27381f32009-11-23 12:27:39 +00005517 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005518 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005519
Douglas Gregora1f013e2008-11-07 22:36:19 +00005520 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005521 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005522 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005523 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005524 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005525 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005526 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005527 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005528 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005529 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005530 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005531
Douglas Gregor6affc782010-08-19 15:37:02 +00005532 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533 // For conversion functions, the function is considered to be a member of
5534 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005535 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005536 //
5537 // Determine the implicit conversion sequence for the implicit
5538 // object parameter.
5539 QualType ImplicitParamType = From->getType();
5540 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5541 ImplicitParamType = FromPtrType->getPointeeType();
5542 CXXRecordDecl *ConversionContext
5543 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005545 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005546 = TryObjectArgumentInitialization(*this, From->getType(),
5547 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005548 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
John McCall0d1da222010-01-12 00:44:57 +00005550 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005551 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005552 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005553 return;
5554 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005555
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005557 // derived to base as such conversions are given Conversion Rank. They only
5558 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5559 QualType FromCanon
5560 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5561 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5562 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5563 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005564 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005565 return;
5566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005567
Douglas Gregora1f013e2008-11-07 22:36:19 +00005568 // To determine what the conversion from the result of calling the
5569 // conversion function to the type we're eventually trying to
5570 // convert to (ToType), we need to synthesize a call to the
5571 // conversion function and attempt copy initialization from it. This
5572 // makes sure that we get the right semantics with respect to
5573 // lvalues/rvalues and the type. Fortunately, we can allocate this
5574 // call on the stack and we don't need its arguments to be
5575 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005576 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005577 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005578 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5579 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005580 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005581 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005582
Richard Smith48d24642011-07-13 22:53:21 +00005583 QualType ConversionType = Conversion->getConversionType();
5584 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005585 Candidate.Viable = false;
5586 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5587 return;
5588 }
5589
Richard Smith48d24642011-07-13 22:53:21 +00005590 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005591
Mike Stump11289f42009-09-09 15:08:12 +00005592 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005593 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5594 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005595 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005596 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005597 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005598 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005599 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005600 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005601 /*InOverloadResolution=*/false,
5602 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005603
John McCall0d1da222010-01-12 00:44:57 +00005604 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005605 case ImplicitConversionSequence::StandardConversion:
5606 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005608 // C++ [over.ics.user]p3:
5609 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005611 // shall have exact match rank.
5612 if (Conversion->getPrimaryTemplate() &&
5613 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5614 Candidate.Viable = false;
5615 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Douglas Gregorcba72b12011-01-21 05:18:22 +00005618 // C++0x [dcl.init.ref]p5:
5619 // In the second case, if the reference is an rvalue reference and
5620 // the second standard conversion sequence of the user-defined
5621 // conversion sequence includes an lvalue-to-rvalue conversion, the
5622 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005624 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5625 Candidate.Viable = false;
5626 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5627 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005628 break;
5629
5630 case ImplicitConversionSequence::BadConversion:
5631 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005632 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005633 break;
5634
5635 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005636 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005637 "Can only end up with a standard conversion sequence or failure");
5638 }
5639}
5640
Douglas Gregor05155d82009-08-21 23:19:43 +00005641/// \brief Adds a conversion function template specialization
5642/// candidate to the overload set, using template argument deduction
5643/// to deduce the template arguments of the conversion function
5644/// template from the type that we are converting to (C++
5645/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005646void
Douglas Gregor05155d82009-08-21 23:19:43 +00005647Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005648 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005649 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005650 Expr *From, QualType ToType,
5651 OverloadCandidateSet &CandidateSet) {
5652 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5653 "Only conversion function templates permitted here");
5654
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005655 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5656 return;
5657
John McCallbc077cf2010-02-08 23:07:23 +00005658 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005659 CXXConversionDecl *Specialization = 0;
5660 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005661 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005662 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005663 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005664 Candidate.FoundDecl = FoundDecl;
5665 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5666 Candidate.Viable = false;
5667 Candidate.FailureKind = ovl_fail_bad_deduction;
5668 Candidate.IsSurrogate = false;
5669 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005670 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005672 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005673 return;
5674 }
Mike Stump11289f42009-09-09 15:08:12 +00005675
Douglas Gregor05155d82009-08-21 23:19:43 +00005676 // Add the conversion function template specialization produced by
5677 // template argument deduction as a candidate.
5678 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005679 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005680 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005681}
5682
Douglas Gregorab7897a2008-11-19 22:57:39 +00005683/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5684/// converts the given @c Object to a function pointer via the
5685/// conversion function @c Conversion, and then attempts to call it
5686/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5687/// the type of function that we'll eventually be calling.
5688void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005689 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005690 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005691 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005692 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005693 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005694 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005695 if (!CandidateSet.isNewCandidate(Conversion))
5696 return;
5697
Douglas Gregor27381f32009-11-23 12:27:39 +00005698 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005699 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005700
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005701 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005702 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005703 Candidate.Function = 0;
5704 Candidate.Surrogate = Conversion;
5705 Candidate.Viable = true;
5706 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005707 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005708 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005709
5710 // Determine the implicit conversion sequence for the implicit
5711 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005712 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005714 Object->Classify(Context),
5715 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005716 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005717 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005718 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005719 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005720 return;
5721 }
5722
5723 // The first conversion is actually a user-defined conversion whose
5724 // first conversion is ObjectInit's standard conversion (which is
5725 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005726 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005727 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005728 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005729 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005730 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005731 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005732 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005733 = Candidate.Conversions[0].UserDefined.Before;
5734 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5735
Mike Stump11289f42009-09-09 15:08:12 +00005736 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005737 unsigned NumArgsInProto = Proto->getNumArgs();
5738
5739 // (C++ 13.3.2p2): A candidate function having fewer than m
5740 // parameters is viable only if it has an ellipsis in its parameter
5741 // list (8.3.5).
5742 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5743 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005744 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005745 return;
5746 }
5747
5748 // Function types don't have any default arguments, so just check if
5749 // we have enough arguments.
5750 if (NumArgs < NumArgsInProto) {
5751 // Not enough arguments.
5752 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005753 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005754 return;
5755 }
5756
5757 // Determine the implicit conversion sequences for each of the
5758 // arguments.
5759 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5760 if (ArgIdx < NumArgsInProto) {
5761 // (C++ 13.3.2p3): for F to be a viable function, there shall
5762 // exist for each argument an implicit conversion sequence
5763 // (13.3.3.1) that converts that argument to the corresponding
5764 // parameter of F.
5765 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005766 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005767 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005768 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005769 /*InOverloadResolution=*/false,
5770 /*AllowObjCWritebackConversion=*/
5771 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005772 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005773 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005774 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005775 break;
5776 }
5777 } else {
5778 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5779 // argument for which there is no corresponding parameter is
5780 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005781 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005782 }
5783 }
5784}
5785
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005786/// \brief Add overload candidates for overloaded operators that are
5787/// member functions.
5788///
5789/// Add the overloaded operator candidates that are member functions
5790/// for the operator Op that was used in an operator expression such
5791/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5792/// CandidateSet will store the added overload candidates. (C++
5793/// [over.match.oper]).
5794void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5795 SourceLocation OpLoc,
5796 Expr **Args, unsigned NumArgs,
5797 OverloadCandidateSet& CandidateSet,
5798 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005799 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5800
5801 // C++ [over.match.oper]p3:
5802 // For a unary operator @ with an operand of a type whose
5803 // cv-unqualified version is T1, and for a binary operator @ with
5804 // a left operand of a type whose cv-unqualified version is T1 and
5805 // a right operand of a type whose cv-unqualified version is T2,
5806 // three sets of candidate functions, designated member
5807 // candidates, non-member candidates and built-in candidates, are
5808 // constructed as follows:
5809 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005810
5811 // -- If T1 is a class type, the set of member candidates is the
5812 // result of the qualified lookup of T1::operator@
5813 // (13.3.1.1.1); otherwise, the set of member candidates is
5814 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005815 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005816 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005817 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005818 return;
Mike Stump11289f42009-09-09 15:08:12 +00005819
John McCall27b18f82009-11-17 02:14:36 +00005820 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5821 LookupQualifiedName(Operators, T1Rec->getDecl());
5822 Operators.suppressDiagnostics();
5823
Mike Stump11289f42009-09-09 15:08:12 +00005824 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005825 OperEnd = Operators.end();
5826 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005827 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005828 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005830 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005831 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005832 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005833}
5834
Douglas Gregora11693b2008-11-12 17:17:38 +00005835/// AddBuiltinCandidate - Add a candidate for a built-in
5836/// operator. ResultTy and ParamTys are the result and parameter types
5837/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005838/// arguments being passed to the candidate. IsAssignmentOperator
5839/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005840/// operator. NumContextualBoolArguments is the number of arguments
5841/// (at the beginning of the argument list) that will be contextually
5842/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005843void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005844 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005845 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005846 bool IsAssignmentOperator,
5847 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005848 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005849 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005850
Douglas Gregora11693b2008-11-12 17:17:38 +00005851 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005852 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005853 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005854 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005855 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005856 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005857 Candidate.BuiltinTypes.ResultTy = ResultTy;
5858 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5859 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5860
5861 // Determine the implicit conversion sequences for each of the
5862 // arguments.
5863 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005864 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005865 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005866 // C++ [over.match.oper]p4:
5867 // For the built-in assignment operators, conversions of the
5868 // left operand are restricted as follows:
5869 // -- no temporaries are introduced to hold the left operand, and
5870 // -- no user-defined conversions are applied to the left
5871 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005872 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005873 //
5874 // We block these conversions by turning off user-defined
5875 // conversions, since that is the only way that initialization of
5876 // a reference to a non-class type can occur from something that
5877 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005878 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005879 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005880 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005881 Candidate.Conversions[ArgIdx]
5882 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005883 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005884 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005885 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005886 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005887 /*InOverloadResolution=*/false,
5888 /*AllowObjCWritebackConversion=*/
5889 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005890 }
John McCall0d1da222010-01-12 00:44:57 +00005891 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005892 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005893 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005894 break;
5895 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005896 }
5897}
5898
5899/// BuiltinCandidateTypeSet - A set of types that will be used for the
5900/// candidate operator functions for built-in operators (C++
5901/// [over.built]). The types are separated into pointer types and
5902/// enumeration types.
5903class BuiltinCandidateTypeSet {
5904 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005905 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005906
5907 /// PointerTypes - The set of pointer types that will be used in the
5908 /// built-in candidates.
5909 TypeSet PointerTypes;
5910
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005911 /// MemberPointerTypes - The set of member pointer types that will be
5912 /// used in the built-in candidates.
5913 TypeSet MemberPointerTypes;
5914
Douglas Gregora11693b2008-11-12 17:17:38 +00005915 /// EnumerationTypes - The set of enumeration types that will be
5916 /// used in the built-in candidates.
5917 TypeSet EnumerationTypes;
5918
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005919 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005920 /// candidates.
5921 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005922
5923 /// \brief A flag indicating non-record types are viable candidates
5924 bool HasNonRecordTypes;
5925
5926 /// \brief A flag indicating whether either arithmetic or enumeration types
5927 /// were present in the candidate set.
5928 bool HasArithmeticOrEnumeralTypes;
5929
Douglas Gregor80af3132011-05-21 23:15:46 +00005930 /// \brief A flag indicating whether the nullptr type was present in the
5931 /// candidate set.
5932 bool HasNullPtrType;
5933
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005934 /// Sema - The semantic analysis instance where we are building the
5935 /// candidate type set.
5936 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005937
Douglas Gregora11693b2008-11-12 17:17:38 +00005938 /// Context - The AST context in which we will build the type sets.
5939 ASTContext &Context;
5940
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005941 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5942 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005943 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005944
5945public:
5946 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005947 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005948
Mike Stump11289f42009-09-09 15:08:12 +00005949 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005950 : HasNonRecordTypes(false),
5951 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005952 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005953 SemaRef(SemaRef),
5954 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005955
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005956 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005957 SourceLocation Loc,
5958 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005959 bool AllowExplicitConversions,
5960 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005961
5962 /// pointer_begin - First pointer type found;
5963 iterator pointer_begin() { return PointerTypes.begin(); }
5964
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005965 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005966 iterator pointer_end() { return PointerTypes.end(); }
5967
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005968 /// member_pointer_begin - First member pointer type found;
5969 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5970
5971 /// member_pointer_end - Past the last member pointer type found;
5972 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5973
Douglas Gregora11693b2008-11-12 17:17:38 +00005974 /// enumeration_begin - First enumeration type found;
5975 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5976
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005977 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005978 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005979
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005980 iterator vector_begin() { return VectorTypes.begin(); }
5981 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005982
5983 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5984 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005985 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005986};
5987
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005988/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005989/// the set of pointer types along with any more-qualified variants of
5990/// that type. For example, if @p Ty is "int const *", this routine
5991/// will add "int const *", "int const volatile *", "int const
5992/// restrict *", and "int const volatile restrict *" to the set of
5993/// pointer types. Returns true if the add of @p Ty itself succeeded,
5994/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005995///
5996/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005997bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005998BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5999 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006000
Douglas Gregora11693b2008-11-12 17:17:38 +00006001 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006002 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006003 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006005 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006006 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006007 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006008 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006009 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006010 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006011 buildObjCPtr = true;
6012 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006013 else
David Blaikie83d382b2011-09-23 05:06:16 +00006014 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006015 }
6016 else
6017 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
Sebastian Redl4990a632009-11-18 20:39:26 +00006019 // Don't add qualified variants of arrays. For one, they're not allowed
6020 // (the qualifier would sink to the element type), and for another, the
6021 // only overload situation where it matters is subscript or pointer +- int,
6022 // and those shouldn't have qualifier variants anyway.
6023 if (PointeeTy->isArrayType())
6024 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006025 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006026 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006027 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006028 bool hasVolatile = VisibleQuals.hasVolatile();
6029 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006030
John McCall8ccfcb52009-09-24 19:53:00 +00006031 // Iterate through all strict supersets of BaseCVR.
6032 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6033 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006034 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6035 // in the types.
6036 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6037 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006038 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006039 if (!buildObjCPtr)
6040 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6041 else
6042 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006043 }
6044
6045 return true;
6046}
6047
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006048/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6049/// to the set of pointer types along with any more-qualified variants of
6050/// that type. For example, if @p Ty is "int const *", this routine
6051/// will add "int const *", "int const volatile *", "int const
6052/// restrict *", and "int const volatile restrict *" to the set of
6053/// pointer types. Returns true if the add of @p Ty itself succeeded,
6054/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006055///
6056/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006057bool
6058BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6059 QualType Ty) {
6060 // Insert this type.
6061 if (!MemberPointerTypes.insert(Ty))
6062 return false;
6063
John McCall8ccfcb52009-09-24 19:53:00 +00006064 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6065 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006066
John McCall8ccfcb52009-09-24 19:53:00 +00006067 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006068 // Don't add qualified variants of arrays. For one, they're not allowed
6069 // (the qualifier would sink to the element type), and for another, the
6070 // only overload situation where it matters is subscript or pointer +- int,
6071 // and those shouldn't have qualifier variants anyway.
6072 if (PointeeTy->isArrayType())
6073 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006074 const Type *ClassTy = PointerTy->getClass();
6075
6076 // Iterate through all strict supersets of the pointee type's CVR
6077 // qualifiers.
6078 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6079 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6080 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006081
John McCall8ccfcb52009-09-24 19:53:00 +00006082 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006083 MemberPointerTypes.insert(
6084 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006085 }
6086
6087 return true;
6088}
6089
Douglas Gregora11693b2008-11-12 17:17:38 +00006090/// AddTypesConvertedFrom - Add each of the types to which the type @p
6091/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006092/// primarily interested in pointer types and enumeration types. We also
6093/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006094/// AllowUserConversions is true if we should look at the conversion
6095/// functions of a class type, and AllowExplicitConversions if we
6096/// should also include the explicit conversion functions of a class
6097/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006098void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006099BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006100 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006101 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006102 bool AllowExplicitConversions,
6103 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006104 // Only deal with canonical types.
6105 Ty = Context.getCanonicalType(Ty);
6106
6107 // Look through reference types; they aren't part of the type of an
6108 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006109 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006110 Ty = RefTy->getPointeeType();
6111
John McCall33ddac02011-01-19 10:06:00 +00006112 // If we're dealing with an array type, decay to the pointer.
6113 if (Ty->isArrayType())
6114 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6115
6116 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006117 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006118
Chandler Carruth00a38332010-12-13 01:44:01 +00006119 // Flag if we ever add a non-record type.
6120 const RecordType *TyRec = Ty->getAs<RecordType>();
6121 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6122
Chandler Carruth00a38332010-12-13 01:44:01 +00006123 // Flag if we encounter an arithmetic type.
6124 HasArithmeticOrEnumeralTypes =
6125 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6126
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006127 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6128 PointerTypes.insert(Ty);
6129 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006130 // Insert our type, and its more-qualified variants, into the set
6131 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006132 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006133 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006134 } else if (Ty->isMemberPointerType()) {
6135 // Member pointers are far easier, since the pointee can't be converted.
6136 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6137 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006138 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006139 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006140 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006141 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006142 // We treat vector types as arithmetic types in many contexts as an
6143 // extension.
6144 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006145 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006146 } else if (Ty->isNullPtrType()) {
6147 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006148 } else if (AllowUserConversions && TyRec) {
6149 // No conversion functions in incomplete types.
6150 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6151 return;
Mike Stump11289f42009-09-09 15:08:12 +00006152
Chandler Carruth00a38332010-12-13 01:44:01 +00006153 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6154 const UnresolvedSetImpl *Conversions
6155 = ClassDecl->getVisibleConversionFunctions();
6156 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6157 E = Conversions->end(); I != E; ++I) {
6158 NamedDecl *D = I.getDecl();
6159 if (isa<UsingShadowDecl>(D))
6160 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006161
Chandler Carruth00a38332010-12-13 01:44:01 +00006162 // Skip conversion function templates; they don't tell us anything
6163 // about which builtin types we can convert to.
6164 if (isa<FunctionTemplateDecl>(D))
6165 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006166
Chandler Carruth00a38332010-12-13 01:44:01 +00006167 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6168 if (AllowExplicitConversions || !Conv->isExplicit()) {
6169 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6170 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006171 }
6172 }
6173 }
6174}
6175
Douglas Gregor84605ae2009-08-24 13:43:27 +00006176/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6177/// the volatile- and non-volatile-qualified assignment operators for the
6178/// given type to the candidate set.
6179static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6180 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006181 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006182 unsigned NumArgs,
6183 OverloadCandidateSet &CandidateSet) {
6184 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006185
Douglas Gregor84605ae2009-08-24 13:43:27 +00006186 // T& operator=(T&, T)
6187 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6188 ParamTypes[1] = T;
6189 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6190 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006191
Douglas Gregor84605ae2009-08-24 13:43:27 +00006192 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6193 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006194 ParamTypes[0]
6195 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006196 ParamTypes[1] = T;
6197 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006198 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006199 }
6200}
Mike Stump11289f42009-09-09 15:08:12 +00006201
Sebastian Redl1054fae2009-10-25 17:03:50 +00006202/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6203/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006204static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6205 Qualifiers VRQuals;
6206 const RecordType *TyRec;
6207 if (const MemberPointerType *RHSMPType =
6208 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006209 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006210 else
6211 TyRec = ArgExpr->getType()->getAs<RecordType>();
6212 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006213 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006214 VRQuals.addVolatile();
6215 VRQuals.addRestrict();
6216 return VRQuals;
6217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006218
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006220 if (!ClassDecl->hasDefinition())
6221 return VRQuals;
6222
John McCallad371252010-01-20 00:46:10 +00006223 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006224 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006225
John McCallad371252010-01-20 00:46:10 +00006226 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006227 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006228 NamedDecl *D = I.getDecl();
6229 if (isa<UsingShadowDecl>(D))
6230 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6231 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006232 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6233 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6234 CanTy = ResTypeRef->getPointeeType();
6235 // Need to go down the pointer/mempointer chain and add qualifiers
6236 // as see them.
6237 bool done = false;
6238 while (!done) {
6239 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6240 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006241 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006242 CanTy->getAs<MemberPointerType>())
6243 CanTy = ResTypeMPtr->getPointeeType();
6244 else
6245 done = true;
6246 if (CanTy.isVolatileQualified())
6247 VRQuals.addVolatile();
6248 if (CanTy.isRestrictQualified())
6249 VRQuals.addRestrict();
6250 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6251 return VRQuals;
6252 }
6253 }
6254 }
6255 return VRQuals;
6256}
John McCall52872982010-11-13 05:51:15 +00006257
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006258namespace {
John McCall52872982010-11-13 05:51:15 +00006259
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006260/// \brief Helper class to manage the addition of builtin operator overload
6261/// candidates. It provides shared state and utility methods used throughout
6262/// the process, as well as a helper method to add each group of builtin
6263/// operator overloads from the standard to a candidate set.
6264class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006265 // Common instance state available to all overload candidate addition methods.
6266 Sema &S;
6267 Expr **Args;
6268 unsigned NumArgs;
6269 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006270 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006271 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006272 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006273
Chandler Carruthc6586e52010-12-12 10:35:00 +00006274 // Define some constants used to index and iterate over the arithemetic types
6275 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006276 // The "promoted arithmetic types" are the arithmetic
6277 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006278 static const unsigned FirstIntegralType = 3;
6279 static const unsigned LastIntegralType = 18;
6280 static const unsigned FirstPromotedIntegralType = 3,
6281 LastPromotedIntegralType = 9;
6282 static const unsigned FirstPromotedArithmeticType = 0,
6283 LastPromotedArithmeticType = 9;
6284 static const unsigned NumArithmeticTypes = 18;
6285
Chandler Carruthc6586e52010-12-12 10:35:00 +00006286 /// \brief Get the canonical type for a given arithmetic type index.
6287 CanQualType getArithmeticType(unsigned index) {
6288 assert(index < NumArithmeticTypes);
6289 static CanQualType ASTContext::* const
6290 ArithmeticTypes[NumArithmeticTypes] = {
6291 // Start of promoted types.
6292 &ASTContext::FloatTy,
6293 &ASTContext::DoubleTy,
6294 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006295
Chandler Carruthc6586e52010-12-12 10:35:00 +00006296 // Start of integral types.
6297 &ASTContext::IntTy,
6298 &ASTContext::LongTy,
6299 &ASTContext::LongLongTy,
6300 &ASTContext::UnsignedIntTy,
6301 &ASTContext::UnsignedLongTy,
6302 &ASTContext::UnsignedLongLongTy,
6303 // End of promoted types.
6304
6305 &ASTContext::BoolTy,
6306 &ASTContext::CharTy,
6307 &ASTContext::WCharTy,
6308 &ASTContext::Char16Ty,
6309 &ASTContext::Char32Ty,
6310 &ASTContext::SignedCharTy,
6311 &ASTContext::ShortTy,
6312 &ASTContext::UnsignedCharTy,
6313 &ASTContext::UnsignedShortTy,
6314 // End of integral types.
6315 // FIXME: What about complex?
6316 };
6317 return S.Context.*ArithmeticTypes[index];
6318 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006319
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006320 /// \brief Gets the canonical type resulting from the usual arithemetic
6321 /// converions for the given arithmetic types.
6322 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6323 // Accelerator table for performing the usual arithmetic conversions.
6324 // The rules are basically:
6325 // - if either is floating-point, use the wider floating-point
6326 // - if same signedness, use the higher rank
6327 // - if same size, use unsigned of the higher rank
6328 // - use the larger type
6329 // These rules, together with the axiom that higher ranks are
6330 // never smaller, are sufficient to precompute all of these results
6331 // *except* when dealing with signed types of higher rank.
6332 // (we could precompute SLL x UI for all known platforms, but it's
6333 // better not to make any assumptions).
6334 enum PromotedType {
6335 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6336 };
6337 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6338 [LastPromotedArithmeticType] = {
6339 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6340 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6341 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6342 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6343 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6344 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6345 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6346 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6347 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6348 };
6349
6350 assert(L < LastPromotedArithmeticType);
6351 assert(R < LastPromotedArithmeticType);
6352 int Idx = ConversionsTable[L][R];
6353
6354 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006355 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006356
6357 // Slow path: we need to compare widths.
6358 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006359 CanQualType LT = getArithmeticType(L),
6360 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006361 unsigned LW = S.Context.getIntWidth(LT),
6362 RW = S.Context.getIntWidth(RT);
6363
6364 // If they're different widths, use the signed type.
6365 if (LW > RW) return LT;
6366 else if (LW < RW) return RT;
6367
6368 // Otherwise, use the unsigned type of the signed type's rank.
6369 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6370 assert(L == SLL || R == SLL);
6371 return S.Context.UnsignedLongLongTy;
6372 }
6373
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006374 /// \brief Helper method to factor out the common pattern of adding overloads
6375 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006376 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6377 bool HasVolatile) {
6378 QualType ParamTypes[2] = {
6379 S.Context.getLValueReferenceType(CandidateTy),
6380 S.Context.IntTy
6381 };
6382
6383 // Non-volatile version.
6384 if (NumArgs == 1)
6385 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6386 else
6387 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6388
6389 // Use a heuristic to reduce number of builtin candidates in the set:
6390 // add volatile version only if there are conversions to a volatile type.
6391 if (HasVolatile) {
6392 ParamTypes[0] =
6393 S.Context.getLValueReferenceType(
6394 S.Context.getVolatileType(CandidateTy));
6395 if (NumArgs == 1)
6396 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6397 else
6398 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6399 }
6400 }
6401
6402public:
6403 BuiltinOperatorOverloadBuilder(
6404 Sema &S, Expr **Args, unsigned NumArgs,
6405 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006406 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006407 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006408 OverloadCandidateSet &CandidateSet)
6409 : S(S), Args(Args), NumArgs(NumArgs),
6410 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006411 HasArithmeticOrEnumeralCandidateType(
6412 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006413 CandidateTypes(CandidateTypes),
6414 CandidateSet(CandidateSet) {
6415 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006416 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006417 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006418 assert(getArithmeticType(LastPromotedIntegralType - 1)
6419 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006420 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006421 assert(getArithmeticType(FirstPromotedArithmeticType)
6422 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006423 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006424 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6425 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006426 "Invalid last promoted arithmetic type");
6427 }
6428
6429 // C++ [over.built]p3:
6430 //
6431 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6432 // is either volatile or empty, there exist candidate operator
6433 // functions of the form
6434 //
6435 // VQ T& operator++(VQ T&);
6436 // T operator++(VQ T&, int);
6437 //
6438 // C++ [over.built]p4:
6439 //
6440 // For every pair (T, VQ), where T is an arithmetic type other
6441 // than bool, and VQ is either volatile or empty, there exist
6442 // candidate operator functions of the form
6443 //
6444 // VQ T& operator--(VQ T&);
6445 // T operator--(VQ T&, int);
6446 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006447 if (!HasArithmeticOrEnumeralCandidateType)
6448 return;
6449
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006450 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6451 Arith < NumArithmeticTypes; ++Arith) {
6452 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006453 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006454 VisibleTypeConversionsQuals.hasVolatile());
6455 }
6456 }
6457
6458 // C++ [over.built]p5:
6459 //
6460 // For every pair (T, VQ), where T is a cv-qualified or
6461 // cv-unqualified object type, and VQ is either volatile or
6462 // empty, there exist candidate operator functions of the form
6463 //
6464 // T*VQ& operator++(T*VQ&);
6465 // T*VQ& operator--(T*VQ&);
6466 // T* operator++(T*VQ&, int);
6467 // T* operator--(T*VQ&, int);
6468 void addPlusPlusMinusMinusPointerOverloads() {
6469 for (BuiltinCandidateTypeSet::iterator
6470 Ptr = CandidateTypes[0].pointer_begin(),
6471 PtrEnd = CandidateTypes[0].pointer_end();
6472 Ptr != PtrEnd; ++Ptr) {
6473 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006474 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006475 continue;
6476
6477 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6478 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6479 VisibleTypeConversionsQuals.hasVolatile()));
6480 }
6481 }
6482
6483 // C++ [over.built]p6:
6484 // For every cv-qualified or cv-unqualified object type T, there
6485 // exist candidate operator functions of the form
6486 //
6487 // T& operator*(T*);
6488 //
6489 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006491 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006492 // T& operator*(T*);
6493 void addUnaryStarPointerOverloads() {
6494 for (BuiltinCandidateTypeSet::iterator
6495 Ptr = CandidateTypes[0].pointer_begin(),
6496 PtrEnd = CandidateTypes[0].pointer_end();
6497 Ptr != PtrEnd; ++Ptr) {
6498 QualType ParamTy = *Ptr;
6499 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006500 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6501 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006502
Douglas Gregor02824322011-01-26 19:30:28 +00006503 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6504 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6505 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006506
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006507 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6508 &ParamTy, Args, 1, CandidateSet);
6509 }
6510 }
6511
6512 // C++ [over.built]p9:
6513 // For every promoted arithmetic type T, there exist candidate
6514 // operator functions of the form
6515 //
6516 // T operator+(T);
6517 // T operator-(T);
6518 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006519 if (!HasArithmeticOrEnumeralCandidateType)
6520 return;
6521
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006522 for (unsigned Arith = FirstPromotedArithmeticType;
6523 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006524 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006525 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6526 }
6527
6528 // Extension: We also add these operators for vector types.
6529 for (BuiltinCandidateTypeSet::iterator
6530 Vec = CandidateTypes[0].vector_begin(),
6531 VecEnd = CandidateTypes[0].vector_end();
6532 Vec != VecEnd; ++Vec) {
6533 QualType VecTy = *Vec;
6534 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6535 }
6536 }
6537
6538 // C++ [over.built]p8:
6539 // For every type T, there exist candidate operator functions of
6540 // the form
6541 //
6542 // T* operator+(T*);
6543 void addUnaryPlusPointerOverloads() {
6544 for (BuiltinCandidateTypeSet::iterator
6545 Ptr = CandidateTypes[0].pointer_begin(),
6546 PtrEnd = CandidateTypes[0].pointer_end();
6547 Ptr != PtrEnd; ++Ptr) {
6548 QualType ParamTy = *Ptr;
6549 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6550 }
6551 }
6552
6553 // C++ [over.built]p10:
6554 // For every promoted integral type T, there exist candidate
6555 // operator functions of the form
6556 //
6557 // T operator~(T);
6558 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006559 if (!HasArithmeticOrEnumeralCandidateType)
6560 return;
6561
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006562 for (unsigned Int = FirstPromotedIntegralType;
6563 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006564 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006565 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6566 }
6567
6568 // Extension: We also add this operator for vector types.
6569 for (BuiltinCandidateTypeSet::iterator
6570 Vec = CandidateTypes[0].vector_begin(),
6571 VecEnd = CandidateTypes[0].vector_end();
6572 Vec != VecEnd; ++Vec) {
6573 QualType VecTy = *Vec;
6574 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6575 }
6576 }
6577
6578 // C++ [over.match.oper]p16:
6579 // For every pointer to member type T, there exist candidate operator
6580 // functions of the form
6581 //
6582 // bool operator==(T,T);
6583 // bool operator!=(T,T);
6584 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6585 /// Set of (canonical) types that we've already handled.
6586 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6587
6588 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6589 for (BuiltinCandidateTypeSet::iterator
6590 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6591 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6592 MemPtr != MemPtrEnd;
6593 ++MemPtr) {
6594 // Don't add the same builtin candidate twice.
6595 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6596 continue;
6597
6598 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6599 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6600 CandidateSet);
6601 }
6602 }
6603 }
6604
6605 // C++ [over.built]p15:
6606 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006607 // For every T, where T is an enumeration type, a pointer type, or
6608 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006609 //
6610 // bool operator<(T, T);
6611 // bool operator>(T, T);
6612 // bool operator<=(T, T);
6613 // bool operator>=(T, T);
6614 // bool operator==(T, T);
6615 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006616 void addRelationalPointerOrEnumeralOverloads() {
6617 // C++ [over.built]p1:
6618 // If there is a user-written candidate with the same name and parameter
6619 // types as a built-in candidate operator function, the built-in operator
6620 // function is hidden and is not included in the set of candidate
6621 // functions.
6622 //
6623 // The text is actually in a note, but if we don't implement it then we end
6624 // up with ambiguities when the user provides an overloaded operator for
6625 // an enumeration type. Note that only enumeration types have this problem,
6626 // so we track which enumeration types we've seen operators for. Also, the
6627 // only other overloaded operator with enumeration argumenst, operator=,
6628 // cannot be overloaded for enumeration types, so this is the only place
6629 // where we must suppress candidates like this.
6630 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6631 UserDefinedBinaryOperators;
6632
6633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6634 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6635 CandidateTypes[ArgIdx].enumeration_end()) {
6636 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6637 CEnd = CandidateSet.end();
6638 C != CEnd; ++C) {
6639 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6640 continue;
6641
6642 QualType FirstParamType =
6643 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6644 QualType SecondParamType =
6645 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6646
6647 // Skip if either parameter isn't of enumeral type.
6648 if (!FirstParamType->isEnumeralType() ||
6649 !SecondParamType->isEnumeralType())
6650 continue;
6651
6652 // Add this operator to the set of known user-defined operators.
6653 UserDefinedBinaryOperators.insert(
6654 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6655 S.Context.getCanonicalType(SecondParamType)));
6656 }
6657 }
6658 }
6659
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006660 /// Set of (canonical) types that we've already handled.
6661 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6662
6663 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6664 for (BuiltinCandidateTypeSet::iterator
6665 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6666 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6667 Ptr != PtrEnd; ++Ptr) {
6668 // Don't add the same builtin candidate twice.
6669 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6670 continue;
6671
6672 QualType ParamTypes[2] = { *Ptr, *Ptr };
6673 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6674 CandidateSet);
6675 }
6676 for (BuiltinCandidateTypeSet::iterator
6677 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6678 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6679 Enum != EnumEnd; ++Enum) {
6680 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6681
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006682 // Don't add the same builtin candidate twice, or if a user defined
6683 // candidate exists.
6684 if (!AddedTypes.insert(CanonType) ||
6685 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6686 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006687 continue;
6688
6689 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006690 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6691 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006692 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006693
6694 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6695 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6696 if (AddedTypes.insert(NullPtrTy) &&
6697 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6698 NullPtrTy))) {
6699 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6700 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6701 CandidateSet);
6702 }
6703 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006704 }
6705 }
6706
6707 // C++ [over.built]p13:
6708 //
6709 // For every cv-qualified or cv-unqualified object type T
6710 // there exist candidate operator functions of the form
6711 //
6712 // T* operator+(T*, ptrdiff_t);
6713 // T& operator[](T*, ptrdiff_t); [BELOW]
6714 // T* operator-(T*, ptrdiff_t);
6715 // T* operator+(ptrdiff_t, T*);
6716 // T& operator[](ptrdiff_t, T*); [BELOW]
6717 //
6718 // C++ [over.built]p14:
6719 //
6720 // For every T, where T is a pointer to object type, there
6721 // exist candidate operator functions of the form
6722 //
6723 // ptrdiff_t operator-(T, T);
6724 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6725 /// Set of (canonical) types that we've already handled.
6726 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6727
6728 for (int Arg = 0; Arg < 2; ++Arg) {
6729 QualType AsymetricParamTypes[2] = {
6730 S.Context.getPointerDiffType(),
6731 S.Context.getPointerDiffType(),
6732 };
6733 for (BuiltinCandidateTypeSet::iterator
6734 Ptr = CandidateTypes[Arg].pointer_begin(),
6735 PtrEnd = CandidateTypes[Arg].pointer_end();
6736 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006737 QualType PointeeTy = (*Ptr)->getPointeeType();
6738 if (!PointeeTy->isObjectType())
6739 continue;
6740
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006741 AsymetricParamTypes[Arg] = *Ptr;
6742 if (Arg == 0 || Op == OO_Plus) {
6743 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6744 // T* operator+(ptrdiff_t, T*);
6745 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6746 CandidateSet);
6747 }
6748 if (Op == OO_Minus) {
6749 // ptrdiff_t operator-(T, T);
6750 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6751 continue;
6752
6753 QualType ParamTypes[2] = { *Ptr, *Ptr };
6754 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6755 Args, 2, CandidateSet);
6756 }
6757 }
6758 }
6759 }
6760
6761 // C++ [over.built]p12:
6762 //
6763 // For every pair of promoted arithmetic types L and R, there
6764 // exist candidate operator functions of the form
6765 //
6766 // LR operator*(L, R);
6767 // LR operator/(L, R);
6768 // LR operator+(L, R);
6769 // LR operator-(L, R);
6770 // bool operator<(L, R);
6771 // bool operator>(L, R);
6772 // bool operator<=(L, R);
6773 // bool operator>=(L, R);
6774 // bool operator==(L, R);
6775 // bool operator!=(L, R);
6776 //
6777 // where LR is the result of the usual arithmetic conversions
6778 // between types L and R.
6779 //
6780 // C++ [over.built]p24:
6781 //
6782 // For every pair of promoted arithmetic types L and R, there exist
6783 // candidate operator functions of the form
6784 //
6785 // LR operator?(bool, L, R);
6786 //
6787 // where LR is the result of the usual arithmetic conversions
6788 // between types L and R.
6789 // Our candidates ignore the first parameter.
6790 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006791 if (!HasArithmeticOrEnumeralCandidateType)
6792 return;
6793
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006794 for (unsigned Left = FirstPromotedArithmeticType;
6795 Left < LastPromotedArithmeticType; ++Left) {
6796 for (unsigned Right = FirstPromotedArithmeticType;
6797 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006798 QualType LandR[2] = { getArithmeticType(Left),
6799 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006800 QualType Result =
6801 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006802 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006803 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6804 }
6805 }
6806
6807 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6808 // conditional operator for vector types.
6809 for (BuiltinCandidateTypeSet::iterator
6810 Vec1 = CandidateTypes[0].vector_begin(),
6811 Vec1End = CandidateTypes[0].vector_end();
6812 Vec1 != Vec1End; ++Vec1) {
6813 for (BuiltinCandidateTypeSet::iterator
6814 Vec2 = CandidateTypes[1].vector_begin(),
6815 Vec2End = CandidateTypes[1].vector_end();
6816 Vec2 != Vec2End; ++Vec2) {
6817 QualType LandR[2] = { *Vec1, *Vec2 };
6818 QualType Result = S.Context.BoolTy;
6819 if (!isComparison) {
6820 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6821 Result = *Vec1;
6822 else
6823 Result = *Vec2;
6824 }
6825
6826 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6827 }
6828 }
6829 }
6830
6831 // C++ [over.built]p17:
6832 //
6833 // For every pair of promoted integral types L and R, there
6834 // exist candidate operator functions of the form
6835 //
6836 // LR operator%(L, R);
6837 // LR operator&(L, R);
6838 // LR operator^(L, R);
6839 // LR operator|(L, R);
6840 // L operator<<(L, R);
6841 // L operator>>(L, R);
6842 //
6843 // where LR is the result of the usual arithmetic conversions
6844 // between types L and R.
6845 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006846 if (!HasArithmeticOrEnumeralCandidateType)
6847 return;
6848
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006849 for (unsigned Left = FirstPromotedIntegralType;
6850 Left < LastPromotedIntegralType; ++Left) {
6851 for (unsigned Right = FirstPromotedIntegralType;
6852 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006853 QualType LandR[2] = { getArithmeticType(Left),
6854 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006855 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6856 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006857 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006858 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6859 }
6860 }
6861 }
6862
6863 // C++ [over.built]p20:
6864 //
6865 // For every pair (T, VQ), where T is an enumeration or
6866 // pointer to member type and VQ is either volatile or
6867 // empty, there exist candidate operator functions of the form
6868 //
6869 // VQ T& operator=(VQ T&, T);
6870 void addAssignmentMemberPointerOrEnumeralOverloads() {
6871 /// Set of (canonical) types that we've already handled.
6872 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6873
6874 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6875 for (BuiltinCandidateTypeSet::iterator
6876 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6877 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6878 Enum != EnumEnd; ++Enum) {
6879 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6880 continue;
6881
6882 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6883 CandidateSet);
6884 }
6885
6886 for (BuiltinCandidateTypeSet::iterator
6887 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6888 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6889 MemPtr != MemPtrEnd; ++MemPtr) {
6890 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6891 continue;
6892
6893 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6894 CandidateSet);
6895 }
6896 }
6897 }
6898
6899 // C++ [over.built]p19:
6900 //
6901 // For every pair (T, VQ), where T is any type and VQ is either
6902 // volatile or empty, there exist candidate operator functions
6903 // of the form
6904 //
6905 // T*VQ& operator=(T*VQ&, T*);
6906 //
6907 // C++ [over.built]p21:
6908 //
6909 // For every pair (T, VQ), where T is a cv-qualified or
6910 // cv-unqualified object type and VQ is either volatile or
6911 // empty, there exist candidate operator functions of the form
6912 //
6913 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6914 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6915 void addAssignmentPointerOverloads(bool isEqualOp) {
6916 /// Set of (canonical) types that we've already handled.
6917 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6918
6919 for (BuiltinCandidateTypeSet::iterator
6920 Ptr = CandidateTypes[0].pointer_begin(),
6921 PtrEnd = CandidateTypes[0].pointer_end();
6922 Ptr != PtrEnd; ++Ptr) {
6923 // If this is operator=, keep track of the builtin candidates we added.
6924 if (isEqualOp)
6925 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006926 else if (!(*Ptr)->getPointeeType()->isObjectType())
6927 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006928
6929 // non-volatile version
6930 QualType ParamTypes[2] = {
6931 S.Context.getLValueReferenceType(*Ptr),
6932 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6933 };
6934 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6935 /*IsAssigmentOperator=*/ isEqualOp);
6936
6937 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6938 VisibleTypeConversionsQuals.hasVolatile()) {
6939 // volatile version
6940 ParamTypes[0] =
6941 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6942 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6943 /*IsAssigmentOperator=*/isEqualOp);
6944 }
6945 }
6946
6947 if (isEqualOp) {
6948 for (BuiltinCandidateTypeSet::iterator
6949 Ptr = CandidateTypes[1].pointer_begin(),
6950 PtrEnd = CandidateTypes[1].pointer_end();
6951 Ptr != PtrEnd; ++Ptr) {
6952 // Make sure we don't add the same candidate twice.
6953 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6954 continue;
6955
Chandler Carruth8e543b32010-12-12 08:17:55 +00006956 QualType ParamTypes[2] = {
6957 S.Context.getLValueReferenceType(*Ptr),
6958 *Ptr,
6959 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006960
6961 // non-volatile version
6962 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6963 /*IsAssigmentOperator=*/true);
6964
6965 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6966 VisibleTypeConversionsQuals.hasVolatile()) {
6967 // volatile version
6968 ParamTypes[0] =
6969 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006970 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6971 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006972 }
6973 }
6974 }
6975 }
6976
6977 // C++ [over.built]p18:
6978 //
6979 // For every triple (L, VQ, R), where L is an arithmetic type,
6980 // VQ is either volatile or empty, and R is a promoted
6981 // arithmetic type, there exist candidate operator functions of
6982 // the form
6983 //
6984 // VQ L& operator=(VQ L&, R);
6985 // VQ L& operator*=(VQ L&, R);
6986 // VQ L& operator/=(VQ L&, R);
6987 // VQ L& operator+=(VQ L&, R);
6988 // VQ L& operator-=(VQ L&, R);
6989 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006990 if (!HasArithmeticOrEnumeralCandidateType)
6991 return;
6992
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006993 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6994 for (unsigned Right = FirstPromotedArithmeticType;
6995 Right < LastPromotedArithmeticType; ++Right) {
6996 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006997 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006998
6999 // Add this built-in operator as a candidate (VQ is empty).
7000 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007001 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007002 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7003 /*IsAssigmentOperator=*/isEqualOp);
7004
7005 // Add this built-in operator as a candidate (VQ is 'volatile').
7006 if (VisibleTypeConversionsQuals.hasVolatile()) {
7007 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007008 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007009 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007010 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7011 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 /*IsAssigmentOperator=*/isEqualOp);
7013 }
7014 }
7015 }
7016
7017 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7018 for (BuiltinCandidateTypeSet::iterator
7019 Vec1 = CandidateTypes[0].vector_begin(),
7020 Vec1End = CandidateTypes[0].vector_end();
7021 Vec1 != Vec1End; ++Vec1) {
7022 for (BuiltinCandidateTypeSet::iterator
7023 Vec2 = CandidateTypes[1].vector_begin(),
7024 Vec2End = CandidateTypes[1].vector_end();
7025 Vec2 != Vec2End; ++Vec2) {
7026 QualType ParamTypes[2];
7027 ParamTypes[1] = *Vec2;
7028 // Add this built-in operator as a candidate (VQ is empty).
7029 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7030 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7031 /*IsAssigmentOperator=*/isEqualOp);
7032
7033 // Add this built-in operator as a candidate (VQ is 'volatile').
7034 if (VisibleTypeConversionsQuals.hasVolatile()) {
7035 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7036 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7038 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007039 /*IsAssigmentOperator=*/isEqualOp);
7040 }
7041 }
7042 }
7043 }
7044
7045 // C++ [over.built]p22:
7046 //
7047 // For every triple (L, VQ, R), where L is an integral type, VQ
7048 // is either volatile or empty, and R is a promoted integral
7049 // type, there exist candidate operator functions of the form
7050 //
7051 // VQ L& operator%=(VQ L&, R);
7052 // VQ L& operator<<=(VQ L&, R);
7053 // VQ L& operator>>=(VQ L&, R);
7054 // VQ L& operator&=(VQ L&, R);
7055 // VQ L& operator^=(VQ L&, R);
7056 // VQ L& operator|=(VQ L&, R);
7057 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007058 if (!HasArithmeticOrEnumeralCandidateType)
7059 return;
7060
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007061 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7062 for (unsigned Right = FirstPromotedIntegralType;
7063 Right < LastPromotedIntegralType; ++Right) {
7064 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007065 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007066
7067 // Add this built-in operator as a candidate (VQ is empty).
7068 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007069 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007070 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7071 if (VisibleTypeConversionsQuals.hasVolatile()) {
7072 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007073 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007074 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7075 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7076 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7077 CandidateSet);
7078 }
7079 }
7080 }
7081 }
7082
7083 // C++ [over.operator]p23:
7084 //
7085 // There also exist candidate operator functions of the form
7086 //
7087 // bool operator!(bool);
7088 // bool operator&&(bool, bool);
7089 // bool operator||(bool, bool);
7090 void addExclaimOverload() {
7091 QualType ParamTy = S.Context.BoolTy;
7092 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7093 /*IsAssignmentOperator=*/false,
7094 /*NumContextualBoolArguments=*/1);
7095 }
7096 void addAmpAmpOrPipePipeOverload() {
7097 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7098 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7099 /*IsAssignmentOperator=*/false,
7100 /*NumContextualBoolArguments=*/2);
7101 }
7102
7103 // C++ [over.built]p13:
7104 //
7105 // For every cv-qualified or cv-unqualified object type T there
7106 // exist candidate operator functions of the form
7107 //
7108 // T* operator+(T*, ptrdiff_t); [ABOVE]
7109 // T& operator[](T*, ptrdiff_t);
7110 // T* operator-(T*, ptrdiff_t); [ABOVE]
7111 // T* operator+(ptrdiff_t, T*); [ABOVE]
7112 // T& operator[](ptrdiff_t, T*);
7113 void addSubscriptOverloads() {
7114 for (BuiltinCandidateTypeSet::iterator
7115 Ptr = CandidateTypes[0].pointer_begin(),
7116 PtrEnd = CandidateTypes[0].pointer_end();
7117 Ptr != PtrEnd; ++Ptr) {
7118 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7119 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007120 if (!PointeeType->isObjectType())
7121 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007123 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7124
7125 // T& operator[](T*, ptrdiff_t)
7126 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7127 }
7128
7129 for (BuiltinCandidateTypeSet::iterator
7130 Ptr = CandidateTypes[1].pointer_begin(),
7131 PtrEnd = CandidateTypes[1].pointer_end();
7132 Ptr != PtrEnd; ++Ptr) {
7133 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7134 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007135 if (!PointeeType->isObjectType())
7136 continue;
7137
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007138 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7139
7140 // T& operator[](ptrdiff_t, T*)
7141 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7142 }
7143 }
7144
7145 // C++ [over.built]p11:
7146 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7147 // C1 is the same type as C2 or is a derived class of C2, T is an object
7148 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7149 // there exist candidate operator functions of the form
7150 //
7151 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7152 //
7153 // where CV12 is the union of CV1 and CV2.
7154 void addArrowStarOverloads() {
7155 for (BuiltinCandidateTypeSet::iterator
7156 Ptr = CandidateTypes[0].pointer_begin(),
7157 PtrEnd = CandidateTypes[0].pointer_end();
7158 Ptr != PtrEnd; ++Ptr) {
7159 QualType C1Ty = (*Ptr);
7160 QualType C1;
7161 QualifierCollector Q1;
7162 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7163 if (!isa<RecordType>(C1))
7164 continue;
7165 // heuristic to reduce number of builtin candidates in the set.
7166 // Add volatile/restrict version only if there are conversions to a
7167 // volatile/restrict type.
7168 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7169 continue;
7170 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7171 continue;
7172 for (BuiltinCandidateTypeSet::iterator
7173 MemPtr = CandidateTypes[1].member_pointer_begin(),
7174 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7175 MemPtr != MemPtrEnd; ++MemPtr) {
7176 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7177 QualType C2 = QualType(mptr->getClass(), 0);
7178 C2 = C2.getUnqualifiedType();
7179 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7180 break;
7181 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7182 // build CV12 T&
7183 QualType T = mptr->getPointeeType();
7184 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7185 T.isVolatileQualified())
7186 continue;
7187 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7188 T.isRestrictQualified())
7189 continue;
7190 T = Q1.apply(S.Context, T);
7191 QualType ResultTy = S.Context.getLValueReferenceType(T);
7192 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7193 }
7194 }
7195 }
7196
7197 // Note that we don't consider the first argument, since it has been
7198 // contextually converted to bool long ago. The candidates below are
7199 // therefore added as binary.
7200 //
7201 // C++ [over.built]p25:
7202 // For every type T, where T is a pointer, pointer-to-member, or scoped
7203 // enumeration type, there exist candidate operator functions of the form
7204 //
7205 // T operator?(bool, T, T);
7206 //
7207 void addConditionalOperatorOverloads() {
7208 /// Set of (canonical) types that we've already handled.
7209 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7210
7211 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7212 for (BuiltinCandidateTypeSet::iterator
7213 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7214 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7215 Ptr != PtrEnd; ++Ptr) {
7216 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7217 continue;
7218
7219 QualType ParamTypes[2] = { *Ptr, *Ptr };
7220 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7221 }
7222
7223 for (BuiltinCandidateTypeSet::iterator
7224 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7225 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7226 MemPtr != MemPtrEnd; ++MemPtr) {
7227 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7228 continue;
7229
7230 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7231 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7232 }
7233
7234 if (S.getLangOptions().CPlusPlus0x) {
7235 for (BuiltinCandidateTypeSet::iterator
7236 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7237 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7238 Enum != EnumEnd; ++Enum) {
7239 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7240 continue;
7241
7242 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7243 continue;
7244
7245 QualType ParamTypes[2] = { *Enum, *Enum };
7246 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7247 }
7248 }
7249 }
7250 }
7251};
7252
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007253} // end anonymous namespace
7254
7255/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7256/// operator overloads to the candidate set (C++ [over.built]), based
7257/// on the operator @p Op and the arguments given. For example, if the
7258/// operator is a binary '+', this routine might add "int
7259/// operator+(int, int)" to cover integer addition.
7260void
7261Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7262 SourceLocation OpLoc,
7263 Expr **Args, unsigned NumArgs,
7264 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007265 // Find all of the types that the arguments can convert to, but only
7266 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007267 // that make use of these types. Also record whether we encounter non-record
7268 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007269 Qualifiers VisibleTypeConversionsQuals;
7270 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007271 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7272 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007273
7274 bool HasNonRecordCandidateType = false;
7275 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007276 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007277 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7278 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7279 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7280 OpLoc,
7281 true,
7282 (Op == OO_Exclaim ||
7283 Op == OO_AmpAmp ||
7284 Op == OO_PipePipe),
7285 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007286 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7287 CandidateTypes[ArgIdx].hasNonRecordTypes();
7288 HasArithmeticOrEnumeralCandidateType =
7289 HasArithmeticOrEnumeralCandidateType ||
7290 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007291 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007292
Chandler Carruth00a38332010-12-13 01:44:01 +00007293 // Exit early when no non-record types have been added to the candidate set
7294 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007295 //
7296 // We can't exit early for !, ||, or &&, since there we have always have
7297 // 'bool' overloads.
7298 if (!HasNonRecordCandidateType &&
7299 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007300 return;
7301
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007302 // Setup an object to manage the common state for building overloads.
7303 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7304 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007305 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 CandidateTypes, CandidateSet);
7307
7308 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007309 switch (Op) {
7310 case OO_None:
7311 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007312 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007313
Chandler Carruth5184de02010-12-12 08:51:33 +00007314 case OO_New:
7315 case OO_Delete:
7316 case OO_Array_New:
7317 case OO_Array_Delete:
7318 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007319 llvm_unreachable(
7320 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007321
7322 case OO_Comma:
7323 case OO_Arrow:
7324 // C++ [over.match.oper]p3:
7325 // -- For the operator ',', the unary operator '&', or the
7326 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007327 break;
7328
7329 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007330 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007332 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007333
7334 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007335 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007336 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007337 } else {
7338 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7339 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7340 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007341 break;
7342
Chandler Carruth5184de02010-12-12 08:51:33 +00007343 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007344 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007345 OpBuilder.addUnaryStarPointerOverloads();
7346 else
7347 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7348 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007349
Chandler Carruth5184de02010-12-12 08:51:33 +00007350 case OO_Slash:
7351 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007352 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007353
7354 case OO_PlusPlus:
7355 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7357 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007358 break;
7359
Douglas Gregor84605ae2009-08-24 13:43:27 +00007360 case OO_EqualEqual:
7361 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007362 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007363 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007364
Douglas Gregora11693b2008-11-12 17:17:38 +00007365 case OO_Less:
7366 case OO_Greater:
7367 case OO_LessEqual:
7368 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007369 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007370 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7371 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007372
Douglas Gregora11693b2008-11-12 17:17:38 +00007373 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007374 case OO_Caret:
7375 case OO_Pipe:
7376 case OO_LessLess:
7377 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007378 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007379 break;
7380
Chandler Carruth5184de02010-12-12 08:51:33 +00007381 case OO_Amp: // '&' is either unary or binary
7382 if (NumArgs == 1)
7383 // C++ [over.match.oper]p3:
7384 // -- For the operator ',', the unary operator '&', or the
7385 // operator '->', the built-in candidates set is empty.
7386 break;
7387
7388 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7389 break;
7390
7391 case OO_Tilde:
7392 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7393 break;
7394
Douglas Gregora11693b2008-11-12 17:17:38 +00007395 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007396 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007397 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007398
7399 case OO_PlusEqual:
7400 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007402 // Fall through.
7403
7404 case OO_StarEqual:
7405 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007406 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007407 break;
7408
7409 case OO_PercentEqual:
7410 case OO_LessLessEqual:
7411 case OO_GreaterGreaterEqual:
7412 case OO_AmpEqual:
7413 case OO_CaretEqual:
7414 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007415 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007416 break;
7417
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007418 case OO_Exclaim:
7419 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007420 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007421
Douglas Gregora11693b2008-11-12 17:17:38 +00007422 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007423 case OO_PipePipe:
7424 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007425 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007426
7427 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007429 break;
7430
7431 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007432 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007433 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007434
7435 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007436 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007437 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7438 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007439 }
7440}
7441
Douglas Gregore254f902009-02-04 00:32:51 +00007442/// \brief Add function candidates found via argument-dependent lookup
7443/// to the set of overloading candidates.
7444///
7445/// This routine performs argument-dependent name lookup based on the
7446/// given function name (which may also be an operator name) and adds
7447/// all of the overload candidates found by ADL to the overload
7448/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007449void
Douglas Gregore254f902009-02-04 00:32:51 +00007450Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00007451 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00007452 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007453 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007454 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007455 bool PartialOverloading,
7456 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007457 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007458
John McCall91f61fc2010-01-26 06:04:06 +00007459 // FIXME: This approach for uniquing ADL results (and removing
7460 // redundant candidates from the set) relies on pointer-equality,
7461 // which means we need to key off the canonical decl. However,
7462 // always going back to the canonical decl might not get us the
7463 // right set of default arguments. What default arguments are
7464 // we supposed to consider on ADL candidates, anyway?
7465
Douglas Gregorcabea402009-09-22 15:41:20 +00007466 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00007467 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7468 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007469
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007470 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007471 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7472 CandEnd = CandidateSet.end();
7473 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007474 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007475 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007476 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007477 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007478 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007479
7480 // For each of the ADL candidates we found, add it to the overload
7481 // set.
John McCall8fe68082010-01-26 07:16:45 +00007482 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007483 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007484 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007485 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007486 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
John McCalla0296f72010-03-19 07:35:19 +00007488 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007489 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007490 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007491 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007492 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00007493 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007494 }
Douglas Gregore254f902009-02-04 00:32:51 +00007495}
7496
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007497/// isBetterOverloadCandidate - Determines whether the first overload
7498/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007499bool
John McCall5c32be02010-08-24 20:38:10 +00007500isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007501 const OverloadCandidate &Cand1,
7502 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007503 SourceLocation Loc,
7504 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007505 // Define viable functions to be better candidates than non-viable
7506 // functions.
7507 if (!Cand2.Viable)
7508 return Cand1.Viable;
7509 else if (!Cand1.Viable)
7510 return false;
7511
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007512 // C++ [over.match.best]p1:
7513 //
7514 // -- if F is a static member function, ICS1(F) is defined such
7515 // that ICS1(F) is neither better nor worse than ICS1(G) for
7516 // any function G, and, symmetrically, ICS1(G) is neither
7517 // better nor worse than ICS1(F).
7518 unsigned StartArg = 0;
7519 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7520 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007521
Douglas Gregord3cb3562009-07-07 23:38:56 +00007522 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007523 // A viable function F1 is defined to be a better function than another
7524 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007525 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007526 unsigned NumArgs = Cand1.NumConversions;
7527 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007528 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007529 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007530 switch (CompareImplicitConversionSequences(S,
7531 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007532 Cand2.Conversions[ArgIdx])) {
7533 case ImplicitConversionSequence::Better:
7534 // Cand1 has a better conversion sequence.
7535 HasBetterConversion = true;
7536 break;
7537
7538 case ImplicitConversionSequence::Worse:
7539 // Cand1 can't be better than Cand2.
7540 return false;
7541
7542 case ImplicitConversionSequence::Indistinguishable:
7543 // Do nothing.
7544 break;
7545 }
7546 }
7547
Mike Stump11289f42009-09-09 15:08:12 +00007548 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007549 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007550 if (HasBetterConversion)
7551 return true;
7552
Mike Stump11289f42009-09-09 15:08:12 +00007553 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007554 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007555 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007556 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7557 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007558
7559 // -- F1 and F2 are function template specializations, and the function
7560 // template for F1 is more specialized than the template for F2
7561 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007562 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007563 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007564 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007565 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007566 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7567 Cand2.Function->getPrimaryTemplate(),
7568 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007570 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007571 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007572 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
Douglas Gregora1f013e2008-11-07 22:36:19 +00007575 // -- the context is an initialization by user-defined conversion
7576 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7577 // from the return type of F1 to the destination type (i.e.,
7578 // the type of the entity being initialized) is a better
7579 // conversion sequence than the standard conversion sequence
7580 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007581 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007582 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007583 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007584 // First check whether we prefer one of the conversion functions over the
7585 // other. This only distinguishes the results in non-standard, extension
7586 // cases such as the conversion from a lambda closure type to a function
7587 // pointer or block.
7588 ImplicitConversionSequence::CompareKind FuncResult
7589 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7590 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7591 return FuncResult;
7592
John McCall5c32be02010-08-24 20:38:10 +00007593 switch (CompareStandardConversionSequences(S,
7594 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007595 Cand2.FinalConversion)) {
7596 case ImplicitConversionSequence::Better:
7597 // Cand1 has a better conversion sequence.
7598 return true;
7599
7600 case ImplicitConversionSequence::Worse:
7601 // Cand1 can't be better than Cand2.
7602 return false;
7603
7604 case ImplicitConversionSequence::Indistinguishable:
7605 // Do nothing
7606 break;
7607 }
7608 }
7609
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007610 return false;
7611}
7612
Mike Stump11289f42009-09-09 15:08:12 +00007613/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007614/// within an overload candidate set.
7615///
7616/// \param CandidateSet the set of candidate functions.
7617///
7618/// \param Loc the location of the function name (or operator symbol) for
7619/// which overload resolution occurs.
7620///
Mike Stump11289f42009-09-09 15:08:12 +00007621/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007622/// function, Best points to the candidate function found.
7623///
7624/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007625OverloadingResult
7626OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007627 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007628 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007629 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007630 Best = end();
7631 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7632 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007634 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007635 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007636 }
7637
7638 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007639 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007640 return OR_No_Viable_Function;
7641
7642 // Make sure that this function is better than every other viable
7643 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007644 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007645 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007646 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007647 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007648 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007649 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007650 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007651 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007652 }
Mike Stump11289f42009-09-09 15:08:12 +00007653
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007654 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007655 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007656 (Best->Function->isDeleted() ||
7657 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007658 return OR_Deleted;
7659
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007660 return OR_Success;
7661}
7662
John McCall53262c92010-01-12 02:15:36 +00007663namespace {
7664
7665enum OverloadCandidateKind {
7666 oc_function,
7667 oc_method,
7668 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007669 oc_function_template,
7670 oc_method_template,
7671 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007672 oc_implicit_default_constructor,
7673 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007674 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007675 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007676 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007677 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007678};
7679
John McCalle1ac8d12010-01-13 00:25:19 +00007680OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7681 FunctionDecl *Fn,
7682 std::string &Description) {
7683 bool isTemplate = false;
7684
7685 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7686 isTemplate = true;
7687 Description = S.getTemplateArgumentBindingsText(
7688 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7689 }
John McCallfd0b2f82010-01-06 09:43:14 +00007690
7691 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007692 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007693 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007694
Sebastian Redl08905022011-02-05 19:23:19 +00007695 if (Ctor->getInheritedConstructor())
7696 return oc_implicit_inherited_constructor;
7697
Alexis Hunt119c10e2011-05-25 23:16:36 +00007698 if (Ctor->isDefaultConstructor())
7699 return oc_implicit_default_constructor;
7700
7701 if (Ctor->isMoveConstructor())
7702 return oc_implicit_move_constructor;
7703
7704 assert(Ctor->isCopyConstructor() &&
7705 "unexpected sort of implicit constructor");
7706 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007707 }
7708
7709 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7710 // This actually gets spelled 'candidate function' for now, but
7711 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007712 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007713 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007714
Alexis Hunt119c10e2011-05-25 23:16:36 +00007715 if (Meth->isMoveAssignmentOperator())
7716 return oc_implicit_move_assignment;
7717
Douglas Gregor12695102012-02-10 08:36:38 +00007718 if (Meth->isCopyAssignmentOperator())
7719 return oc_implicit_copy_assignment;
7720
7721 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7722 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007723 }
7724
John McCalle1ac8d12010-01-13 00:25:19 +00007725 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007726}
7727
Sebastian Redl08905022011-02-05 19:23:19 +00007728void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7729 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7730 if (!Ctor) return;
7731
7732 Ctor = Ctor->getInheritedConstructor();
7733 if (!Ctor) return;
7734
7735 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7736}
7737
John McCall53262c92010-01-12 02:15:36 +00007738} // end anonymous namespace
7739
7740// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007741void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007742 std::string FnDesc;
7743 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007744 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7745 << (unsigned) K << FnDesc;
7746 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7747 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007748 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007749}
7750
Douglas Gregorb491ed32011-02-19 21:32:49 +00007751//Notes the location of all overload candidates designated through
7752// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007753void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007754 assert(OverloadedExpr->getType() == Context.OverloadTy);
7755
7756 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7757 OverloadExpr *OvlExpr = Ovl.Expression;
7758
7759 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7760 IEnd = OvlExpr->decls_end();
7761 I != IEnd; ++I) {
7762 if (FunctionTemplateDecl *FunTmpl =
7763 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007764 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007765 } else if (FunctionDecl *Fun
7766 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007767 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007768 }
7769 }
7770}
7771
John McCall0d1da222010-01-12 00:44:57 +00007772/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7773/// "lead" diagnostic; it will be given two arguments, the source and
7774/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007775void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7776 Sema &S,
7777 SourceLocation CaretLoc,
7778 const PartialDiagnostic &PDiag) const {
7779 S.Diag(CaretLoc, PDiag)
7780 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007781 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007782 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7783 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007784 }
John McCall12f97bc2010-01-08 04:41:39 +00007785}
7786
John McCall0d1da222010-01-12 00:44:57 +00007787namespace {
7788
John McCall6a61b522010-01-13 09:16:55 +00007789void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7790 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7791 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007792 assert(Cand->Function && "for now, candidate must be a function");
7793 FunctionDecl *Fn = Cand->Function;
7794
7795 // There's a conversion slot for the object argument if this is a
7796 // non-constructor method. Note that 'I' corresponds the
7797 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007798 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007799 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007800 if (I == 0)
7801 isObjectArgument = true;
7802 else
7803 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007804 }
7805
John McCalle1ac8d12010-01-13 00:25:19 +00007806 std::string FnDesc;
7807 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7808
John McCall6a61b522010-01-13 09:16:55 +00007809 Expr *FromExpr = Conv.Bad.FromExpr;
7810 QualType FromTy = Conv.Bad.getFromType();
7811 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007812
John McCallfb7ad0f2010-02-02 02:42:52 +00007813 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007814 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007815 Expr *E = FromExpr->IgnoreParens();
7816 if (isa<UnaryOperator>(E))
7817 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007818 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007819
7820 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7821 << (unsigned) FnKind << FnDesc
7822 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7823 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007824 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007825 return;
7826 }
7827
John McCall6d174642010-01-23 08:10:49 +00007828 // Do some hand-waving analysis to see if the non-viability is due
7829 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007830 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7831 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7832 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7833 CToTy = RT->getPointeeType();
7834 else {
7835 // TODO: detect and diagnose the full richness of const mismatches.
7836 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7837 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7838 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7839 }
7840
7841 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7842 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7843 // It is dumb that we have to do this here.
7844 while (isa<ArrayType>(CFromTy))
7845 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7846 while (isa<ArrayType>(CToTy))
7847 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7848
7849 Qualifiers FromQs = CFromTy.getQualifiers();
7850 Qualifiers ToQs = CToTy.getQualifiers();
7851
7852 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7853 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7854 << (unsigned) FnKind << FnDesc
7855 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7856 << FromTy
7857 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7858 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007859 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007860 return;
7861 }
7862
John McCall31168b02011-06-15 23:02:42 +00007863 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007865 << (unsigned) FnKind << FnDesc
7866 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7867 << FromTy
7868 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7869 << (unsigned) isObjectArgument << I+1;
7870 MaybeEmitInheritedConstructorNote(S, Fn);
7871 return;
7872 }
7873
Douglas Gregoraec25842011-04-26 23:16:46 +00007874 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7876 << (unsigned) FnKind << FnDesc
7877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7878 << FromTy
7879 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7880 << (unsigned) isObjectArgument << I+1;
7881 MaybeEmitInheritedConstructorNote(S, Fn);
7882 return;
7883 }
7884
John McCall47000992010-01-14 03:28:57 +00007885 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7886 assert(CVR && "unexpected qualifiers mismatch");
7887
7888 if (isObjectArgument) {
7889 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7890 << (unsigned) FnKind << FnDesc
7891 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7892 << FromTy << (CVR - 1);
7893 } else {
7894 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7895 << (unsigned) FnKind << FnDesc
7896 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7897 << FromTy << (CVR - 1) << I+1;
7898 }
Sebastian Redl08905022011-02-05 19:23:19 +00007899 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007900 return;
7901 }
7902
Sebastian Redla72462c2011-09-24 17:48:32 +00007903 // Special diagnostic for failure to convert an initializer list, since
7904 // telling the user that it has type void is not useful.
7905 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7907 << (unsigned) FnKind << FnDesc
7908 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7909 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7910 MaybeEmitInheritedConstructorNote(S, Fn);
7911 return;
7912 }
7913
John McCall6d174642010-01-23 08:10:49 +00007914 // Diagnose references or pointers to incomplete types differently,
7915 // since it's far from impossible that the incompleteness triggered
7916 // the failure.
7917 QualType TempFromTy = FromTy.getNonReferenceType();
7918 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7919 TempFromTy = PTy->getPointeeType();
7920 if (TempFromTy->isIncompleteType()) {
7921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7922 << (unsigned) FnKind << FnDesc
7923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7924 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007925 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007926 return;
7927 }
7928
Douglas Gregor56f2e342010-06-30 23:01:39 +00007929 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007930 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007931 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7932 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7933 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7934 FromPtrTy->getPointeeType()) &&
7935 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7936 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007938 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007939 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007940 }
7941 } else if (const ObjCObjectPointerType *FromPtrTy
7942 = FromTy->getAs<ObjCObjectPointerType>()) {
7943 if (const ObjCObjectPointerType *ToPtrTy
7944 = ToTy->getAs<ObjCObjectPointerType>())
7945 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7946 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7947 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7948 FromPtrTy->getPointeeType()) &&
7949 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007950 BaseToDerivedConversion = 2;
7951 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7952 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7953 !FromTy->isIncompleteType() &&
7954 !ToRefTy->getPointeeType()->isIncompleteType() &&
7955 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7956 BaseToDerivedConversion = 3;
7957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007958
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007959 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007960 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007961 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007962 << (unsigned) FnKind << FnDesc
7963 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007964 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007965 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007966 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007967 return;
7968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007970 if (isa<ObjCObjectPointerType>(CFromTy) &&
7971 isa<PointerType>(CToTy)) {
7972 Qualifiers FromQs = CFromTy.getQualifiers();
7973 Qualifiers ToQs = CToTy.getQualifiers();
7974 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7976 << (unsigned) FnKind << FnDesc
7977 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7978 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7979 MaybeEmitInheritedConstructorNote(S, Fn);
7980 return;
7981 }
7982 }
7983
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007984 // Emit the generic diagnostic and, optionally, add the hints to it.
7985 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7986 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007987 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007988 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7989 << (unsigned) (Cand->Fix.Kind);
7990
7991 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00007992 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7993 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007994 FDiag << *HI;
7995 S.Diag(Fn->getLocation(), FDiag);
7996
Sebastian Redl08905022011-02-05 19:23:19 +00007997 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007998}
7999
8000void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8001 unsigned NumFormalArgs) {
8002 // TODO: treat calls to a missing default constructor as a special case
8003
8004 FunctionDecl *Fn = Cand->Function;
8005 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8006
8007 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008009 // With invalid overloaded operators, it's possible that we think we
8010 // have an arity mismatch when it fact it looks like we have the
8011 // right number of arguments, because only overloaded operators have
8012 // the weird behavior of overloading member and non-member functions.
8013 // Just don't report anything.
8014 if (Fn->isInvalidDecl() &&
8015 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8016 return;
8017
John McCall6a61b522010-01-13 09:16:55 +00008018 // at least / at most / exactly
8019 unsigned mode, modeCount;
8020 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008021 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8022 (Cand->FailureKind == ovl_fail_bad_deduction &&
8023 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008024 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008025 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008026 mode = 0; // "at least"
8027 else
8028 mode = 2; // "exactly"
8029 modeCount = MinParams;
8030 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008031 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8032 (Cand->FailureKind == ovl_fail_bad_deduction &&
8033 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008034 if (MinParams != FnTy->getNumArgs())
8035 mode = 1; // "at most"
8036 else
8037 mode = 2; // "exactly"
8038 modeCount = FnTy->getNumArgs();
8039 }
8040
8041 std::string Description;
8042 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8043
8044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008046 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008047 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008048}
8049
John McCall8b9ed552010-02-01 18:53:26 +00008050/// Diagnose a failed template-argument deduction.
8051void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8052 Expr **Args, unsigned NumArgs) {
8053 FunctionDecl *Fn = Cand->Function; // pattern
8054
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008055 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008056 NamedDecl *ParamD;
8057 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8058 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8059 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008060 switch (Cand->DeductionFailure.Result) {
8061 case Sema::TDK_Success:
8062 llvm_unreachable("TDK_success while diagnosing bad deduction");
8063
8064 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008065 assert(ParamD && "no parameter found for incomplete deduction result");
8066 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8067 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008068 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008069 return;
8070 }
8071
John McCall42d7d192010-08-05 09:05:08 +00008072 case Sema::TDK_Underqualified: {
8073 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8074 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8075
8076 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8077
8078 // Param will have been canonicalized, but it should just be a
8079 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008080 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008081 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008082 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008083 assert(S.Context.hasSameType(Param, NonCanonParam));
8084
8085 // Arg has also been canonicalized, but there's nothing we can do
8086 // about that. It also doesn't matter as much, because it won't
8087 // have any template parameters in it (because deduction isn't
8088 // done on dependent types).
8089 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8090
8091 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8092 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008093 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008094 return;
8095 }
8096
8097 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008098 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008099 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008100 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008101 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008102 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008103 which = 1;
8104 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008105 which = 2;
8106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008107
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008110 << *Cand->DeductionFailure.getFirstArg()
8111 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008112 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008113 return;
8114 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008115
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008116 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008117 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008118 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008119 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008120 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8121 << ParamD->getDeclName();
8122 else {
8123 int index = 0;
8124 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8125 index = TTP->getIndex();
8126 else if (NonTypeTemplateParmDecl *NTTP
8127 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8128 index = NTTP->getIndex();
8129 else
8130 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008131 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008132 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8133 << (index + 1);
8134 }
Sebastian Redl08905022011-02-05 19:23:19 +00008135 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008136 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137
Douglas Gregor02eb4832010-05-08 18:13:28 +00008138 case Sema::TDK_TooManyArguments:
8139 case Sema::TDK_TooFewArguments:
8140 DiagnoseArityMismatch(S, Cand, NumArgs);
8141 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008142
8143 case Sema::TDK_InstantiationDepth:
8144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008145 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008146 return;
8147
8148 case Sema::TDK_SubstitutionFailure: {
8149 std::string ArgString;
8150 if (TemplateArgumentList *Args
8151 = Cand->DeductionFailure.getTemplateArgumentList())
8152 ArgString = S.getTemplateArgumentBindingsText(
8153 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8154 *Args);
8155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8156 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008157 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008158 return;
8159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160
John McCall8b9ed552010-02-01 18:53:26 +00008161 // TODO: diagnose these individually, then kill off
8162 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008163 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008164 case Sema::TDK_FailedOverloadResolution:
8165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008166 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008167 return;
8168 }
8169}
8170
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008171/// CUDA: diagnose an invalid call across targets.
8172void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8173 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8174 FunctionDecl *Callee = Cand->Function;
8175
8176 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8177 CalleeTarget = S.IdentifyCUDATarget(Callee);
8178
8179 std::string FnDesc;
8180 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8181
8182 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8183 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8184}
8185
John McCall8b9ed552010-02-01 18:53:26 +00008186/// Generates a 'note' diagnostic for an overload candidate. We've
8187/// already generated a primary error at the call site.
8188///
8189/// It really does need to be a single diagnostic with its caret
8190/// pointed at the candidate declaration. Yes, this creates some
8191/// major challenges of technical writing. Yes, this makes pointing
8192/// out problems with specific arguments quite awkward. It's still
8193/// better than generating twenty screens of text for every failed
8194/// overload.
8195///
8196/// It would be great to be able to express per-candidate problems
8197/// more richly for those diagnostic clients that cared, but we'd
8198/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008199void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8200 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008201 FunctionDecl *Fn = Cand->Function;
8202
John McCall12f97bc2010-01-08 04:41:39 +00008203 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008204 if (Cand->Viable && (Fn->isDeleted() ||
8205 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008206 std::string FnDesc;
8207 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008208
8209 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00008210 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00008211 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008212 return;
John McCall12f97bc2010-01-08 04:41:39 +00008213 }
8214
John McCalle1ac8d12010-01-13 00:25:19 +00008215 // We don't really have anything else to say about viable candidates.
8216 if (Cand->Viable) {
8217 S.NoteOverloadCandidate(Fn);
8218 return;
8219 }
John McCall0d1da222010-01-12 00:44:57 +00008220
John McCall6a61b522010-01-13 09:16:55 +00008221 switch (Cand->FailureKind) {
8222 case ovl_fail_too_many_arguments:
8223 case ovl_fail_too_few_arguments:
8224 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008225
John McCall6a61b522010-01-13 09:16:55 +00008226 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00008227 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8228
John McCallfe796dd2010-01-23 05:17:32 +00008229 case ovl_fail_trivial_conversion:
8230 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008231 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008232 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008233
John McCall65eb8792010-02-25 01:37:24 +00008234 case ovl_fail_bad_conversion: {
8235 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008236 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008237 if (Cand->Conversions[I].isBad())
8238 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008239
John McCall6a61b522010-01-13 09:16:55 +00008240 // FIXME: this currently happens when we're called from SemaInit
8241 // when user-conversion overload fails. Figure out how to handle
8242 // those conditions and diagnose them well.
8243 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008244 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008245
8246 case ovl_fail_bad_target:
8247 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008248 }
John McCalld3224162010-01-08 00:58:21 +00008249}
8250
8251void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8252 // Desugar the type of the surrogate down to a function type,
8253 // retaining as many typedefs as possible while still showing
8254 // the function type (and, therefore, its parameter types).
8255 QualType FnType = Cand->Surrogate->getConversionType();
8256 bool isLValueReference = false;
8257 bool isRValueReference = false;
8258 bool isPointer = false;
8259 if (const LValueReferenceType *FnTypeRef =
8260 FnType->getAs<LValueReferenceType>()) {
8261 FnType = FnTypeRef->getPointeeType();
8262 isLValueReference = true;
8263 } else if (const RValueReferenceType *FnTypeRef =
8264 FnType->getAs<RValueReferenceType>()) {
8265 FnType = FnTypeRef->getPointeeType();
8266 isRValueReference = true;
8267 }
8268 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8269 FnType = FnTypePtr->getPointeeType();
8270 isPointer = true;
8271 }
8272 // Desugar down to a function type.
8273 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8274 // Reconstruct the pointer/reference as appropriate.
8275 if (isPointer) FnType = S.Context.getPointerType(FnType);
8276 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8277 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8278
8279 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8280 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008281 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008282}
8283
8284void NoteBuiltinOperatorCandidate(Sema &S,
8285 const char *Opc,
8286 SourceLocation OpLoc,
8287 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008288 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008289 std::string TypeStr("operator");
8290 TypeStr += Opc;
8291 TypeStr += "(";
8292 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008293 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008294 TypeStr += ")";
8295 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8296 } else {
8297 TypeStr += ", ";
8298 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8299 TypeStr += ")";
8300 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8301 }
8302}
8303
8304void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8305 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008306 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008307 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8308 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008309 if (ICS.isBad()) break; // all meaningless after first invalid
8310 if (!ICS.isAmbiguous()) continue;
8311
John McCall5c32be02010-08-24 20:38:10 +00008312 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008313 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008314 }
8315}
8316
John McCall3712d9e2010-01-15 23:32:50 +00008317SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8318 if (Cand->Function)
8319 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008320 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008321 return Cand->Surrogate->getLocation();
8322 return SourceLocation();
8323}
8324
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008325static unsigned
8326RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008327 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008328 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008329 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008330
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008331 case Sema::TDK_Incomplete:
8332 return 1;
8333
8334 case Sema::TDK_Underqualified:
8335 case Sema::TDK_Inconsistent:
8336 return 2;
8337
8338 case Sema::TDK_SubstitutionFailure:
8339 case Sema::TDK_NonDeducedMismatch:
8340 return 3;
8341
8342 case Sema::TDK_InstantiationDepth:
8343 case Sema::TDK_FailedOverloadResolution:
8344 return 4;
8345
8346 case Sema::TDK_InvalidExplicitArguments:
8347 return 5;
8348
8349 case Sema::TDK_TooManyArguments:
8350 case Sema::TDK_TooFewArguments:
8351 return 6;
8352 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008353 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008354}
8355
John McCallad2587a2010-01-12 00:48:53 +00008356struct CompareOverloadCandidatesForDisplay {
8357 Sema &S;
8358 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008359
8360 bool operator()(const OverloadCandidate *L,
8361 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008362 // Fast-path this check.
8363 if (L == R) return false;
8364
John McCall12f97bc2010-01-08 04:41:39 +00008365 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008366 if (L->Viable) {
8367 if (!R->Viable) return true;
8368
8369 // TODO: introduce a tri-valued comparison for overload
8370 // candidates. Would be more worthwhile if we had a sort
8371 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008372 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8373 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008374 } else if (R->Viable)
8375 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008376
John McCall3712d9e2010-01-15 23:32:50 +00008377 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008378
John McCall3712d9e2010-01-15 23:32:50 +00008379 // Criteria by which we can sort non-viable candidates:
8380 if (!L->Viable) {
8381 // 1. Arity mismatches come after other candidates.
8382 if (L->FailureKind == ovl_fail_too_many_arguments ||
8383 L->FailureKind == ovl_fail_too_few_arguments)
8384 return false;
8385 if (R->FailureKind == ovl_fail_too_many_arguments ||
8386 R->FailureKind == ovl_fail_too_few_arguments)
8387 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008388
John McCallfe796dd2010-01-23 05:17:32 +00008389 // 2. Bad conversions come first and are ordered by the number
8390 // of bad conversions and quality of good conversions.
8391 if (L->FailureKind == ovl_fail_bad_conversion) {
8392 if (R->FailureKind != ovl_fail_bad_conversion)
8393 return true;
8394
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008395 // The conversion that can be fixed with a smaller number of changes,
8396 // comes first.
8397 unsigned numLFixes = L->Fix.NumConversionsFixed;
8398 unsigned numRFixes = R->Fix.NumConversionsFixed;
8399 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8400 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008401 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008402 if (numLFixes < numRFixes)
8403 return true;
8404 else
8405 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008406 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008407
John McCallfe796dd2010-01-23 05:17:32 +00008408 // If there's any ordering between the defined conversions...
8409 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008410 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008411
8412 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008413 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008414 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008415 switch (CompareImplicitConversionSequences(S,
8416 L->Conversions[I],
8417 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008418 case ImplicitConversionSequence::Better:
8419 leftBetter++;
8420 break;
8421
8422 case ImplicitConversionSequence::Worse:
8423 leftBetter--;
8424 break;
8425
8426 case ImplicitConversionSequence::Indistinguishable:
8427 break;
8428 }
8429 }
8430 if (leftBetter > 0) return true;
8431 if (leftBetter < 0) return false;
8432
8433 } else if (R->FailureKind == ovl_fail_bad_conversion)
8434 return false;
8435
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008436 if (L->FailureKind == ovl_fail_bad_deduction) {
8437 if (R->FailureKind != ovl_fail_bad_deduction)
8438 return true;
8439
8440 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8441 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008442 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008443 } else if (R->FailureKind == ovl_fail_bad_deduction)
8444 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008445
John McCall3712d9e2010-01-15 23:32:50 +00008446 // TODO: others?
8447 }
8448
8449 // Sort everything else by location.
8450 SourceLocation LLoc = GetLocationForCandidate(L);
8451 SourceLocation RLoc = GetLocationForCandidate(R);
8452
8453 // Put candidates without locations (e.g. builtins) at the end.
8454 if (LLoc.isInvalid()) return false;
8455 if (RLoc.isInvalid()) return true;
8456
8457 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008458 }
8459};
8460
John McCallfe796dd2010-01-23 05:17:32 +00008461/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008462/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008463void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8464 Expr **Args, unsigned NumArgs) {
8465 assert(!Cand->Viable);
8466
8467 // Don't do anything on failures other than bad conversion.
8468 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8469
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008470 // We only want the FixIts if all the arguments can be corrected.
8471 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008472 // Use a implicit copy initialization to check conversion fixes.
8473 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008474
John McCallfe796dd2010-01-23 05:17:32 +00008475 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008476 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008477 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008478 while (true) {
8479 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8480 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008481 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008482 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008483 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008484 }
John McCallfe796dd2010-01-23 05:17:32 +00008485 }
8486
8487 if (ConvIdx == ConvCount)
8488 return;
8489
John McCall65eb8792010-02-25 01:37:24 +00008490 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8491 "remaining conversion is initialized?");
8492
Douglas Gregoradc7a702010-04-16 17:45:54 +00008493 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008494 // operation somehow.
8495 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008496
8497 const FunctionProtoType* Proto;
8498 unsigned ArgIdx = ConvIdx;
8499
8500 if (Cand->IsSurrogate) {
8501 QualType ConvType
8502 = Cand->Surrogate->getConversionType().getNonReferenceType();
8503 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8504 ConvType = ConvPtrType->getPointeeType();
8505 Proto = ConvType->getAs<FunctionProtoType>();
8506 ArgIdx--;
8507 } else if (Cand->Function) {
8508 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8509 if (isa<CXXMethodDecl>(Cand->Function) &&
8510 !isa<CXXConstructorDecl>(Cand->Function))
8511 ArgIdx--;
8512 } else {
8513 // Builtin binary operator with a bad first conversion.
8514 assert(ConvCount <= 3);
8515 for (; ConvIdx != ConvCount; ++ConvIdx)
8516 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008517 = TryCopyInitialization(S, Args[ConvIdx],
8518 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008519 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008520 /*InOverloadResolution*/ true,
8521 /*AllowObjCWritebackConversion=*/
8522 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008523 return;
8524 }
8525
8526 // Fill in the rest of the conversions.
8527 unsigned NumArgsInProto = Proto->getNumArgs();
8528 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008529 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008530 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008531 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008532 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008533 /*InOverloadResolution=*/true,
8534 /*AllowObjCWritebackConversion=*/
8535 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008536 // Store the FixIt in the candidate if it exists.
8537 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008538 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008539 }
John McCallfe796dd2010-01-23 05:17:32 +00008540 else
8541 Cand->Conversions[ConvIdx].setEllipsis();
8542 }
8543}
8544
John McCalld3224162010-01-08 00:58:21 +00008545} // end anonymous namespace
8546
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008547/// PrintOverloadCandidates - When overload resolution fails, prints
8548/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008549/// set.
John McCall5c32be02010-08-24 20:38:10 +00008550void OverloadCandidateSet::NoteCandidates(Sema &S,
8551 OverloadCandidateDisplayKind OCD,
8552 Expr **Args, unsigned NumArgs,
8553 const char *Opc,
8554 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008555 // Sort the candidates by viability and position. Sorting directly would
8556 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008557 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008558 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8559 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008560 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008561 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008562 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008563 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008564 if (Cand->Function || Cand->IsSurrogate)
8565 Cands.push_back(Cand);
8566 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8567 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008568 }
8569 }
8570
John McCallad2587a2010-01-12 00:48:53 +00008571 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008572 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008573
John McCall0d1da222010-01-12 00:44:57 +00008574 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008575
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008576 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008577 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8578 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008579 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008580 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8581 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008582
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008583 // Set an arbitrary limit on the number of candidate functions we'll spam
8584 // the user with. FIXME: This limit should depend on details of the
8585 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008586 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008587 break;
8588 }
8589 ++CandsShown;
8590
John McCalld3224162010-01-08 00:58:21 +00008591 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008592 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008593 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008594 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008595 else {
8596 assert(Cand->Viable &&
8597 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008598 // Generally we only see ambiguities including viable builtin
8599 // operators if overload resolution got screwed up by an
8600 // ambiguous user-defined conversion.
8601 //
8602 // FIXME: It's quite possible for different conversions to see
8603 // different ambiguities, though.
8604 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008605 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008606 ReportedAmbiguousConversions = true;
8607 }
John McCalld3224162010-01-08 00:58:21 +00008608
John McCall0d1da222010-01-12 00:44:57 +00008609 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008610 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008611 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008612 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008613
8614 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008615 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008616}
8617
Douglas Gregorb491ed32011-02-19 21:32:49 +00008618// [PossiblyAFunctionType] --> [Return]
8619// NonFunctionType --> NonFunctionType
8620// R (A) --> R(A)
8621// R (*)(A) --> R (A)
8622// R (&)(A) --> R (A)
8623// R (S::*)(A) --> R (A)
8624QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8625 QualType Ret = PossiblyAFunctionType;
8626 if (const PointerType *ToTypePtr =
8627 PossiblyAFunctionType->getAs<PointerType>())
8628 Ret = ToTypePtr->getPointeeType();
8629 else if (const ReferenceType *ToTypeRef =
8630 PossiblyAFunctionType->getAs<ReferenceType>())
8631 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008632 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008633 PossiblyAFunctionType->getAs<MemberPointerType>())
8634 Ret = MemTypePtr->getPointeeType();
8635 Ret =
8636 Context.getCanonicalType(Ret).getUnqualifiedType();
8637 return Ret;
8638}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008639
Douglas Gregorb491ed32011-02-19 21:32:49 +00008640// A helper class to help with address of function resolution
8641// - allows us to avoid passing around all those ugly parameters
8642class AddressOfFunctionResolver
8643{
8644 Sema& S;
8645 Expr* SourceExpr;
8646 const QualType& TargetType;
8647 QualType TargetFunctionType; // Extracted function type from target type
8648
8649 bool Complain;
8650 //DeclAccessPair& ResultFunctionAccessPair;
8651 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008652
Douglas Gregorb491ed32011-02-19 21:32:49 +00008653 bool TargetTypeIsNonStaticMemberFunction;
8654 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008655
Douglas Gregorb491ed32011-02-19 21:32:49 +00008656 OverloadExpr::FindResult OvlExprInfo;
8657 OverloadExpr *OvlExpr;
8658 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008659 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008660
Douglas Gregorb491ed32011-02-19 21:32:49 +00008661public:
8662 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8663 const QualType& TargetType, bool Complain)
8664 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8665 Complain(Complain), Context(S.getASTContext()),
8666 TargetTypeIsNonStaticMemberFunction(
8667 !!TargetType->getAs<MemberPointerType>()),
8668 FoundNonTemplateFunction(false),
8669 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8670 OvlExpr(OvlExprInfo.Expression)
8671 {
8672 ExtractUnqualifiedFunctionTypeFromTargetType();
8673
8674 if (!TargetFunctionType->isFunctionType()) {
8675 if (OvlExpr->hasExplicitTemplateArgs()) {
8676 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008677 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008678 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008679
8680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8681 if (!Method->isStatic()) {
8682 // If the target type is a non-function type and the function
8683 // found is a non-static member function, pretend as if that was
8684 // the target, it's the only possible type to end up with.
8685 TargetTypeIsNonStaticMemberFunction = true;
8686
8687 // And skip adding the function if its not in the proper form.
8688 // We'll diagnose this due to an empty set of functions.
8689 if (!OvlExprInfo.HasFormOfMemberPointer)
8690 return;
8691 }
8692 }
8693
Douglas Gregorb491ed32011-02-19 21:32:49 +00008694 Matches.push_back(std::make_pair(dap,Fn));
8695 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008696 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008697 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008698 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008699
8700 if (OvlExpr->hasExplicitTemplateArgs())
8701 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008702
Douglas Gregorb491ed32011-02-19 21:32:49 +00008703 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8704 // C++ [over.over]p4:
8705 // If more than one function is selected, [...]
8706 if (Matches.size() > 1) {
8707 if (FoundNonTemplateFunction)
8708 EliminateAllTemplateMatches();
8709 else
8710 EliminateAllExceptMostSpecializedTemplate();
8711 }
8712 }
8713 }
8714
8715private:
8716 bool isTargetTypeAFunction() const {
8717 return TargetFunctionType->isFunctionType();
8718 }
8719
8720 // [ToType] [Return]
8721
8722 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8723 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8724 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8725 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8726 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8727 }
8728
8729 // return true if any matching specializations were found
8730 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8731 const DeclAccessPair& CurAccessFunPair) {
8732 if (CXXMethodDecl *Method
8733 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8734 // Skip non-static function templates when converting to pointer, and
8735 // static when converting to member pointer.
8736 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8737 return false;
8738 }
8739 else if (TargetTypeIsNonStaticMemberFunction)
8740 return false;
8741
8742 // C++ [over.over]p2:
8743 // If the name is a function template, template argument deduction is
8744 // done (14.8.2.2), and if the argument deduction succeeds, the
8745 // resulting template argument list is used to generate a single
8746 // function template specialization, which is added to the set of
8747 // overloaded functions considered.
8748 FunctionDecl *Specialization = 0;
8749 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8750 if (Sema::TemplateDeductionResult Result
8751 = S.DeduceTemplateArguments(FunctionTemplate,
8752 &OvlExplicitTemplateArgs,
8753 TargetFunctionType, Specialization,
8754 Info)) {
8755 // FIXME: make a note of the failed deduction for diagnostics.
8756 (void)Result;
8757 return false;
8758 }
8759
8760 // Template argument deduction ensures that we have an exact match.
8761 // This function template specicalization works.
8762 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8763 assert(TargetFunctionType
8764 == Context.getCanonicalType(Specialization->getType()));
8765 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8766 return true;
8767 }
8768
8769 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8770 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008772 // Skip non-static functions when converting to pointer, and static
8773 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008774 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8775 return false;
8776 }
8777 else if (TargetTypeIsNonStaticMemberFunction)
8778 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008779
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008780 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008781 if (S.getLangOptions().CUDA)
8782 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8783 if (S.CheckCUDATarget(Caller, FunDecl))
8784 return false;
8785
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008786 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008787 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8788 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008789 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8790 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008791 Matches.push_back(std::make_pair(CurAccessFunPair,
8792 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008793 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008794 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008795 }
Mike Stump11289f42009-09-09 15:08:12 +00008796 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008797
8798 return false;
8799 }
8800
8801 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8802 bool Ret = false;
8803
8804 // If the overload expression doesn't have the form of a pointer to
8805 // member, don't try to convert it to a pointer-to-member type.
8806 if (IsInvalidFormOfPointerToMemberFunction())
8807 return false;
8808
8809 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8810 E = OvlExpr->decls_end();
8811 I != E; ++I) {
8812 // Look through any using declarations to find the underlying function.
8813 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8814
8815 // C++ [over.over]p3:
8816 // Non-member functions and static member functions match
8817 // targets of type "pointer-to-function" or "reference-to-function."
8818 // Nonstatic member functions match targets of
8819 // type "pointer-to-member-function."
8820 // Note that according to DR 247, the containing class does not matter.
8821 if (FunctionTemplateDecl *FunctionTemplate
8822 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8823 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8824 Ret = true;
8825 }
8826 // If we have explicit template arguments supplied, skip non-templates.
8827 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8828 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8829 Ret = true;
8830 }
8831 assert(Ret || Matches.empty());
8832 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008833 }
8834
Douglas Gregorb491ed32011-02-19 21:32:49 +00008835 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008836 // [...] and any given function template specialization F1 is
8837 // eliminated if the set contains a second function template
8838 // specialization whose function template is more specialized
8839 // than the function template of F1 according to the partial
8840 // ordering rules of 14.5.5.2.
8841
8842 // The algorithm specified above is quadratic. We instead use a
8843 // two-pass algorithm (similar to the one used to identify the
8844 // best viable function in an overload set) that identifies the
8845 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008846
8847 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8848 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8849 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008850
John McCall58cc69d2010-01-27 01:50:18 +00008851 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008852 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8853 TPOC_Other, 0, SourceExpr->getLocStart(),
8854 S.PDiag(),
8855 S.PDiag(diag::err_addr_ovl_ambiguous)
8856 << Matches[0].second->getDeclName(),
8857 S.PDiag(diag::note_ovl_candidate)
8858 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008859 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008860
Douglas Gregorb491ed32011-02-19 21:32:49 +00008861 if (Result != MatchesCopy.end()) {
8862 // Make it the first and only element
8863 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8864 Matches[0].second = cast<FunctionDecl>(*Result);
8865 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008866 }
8867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868
Douglas Gregorb491ed32011-02-19 21:32:49 +00008869 void EliminateAllTemplateMatches() {
8870 // [...] any function template specializations in the set are
8871 // eliminated if the set also contains a non-template function, [...]
8872 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8873 if (Matches[I].second->getPrimaryTemplate() == 0)
8874 ++I;
8875 else {
8876 Matches[I] = Matches[--N];
8877 Matches.set_size(N);
8878 }
8879 }
8880 }
8881
8882public:
8883 void ComplainNoMatchesFound() const {
8884 assert(Matches.empty());
8885 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8886 << OvlExpr->getName() << TargetFunctionType
8887 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008888 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008889 }
8890
8891 bool IsInvalidFormOfPointerToMemberFunction() const {
8892 return TargetTypeIsNonStaticMemberFunction &&
8893 !OvlExprInfo.HasFormOfMemberPointer;
8894 }
8895
8896 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8897 // TODO: Should we condition this on whether any functions might
8898 // have matched, or is it more appropriate to do that in callers?
8899 // TODO: a fixit wouldn't hurt.
8900 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8901 << TargetType << OvlExpr->getSourceRange();
8902 }
8903
8904 void ComplainOfInvalidConversion() const {
8905 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8906 << OvlExpr->getName() << TargetType;
8907 }
8908
8909 void ComplainMultipleMatchesFound() const {
8910 assert(Matches.size() > 1);
8911 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8912 << OvlExpr->getName()
8913 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008914 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008915 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008916
8917 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8918
Douglas Gregorb491ed32011-02-19 21:32:49 +00008919 int getNumMatches() const { return Matches.size(); }
8920
8921 FunctionDecl* getMatchingFunctionDecl() const {
8922 if (Matches.size() != 1) return 0;
8923 return Matches[0].second;
8924 }
8925
8926 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8927 if (Matches.size() != 1) return 0;
8928 return &Matches[0].first;
8929 }
8930};
8931
8932/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8933/// an overloaded function (C++ [over.over]), where @p From is an
8934/// expression with overloaded function type and @p ToType is the type
8935/// we're trying to resolve to. For example:
8936///
8937/// @code
8938/// int f(double);
8939/// int f(int);
8940///
8941/// int (*pfd)(double) = f; // selects f(double)
8942/// @endcode
8943///
8944/// This routine returns the resulting FunctionDecl if it could be
8945/// resolved, and NULL otherwise. When @p Complain is true, this
8946/// routine will emit diagnostics if there is an error.
8947FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008948Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8949 QualType TargetType,
8950 bool Complain,
8951 DeclAccessPair &FoundResult,
8952 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008953 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008954
8955 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8956 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008957 int NumMatches = Resolver.getNumMatches();
8958 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008959 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008960 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8961 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8962 else
8963 Resolver.ComplainNoMatchesFound();
8964 }
8965 else if (NumMatches > 1 && Complain)
8966 Resolver.ComplainMultipleMatchesFound();
8967 else if (NumMatches == 1) {
8968 Fn = Resolver.getMatchingFunctionDecl();
8969 assert(Fn);
8970 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00008971 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008972 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008973 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008974 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008975
8976 if (pHadMultipleCandidates)
8977 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008978 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008979}
8980
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008981/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008982/// resolve that overloaded function expression down to a single function.
8983///
8984/// This routine can only resolve template-ids that refer to a single function
8985/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008986/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008987/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008988FunctionDecl *
8989Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8990 bool Complain,
8991 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008992 // C++ [over.over]p1:
8993 // [...] [Note: any redundant set of parentheses surrounding the
8994 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008995 // C++ [over.over]p1:
8996 // [...] The overloaded function name can be preceded by the &
8997 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008998
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008999 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009000 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009001 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009002
9003 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009004 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009005
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009006 // Look through all of the overloaded functions, searching for one
9007 // whose type matches exactly.
9008 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009009 for (UnresolvedSetIterator I = ovl->decls_begin(),
9010 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009011 // C++0x [temp.arg.explicit]p3:
9012 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009013 // where deduction is not done, if a template argument list is
9014 // specified and it, along with any default template arguments,
9015 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009016 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009017 FunctionTemplateDecl *FunctionTemplate
9018 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009019
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009020 // C++ [over.over]p2:
9021 // If the name is a function template, template argument deduction is
9022 // done (14.8.2.2), and if the argument deduction succeeds, the
9023 // resulting template argument list is used to generate a single
9024 // function template specialization, which is added to the set of
9025 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009026 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009027 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009028 if (TemplateDeductionResult Result
9029 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9030 Specialization, Info)) {
9031 // FIXME: make a note of the failed deduction for diagnostics.
9032 (void)Result;
9033 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009034 }
9035
John McCall0009fcc2011-04-26 20:42:42 +00009036 assert(Specialization && "no specialization and no error?");
9037
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009038 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009039 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009040 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009041 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9042 << ovl->getName();
9043 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009044 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009045 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009046 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009047
John McCall0009fcc2011-04-26 20:42:42 +00009048 Matched = Specialization;
9049 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009051
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009052 return Matched;
9053}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009054
Douglas Gregor1beec452011-03-12 01:48:56 +00009055
9056
9057
John McCall50a2c2c2011-10-11 23:14:30 +00009058// Resolve and fix an overloaded expression that can be resolved
9059// because it identifies a single function template specialization.
9060//
Douglas Gregor1beec452011-03-12 01:48:56 +00009061// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009062//
9063// Return true if it was logically possible to so resolve the
9064// expression, regardless of whether or not it succeeded. Always
9065// returns true if 'complain' is set.
9066bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9067 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9068 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009069 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009070 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009071 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009072
John McCall50a2c2c2011-10-11 23:14:30 +00009073 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009074
John McCall0009fcc2011-04-26 20:42:42 +00009075 DeclAccessPair found;
9076 ExprResult SingleFunctionExpression;
9077 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9078 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00009079 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
9080 SrcExpr = ExprError();
9081 return true;
9082 }
John McCall0009fcc2011-04-26 20:42:42 +00009083
9084 // It is only correct to resolve to an instance method if we're
9085 // resolving a form that's permitted to be a pointer to member.
9086 // Otherwise we'll end up making a bound member expression, which
9087 // is illegal in all the contexts we resolve like this.
9088 if (!ovl.HasFormOfMemberPointer &&
9089 isa<CXXMethodDecl>(fn) &&
9090 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009091 if (!complain) return false;
9092
9093 Diag(ovl.Expression->getExprLoc(),
9094 diag::err_bound_member_function)
9095 << 0 << ovl.Expression->getSourceRange();
9096
9097 // TODO: I believe we only end up here if there's a mix of
9098 // static and non-static candidates (otherwise the expression
9099 // would have 'bound member' type, not 'overload' type).
9100 // Ideally we would note which candidate was chosen and why
9101 // the static candidates were rejected.
9102 SrcExpr = ExprError();
9103 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009104 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009105
John McCall0009fcc2011-04-26 20:42:42 +00009106 // Fix the expresion to refer to 'fn'.
9107 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009108 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009109
9110 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009111 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009112 SingleFunctionExpression =
9113 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009114 if (SingleFunctionExpression.isInvalid()) {
9115 SrcExpr = ExprError();
9116 return true;
9117 }
9118 }
John McCall0009fcc2011-04-26 20:42:42 +00009119 }
9120
9121 if (!SingleFunctionExpression.isUsable()) {
9122 if (complain) {
9123 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9124 << ovl.Expression->getName()
9125 << DestTypeForComplaining
9126 << OpRangeForComplaining
9127 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009128 NoteAllOverloadCandidates(SrcExpr.get());
9129
9130 SrcExpr = ExprError();
9131 return true;
9132 }
9133
9134 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009135 }
9136
John McCall50a2c2c2011-10-11 23:14:30 +00009137 SrcExpr = SingleFunctionExpression;
9138 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009139}
9140
Douglas Gregorcabea402009-09-22 15:41:20 +00009141/// \brief Add a single candidate to the overload set.
9142static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009143 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009144 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009145 Expr **Args, unsigned NumArgs,
9146 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009147 bool PartialOverloading,
9148 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009149 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009150 if (isa<UsingShadowDecl>(Callee))
9151 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9152
Douglas Gregorcabea402009-09-22 15:41:20 +00009153 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009154 if (ExplicitTemplateArgs) {
9155 assert(!KnownValid && "Explicit template arguments?");
9156 return;
9157 }
John McCalla0296f72010-03-19 07:35:19 +00009158 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00009159 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009160 return;
John McCalld14a8642009-11-21 08:51:07 +00009161 }
9162
9163 if (FunctionTemplateDecl *FuncTemplate
9164 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009165 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9166 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00009167 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009168 return;
9169 }
9170
Richard Smith95ce4f62011-06-26 22:19:54 +00009171 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009172}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009173
Douglas Gregorcabea402009-09-22 15:41:20 +00009174/// \brief Add the overload candidates named by callee and/or found by argument
9175/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009176void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00009177 Expr **Args, unsigned NumArgs,
9178 OverloadCandidateSet &CandidateSet,
9179 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009180
9181#ifndef NDEBUG
9182 // Verify that ArgumentDependentLookup is consistent with the rules
9183 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009184 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009185 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9186 // and let Y be the lookup set produced by argument dependent
9187 // lookup (defined as follows). If X contains
9188 //
9189 // -- a declaration of a class member, or
9190 //
9191 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009192 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009193 //
9194 // -- a declaration that is neither a function or a function
9195 // template
9196 //
9197 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009198
John McCall57500772009-12-16 12:17:52 +00009199 if (ULE->requiresADL()) {
9200 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9201 E = ULE->decls_end(); I != E; ++I) {
9202 assert(!(*I)->getDeclContext()->isRecord());
9203 assert(isa<UsingShadowDecl>(*I) ||
9204 !(*I)->getDeclContext()->isFunctionOrMethod());
9205 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009206 }
9207 }
9208#endif
9209
John McCall57500772009-12-16 12:17:52 +00009210 // It would be nice to avoid this copy.
9211 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009212 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009213 if (ULE->hasExplicitTemplateArgs()) {
9214 ULE->copyTemplateArgumentsInto(TABuffer);
9215 ExplicitTemplateArgs = &TABuffer;
9216 }
9217
9218 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9219 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00009220 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009221 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009222 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009223
John McCall57500772009-12-16 12:17:52 +00009224 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009225 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9226 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009227 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00009228 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00009229 PartialOverloading,
9230 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009231}
John McCalld681c392009-12-16 08:11:27 +00009232
Richard Smith998a5912011-06-05 22:42:48 +00009233/// Attempt to recover from an ill-formed use of a non-dependent name in a
9234/// template, where the non-dependent name was declared after the template
9235/// was defined. This is common in code written for a compilers which do not
9236/// correctly implement two-stage name lookup.
9237///
9238/// Returns true if a viable candidate was found and a diagnostic was issued.
9239static bool
9240DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9241 const CXXScopeSpec &SS, LookupResult &R,
9242 TemplateArgumentListInfo *ExplicitTemplateArgs,
9243 Expr **Args, unsigned NumArgs) {
9244 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9245 return false;
9246
9247 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9248 SemaRef.LookupQualifiedName(R, DC);
9249
9250 if (!R.empty()) {
9251 R.suppressDiagnostics();
9252
9253 if (isa<CXXRecordDecl>(DC)) {
9254 // Don't diagnose names we find in classes; we get much better
9255 // diagnostics for these from DiagnoseEmptyLookup.
9256 R.clear();
9257 return false;
9258 }
9259
9260 OverloadCandidateSet Candidates(FnLoc);
9261 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9262 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9263 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00009264 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009265
9266 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009267 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009268 // No viable functions. Don't bother the user with notes for functions
9269 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009270 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009271 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009272 }
Richard Smith998a5912011-06-05 22:42:48 +00009273
9274 // Find the namespaces where ADL would have looked, and suggest
9275 // declaring the function there instead.
9276 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9277 Sema::AssociatedClassSet AssociatedClasses;
9278 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9279 AssociatedNamespaces,
9280 AssociatedClasses);
9281 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009282 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009283 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009284 for (Sema::AssociatedNamespaceSet::iterator
9285 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009286 end = AssociatedNamespaces.end(); it != end; ++it) {
9287 if (!Std->Encloses(*it))
9288 SuggestedNamespaces.insert(*it);
9289 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009290 } else {
9291 // Lacking the 'std::' namespace, use all of the associated namespaces.
9292 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009293 }
9294
9295 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9296 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009297 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009298 SemaRef.Diag(Best->Function->getLocation(),
9299 diag::note_not_found_by_two_phase_lookup)
9300 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009301 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009302 SemaRef.Diag(Best->Function->getLocation(),
9303 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009304 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009305 } else {
9306 // FIXME: It would be useful to list the associated namespaces here,
9307 // but the diagnostics infrastructure doesn't provide a way to produce
9308 // a localized representation of a list of items.
9309 SemaRef.Diag(Best->Function->getLocation(),
9310 diag::note_not_found_by_two_phase_lookup)
9311 << R.getLookupName() << 2;
9312 }
9313
9314 // Try to recover by calling this function.
9315 return true;
9316 }
9317
9318 R.clear();
9319 }
9320
9321 return false;
9322}
9323
9324/// Attempt to recover from ill-formed use of a non-dependent operator in a
9325/// template, where the non-dependent operator was declared after the template
9326/// was defined.
9327///
9328/// Returns true if a viable candidate was found and a diagnostic was issued.
9329static bool
9330DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9331 SourceLocation OpLoc,
9332 Expr **Args, unsigned NumArgs) {
9333 DeclarationName OpName =
9334 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9335 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9336 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9337 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9338}
9339
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009340namespace {
9341// Callback to limit the allowed keywords and to only accept typo corrections
9342// that are keywords or whose decls refer to functions (or template functions)
9343// that accept the given number of arguments.
9344class RecoveryCallCCC : public CorrectionCandidateCallback {
9345 public:
9346 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9347 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9348 WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9349 WantRemainingKeywords = false;
9350 }
9351
9352 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9353 if (!candidate.getCorrectionDecl())
9354 return candidate.isKeyword();
9355
9356 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9357 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9358 FunctionDecl *FD = 0;
9359 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9360 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9361 FD = FTD->getTemplatedDecl();
9362 if (!HasExplicitTemplateArgs && !FD) {
9363 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9364 // If the Decl is neither a function nor a template function,
9365 // determine if it is a pointer or reference to a function. If so,
9366 // check against the number of arguments expected for the pointee.
9367 QualType ValType = cast<ValueDecl>(ND)->getType();
9368 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9369 ValType = ValType->getPointeeType();
9370 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9371 if (FPT->getNumArgs() == NumArgs)
9372 return true;
9373 }
9374 }
9375 if (FD && FD->getNumParams() >= NumArgs &&
9376 FD->getMinRequiredArguments() <= NumArgs)
9377 return true;
9378 }
9379 return false;
9380 }
9381
9382 private:
9383 unsigned NumArgs;
9384 bool HasExplicitTemplateArgs;
9385};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009386
9387// Callback that effectively disabled typo correction
9388class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9389 public:
9390 NoTypoCorrectionCCC() {
9391 WantTypeSpecifiers = false;
9392 WantExpressionKeywords = false;
9393 WantCXXNamedCasts = false;
9394 WantRemainingKeywords = false;
9395 }
9396
9397 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9398 return false;
9399 }
9400};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009401}
9402
John McCalld681c392009-12-16 08:11:27 +00009403/// Attempts to recover from a call where no functions were found.
9404///
9405/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009406static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009407BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009408 UnresolvedLookupExpr *ULE,
9409 SourceLocation LParenLoc,
9410 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00009411 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009412 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009413
9414 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009415 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009416 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009417
John McCall57500772009-12-16 12:17:52 +00009418 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009419 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009420 if (ULE->hasExplicitTemplateArgs()) {
9421 ULE->copyTemplateArgumentsInto(TABuffer);
9422 ExplicitTemplateArgs = &TABuffer;
9423 }
9424
John McCalld681c392009-12-16 08:11:27 +00009425 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9426 Sema::LookupOrdinaryName);
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009427 RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009428 NoTypoCorrectionCCC RejectAll;
9429 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9430 (CorrectionCandidateCallback*)&Validator :
9431 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009432 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9433 ExplicitTemplateArgs, Args, NumArgs) &&
9434 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009435 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00009436 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00009437 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009438
John McCall57500772009-12-16 12:17:52 +00009439 assert(!R.empty() && "lookup results empty despite recovery");
9440
9441 // Build an implicit member call if appropriate. Just drop the
9442 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009443 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009444 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009445 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9446 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009447 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009448 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009449 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009450 else
9451 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9452
9453 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009454 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009455
9456 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009457 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009458 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009459 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009460 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009461}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009462
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009463/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009464/// (which eventually refers to the declaration Func) and the call
9465/// arguments Args/NumArgs, attempt to resolve the function call down
9466/// to a specific function. If overload resolution succeeds, returns
9467/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009468/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009469/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009470ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009471Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009472 SourceLocation LParenLoc,
9473 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009474 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009475 Expr *ExecConfig,
9476 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009477#ifndef NDEBUG
9478 if (ULE->requiresADL()) {
9479 // To do ADL, we must have found an unqualified name.
9480 assert(!ULE->getQualifier() && "qualified name with ADL");
9481
9482 // We don't perform ADL for implicit declarations of builtins.
9483 // Verify that this was correctly set up.
9484 FunctionDecl *F;
9485 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9486 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9487 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009488 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009489
John McCall57500772009-12-16 12:17:52 +00009490 // We don't perform ADL in C.
9491 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009492 } else
9493 assert(!ULE->isStdAssociatedNamespace() &&
9494 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009495#endif
9496
John McCall4124c492011-10-17 18:40:02 +00009497 UnbridgedCastsSet UnbridgedCasts;
9498 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9499 return ExprError();
9500
John McCallbc077cf2010-02-08 23:07:23 +00009501 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009502
John McCall57500772009-12-16 12:17:52 +00009503 // Add the functions denoted by the callee to the set of candidate
9504 // functions, including those from argument-dependent lookup.
9505 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009506
9507 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009508 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9509 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009510 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009511 // In Microsoft mode, if we are inside a template class member function then
9512 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009513 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009514 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00009515 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009516 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009517 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9518 Context.DependentTy, VK_RValue,
9519 RParenLoc);
9520 CE->setTypeDependent(true);
9521 return Owned(CE);
9522 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009523 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009524 RParenLoc, /*EmptyLookup=*/true,
9525 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009526 }
John McCalld681c392009-12-16 08:11:27 +00009527
John McCall4124c492011-10-17 18:40:02 +00009528 UnbridgedCasts.restore();
9529
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009530 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009531 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009532 case OR_Success: {
9533 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009534 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009535 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009536 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009537 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009538 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9539 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009540 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009541
Richard Smith998a5912011-06-05 22:42:48 +00009542 case OR_No_Viable_Function: {
9543 // Try to recover by looking for viable functions which the user might
9544 // have meant to call.
9545 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9546 Args, NumArgs, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009547 /*EmptyLookup=*/false,
9548 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009549 if (!Recovery.isInvalid())
9550 return Recovery;
9551
Chris Lattner45d9d602009-02-17 07:29:20 +00009552 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009553 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009554 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009555 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009556 break;
Richard Smith998a5912011-06-05 22:42:48 +00009557 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009558
9559 case OR_Ambiguous:
9560 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009561 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009562 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009563 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009564
9565 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009566 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009567 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9568 << Best->Function->isDeleted()
9569 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009570 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009571 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009573
9574 // We emitted an error for the unvailable/deleted function call but keep
9575 // the call in the AST.
9576 FunctionDecl *FDecl = Best->Function;
9577 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9578 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9579 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009580 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009581 }
9582
Douglas Gregorb412e172010-07-25 18:17:45 +00009583 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009584 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009585}
9586
John McCall4c4c1df2010-01-26 03:27:55 +00009587static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009588 return Functions.size() > 1 ||
9589 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9590}
9591
Douglas Gregor084d8552009-03-13 23:49:33 +00009592/// \brief Create a unary operation that may resolve to an overloaded
9593/// operator.
9594///
9595/// \param OpLoc The location of the operator itself (e.g., '*').
9596///
9597/// \param OpcIn The UnaryOperator::Opcode that describes this
9598/// operator.
9599///
9600/// \param Functions The set of non-member functions that will be
9601/// considered by overload resolution. The caller needs to build this
9602/// set based on the context using, e.g.,
9603/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9604/// set should not contain any member functions; those will be added
9605/// by CreateOverloadedUnaryOp().
9606///
9607/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009608ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009609Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9610 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009611 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009612 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009613
9614 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9615 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9616 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009617 // TODO: provide better source location info.
9618 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009619
John McCall4124c492011-10-17 18:40:02 +00009620 if (checkPlaceholderForOverload(*this, Input))
9621 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009622
Douglas Gregor084d8552009-03-13 23:49:33 +00009623 Expr *Args[2] = { Input, 0 };
9624 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009625
Douglas Gregor084d8552009-03-13 23:49:33 +00009626 // For post-increment and post-decrement, add the implicit '0' as
9627 // the second argument, so that we know this is a post-increment or
9628 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009629 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009630 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009631 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9632 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009633 NumArgs = 2;
9634 }
9635
9636 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009637 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009638 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009639 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009640 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009641 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009642 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009643
John McCall58cc69d2010-01-27 01:50:18 +00009644 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009645 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009646 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009647 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009648 /*ADL*/ true, IsOverloaded(Fns),
9649 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009650 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009651 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009652 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009653 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009654 OpLoc));
9655 }
9656
9657 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009658 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009659
9660 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009661 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009662
9663 // Add operator candidates that are member functions.
9664 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9665
John McCall4c4c1df2010-01-26 03:27:55 +00009666 // Add candidates from ADL.
9667 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009668 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009669 /*ExplicitTemplateArgs*/ 0,
9670 CandidateSet);
9671
Douglas Gregor084d8552009-03-13 23:49:33 +00009672 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009673 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009674
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009675 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9676
Douglas Gregor084d8552009-03-13 23:49:33 +00009677 // Perform overload resolution.
9678 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009679 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009680 case OR_Success: {
9681 // We found a built-in operator or an overloaded operator.
9682 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009683
Douglas Gregor084d8552009-03-13 23:49:33 +00009684 if (FnDecl) {
9685 // We matched an overloaded operator. Build a call to that
9686 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009687
Eli Friedmanfa0df832012-02-02 03:46:19 +00009688 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009689
Douglas Gregor084d8552009-03-13 23:49:33 +00009690 // Convert the arguments.
9691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009692 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009693
John Wiegley01296292011-04-08 18:41:53 +00009694 ExprResult InputRes =
9695 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9696 Best->FoundDecl, Method);
9697 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009698 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009699 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009700 } else {
9701 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009702 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009703 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009704 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009705 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009706 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009707 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009708 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009709 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009710 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009711 }
9712
John McCall4fa0d5f2010-05-06 18:15:07 +00009713 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9714
John McCall7decc9e2010-11-18 06:31:45 +00009715 // Determine the result type.
9716 QualType ResultTy = FnDecl->getResultType();
9717 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9718 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009719
Douglas Gregor084d8552009-03-13 23:49:33 +00009720 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009721 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009722 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009723 if (FnExpr.isInvalid())
9724 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009725
Eli Friedman030eee42009-11-18 03:58:17 +00009726 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009727 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009728 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009729 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009730
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009731 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009732 FnDecl))
9733 return ExprError();
9734
John McCallb268a282010-08-23 23:25:46 +00009735 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009736 } else {
9737 // We matched a built-in operator. Convert the arguments, then
9738 // break out so that we will build the appropriate built-in
9739 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009740 ExprResult InputRes =
9741 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9742 Best->Conversions[0], AA_Passing);
9743 if (InputRes.isInvalid())
9744 return ExprError();
9745 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009746 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009747 }
John Wiegley01296292011-04-08 18:41:53 +00009748 }
9749
9750 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009751 // This is an erroneous use of an operator which can be overloaded by
9752 // a non-member function. Check for non-member operators which were
9753 // defined too late to be candidates.
9754 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9755 // FIXME: Recover by calling the found function.
9756 return ExprError();
9757
John Wiegley01296292011-04-08 18:41:53 +00009758 // No viable function; fall through to handling this as a
9759 // built-in operator, which will produce an error message for us.
9760 break;
9761
9762 case OR_Ambiguous:
9763 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9764 << UnaryOperator::getOpcodeStr(Opc)
9765 << Input->getType()
9766 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009767 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009768 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9769 return ExprError();
9770
9771 case OR_Deleted:
9772 Diag(OpLoc, diag::err_ovl_deleted_oper)
9773 << Best->Function->isDeleted()
9774 << UnaryOperator::getOpcodeStr(Opc)
9775 << getDeletedOrUnavailableSuffix(Best->Function)
9776 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009777 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9778 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009779 return ExprError();
9780 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009781
9782 // Either we found no viable overloaded operator or we matched a
9783 // built-in operator. In either case, fall through to trying to
9784 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009785 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009786}
9787
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009788/// \brief Create a binary operation that may resolve to an overloaded
9789/// operator.
9790///
9791/// \param OpLoc The location of the operator itself (e.g., '+').
9792///
9793/// \param OpcIn The BinaryOperator::Opcode that describes this
9794/// operator.
9795///
9796/// \param Functions The set of non-member functions that will be
9797/// considered by overload resolution. The caller needs to build this
9798/// set based on the context using, e.g.,
9799/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9800/// set should not contain any member functions; those will be added
9801/// by CreateOverloadedBinOp().
9802///
9803/// \param LHS Left-hand argument.
9804/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009805ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009806Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009807 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009808 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009809 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009810 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009811 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009812
9813 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9814 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9815 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9816
9817 // If either side is type-dependent, create an appropriate dependent
9818 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009819 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009820 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009822 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009823 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009824 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009825 Context.DependentTy,
9826 VK_RValue, OK_Ordinary,
9827 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009828
Douglas Gregor5287f092009-11-05 00:51:44 +00009829 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9830 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009831 VK_LValue,
9832 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009833 Context.DependentTy,
9834 Context.DependentTy,
9835 OpLoc));
9836 }
John McCall4c4c1df2010-01-26 03:27:55 +00009837
9838 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009839 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009840 // TODO: provide better source location info in DNLoc component.
9841 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009842 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009843 = UnresolvedLookupExpr::Create(Context, NamingClass,
9844 NestedNameSpecifierLoc(), OpNameInfo,
9845 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009846 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009847 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009848 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009849 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009850 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009851 OpLoc));
9852 }
9853
John McCall4124c492011-10-17 18:40:02 +00009854 // Always do placeholder-like conversions on the RHS.
9855 if (checkPlaceholderForOverload(*this, Args[1]))
9856 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009857
John McCall526ab472011-10-25 17:37:35 +00009858 // Do placeholder-like conversion on the LHS; note that we should
9859 // not get here with a PseudoObject LHS.
9860 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009861 if (checkPlaceholderForOverload(*this, Args[0]))
9862 return ExprError();
9863
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009864 // If this is the assignment operator, we only perform overload resolution
9865 // if the left-hand side is a class or enumeration type. This is actually
9866 // a hack. The standard requires that we do overload resolution between the
9867 // various built-in candidates, but as DR507 points out, this can lead to
9868 // problems. So we do it this way, which pretty much follows what GCC does.
9869 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009870 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009871 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009872
John McCalle26a8722010-12-04 08:14:53 +00009873 // If this is the .* operator, which is not overloadable, just
9874 // create a built-in binary operator.
9875 if (Opc == BO_PtrMemD)
9876 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9877
Douglas Gregor084d8552009-03-13 23:49:33 +00009878 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009879 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009880
9881 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009882 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009883
9884 // Add operator candidates that are member functions.
9885 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9886
John McCall4c4c1df2010-01-26 03:27:55 +00009887 // Add candidates from ADL.
9888 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9889 Args, 2,
9890 /*ExplicitTemplateArgs*/ 0,
9891 CandidateSet);
9892
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009893 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009894 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009895
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009896 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9897
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009898 // Perform overload resolution.
9899 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009900 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009901 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009902 // We found a built-in operator or an overloaded operator.
9903 FunctionDecl *FnDecl = Best->Function;
9904
9905 if (FnDecl) {
9906 // We matched an overloaded operator. Build a call to that
9907 // operator.
9908
Eli Friedmanfa0df832012-02-02 03:46:19 +00009909 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009910
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009911 // Convert the arguments.
9912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009913 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009914 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009915
Chandler Carruth8e543b32010-12-12 08:17:55 +00009916 ExprResult Arg1 =
9917 PerformCopyInitialization(
9918 InitializedEntity::InitializeParameter(Context,
9919 FnDecl->getParamDecl(0)),
9920 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009921 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009922 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009923
John Wiegley01296292011-04-08 18:41:53 +00009924 ExprResult Arg0 =
9925 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9926 Best->FoundDecl, Method);
9927 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009928 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009929 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009930 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009931 } else {
9932 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009933 ExprResult Arg0 = PerformCopyInitialization(
9934 InitializedEntity::InitializeParameter(Context,
9935 FnDecl->getParamDecl(0)),
9936 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009937 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009938 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009939
Chandler Carruth8e543b32010-12-12 08:17:55 +00009940 ExprResult Arg1 =
9941 PerformCopyInitialization(
9942 InitializedEntity::InitializeParameter(Context,
9943 FnDecl->getParamDecl(1)),
9944 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009945 if (Arg1.isInvalid())
9946 return ExprError();
9947 Args[0] = LHS = Arg0.takeAs<Expr>();
9948 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009949 }
9950
John McCall4fa0d5f2010-05-06 18:15:07 +00009951 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9952
John McCall7decc9e2010-11-18 06:31:45 +00009953 // Determine the result type.
9954 QualType ResultTy = FnDecl->getResultType();
9955 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9956 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009957
9958 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009959 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9960 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009961 if (FnExpr.isInvalid())
9962 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009963
John McCallb268a282010-08-23 23:25:46 +00009964 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009965 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009966 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009967
9968 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009969 FnDecl))
9970 return ExprError();
9971
John McCallb268a282010-08-23 23:25:46 +00009972 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009973 } else {
9974 // We matched a built-in operator. Convert the arguments, then
9975 // break out so that we will build the appropriate built-in
9976 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009977 ExprResult ArgsRes0 =
9978 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9979 Best->Conversions[0], AA_Passing);
9980 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009981 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009982 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009983
John Wiegley01296292011-04-08 18:41:53 +00009984 ExprResult ArgsRes1 =
9985 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9986 Best->Conversions[1], AA_Passing);
9987 if (ArgsRes1.isInvalid())
9988 return ExprError();
9989 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009990 break;
9991 }
9992 }
9993
Douglas Gregor66950a32009-09-30 21:46:01 +00009994 case OR_No_Viable_Function: {
9995 // C++ [over.match.oper]p9:
9996 // If the operator is the operator , [...] and there are no
9997 // viable functions, then the operator is assumed to be the
9998 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009999 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010000 break;
10001
Chandler Carruth8e543b32010-12-12 08:17:55 +000010002 // For class as left operand for assignment or compound assigment
10003 // operator do not fall through to handling in built-in, but report that
10004 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010005 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010006 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010007 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010008 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10009 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010011 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010012 // This is an erroneous use of an operator which can be overloaded by
10013 // a non-member function. Check for non-member operators which were
10014 // defined too late to be candidates.
10015 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
10016 // FIXME: Recover by calling the found function.
10017 return ExprError();
10018
Douglas Gregor66950a32009-09-30 21:46:01 +000010019 // No viable function; try to create a built-in operation, which will
10020 // produce an error. Then, show the non-viable candidates.
10021 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010023 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010024 "C++ binary operator overloading is missing candidates!");
10025 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +000010026 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10027 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010028 return move(Result);
10029 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010030
10031 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010032 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010033 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010034 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010035 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010036 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10037 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010038 return ExprError();
10039
10040 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010041 if (isImplicitlyDeleted(Best->Function)) {
10042 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10043 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10044 << getSpecialMember(Method)
10045 << BinaryOperator::getOpcodeStr(Opc)
10046 << getDeletedOrUnavailableSuffix(Best->Function);
10047
10048 if (Method->getParent()->isLambda()) {
10049 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
10050 return ExprError();
10051 }
10052 } else {
10053 Diag(OpLoc, diag::err_ovl_deleted_oper)
10054 << Best->Function->isDeleted()
10055 << BinaryOperator::getOpcodeStr(Opc)
10056 << getDeletedOrUnavailableSuffix(Best->Function)
10057 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10058 }
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010059 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10060 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010061 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010062 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010063
Douglas Gregor66950a32009-09-30 21:46:01 +000010064 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010065 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010066}
10067
John McCalldadc5752010-08-24 06:29:42 +000010068ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010069Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10070 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010071 Expr *Base, Expr *Idx) {
10072 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010073 DeclarationName OpName =
10074 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10075
10076 // If either side is type-dependent, create an appropriate dependent
10077 // expression.
10078 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10079
John McCall58cc69d2010-01-27 01:50:18 +000010080 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010081 // CHECKME: no 'operator' keyword?
10082 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10083 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010084 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010085 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010086 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010087 /*ADL*/ true, /*Overloaded*/ false,
10088 UnresolvedSetIterator(),
10089 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010090 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010091
Sebastian Redladba46e2009-10-29 20:17:01 +000010092 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10093 Args, 2,
10094 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010095 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010096 RLoc));
10097 }
10098
John McCall4124c492011-10-17 18:40:02 +000010099 // Handle placeholders on both operands.
10100 if (checkPlaceholderForOverload(*this, Args[0]))
10101 return ExprError();
10102 if (checkPlaceholderForOverload(*this, Args[1]))
10103 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010104
Sebastian Redladba46e2009-10-29 20:17:01 +000010105 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010106 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010107
10108 // Subscript can only be overloaded as a member function.
10109
10110 // Add operator candidates that are member functions.
10111 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10112
10113 // Add builtin operator candidates.
10114 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10115
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010116 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10117
Sebastian Redladba46e2009-10-29 20:17:01 +000010118 // Perform overload resolution.
10119 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010120 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010121 case OR_Success: {
10122 // We found a built-in operator or an overloaded operator.
10123 FunctionDecl *FnDecl = Best->Function;
10124
10125 if (FnDecl) {
10126 // We matched an overloaded operator. Build a call to that
10127 // operator.
10128
Eli Friedmanfa0df832012-02-02 03:46:19 +000010129 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010130
John McCalla0296f72010-03-19 07:35:19 +000010131 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010132 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010133
Sebastian Redladba46e2009-10-29 20:17:01 +000010134 // Convert the arguments.
10135 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010136 ExprResult Arg0 =
10137 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10138 Best->FoundDecl, Method);
10139 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010140 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010141 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010142
Anders Carlssona68e51e2010-01-29 18:37:50 +000010143 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010144 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010145 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010146 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010147 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010148 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010149 Owned(Args[1]));
10150 if (InputInit.isInvalid())
10151 return ExprError();
10152
10153 Args[1] = InputInit.takeAs<Expr>();
10154
Sebastian Redladba46e2009-10-29 20:17:01 +000010155 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010156 QualType ResultTy = FnDecl->getResultType();
10157 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10158 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010159
10160 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010161 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10162 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010163 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10164 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010165 OpLocInfo.getLoc(),
10166 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010167 if (FnExpr.isInvalid())
10168 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010169
John McCallb268a282010-08-23 23:25:46 +000010170 CXXOperatorCallExpr *TheCall =
10171 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010172 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010173 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010174
John McCallb268a282010-08-23 23:25:46 +000010175 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010176 FnDecl))
10177 return ExprError();
10178
John McCallb268a282010-08-23 23:25:46 +000010179 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010180 } else {
10181 // We matched a built-in operator. Convert the arguments, then
10182 // break out so that we will build the appropriate built-in
10183 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010184 ExprResult ArgsRes0 =
10185 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10186 Best->Conversions[0], AA_Passing);
10187 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010188 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010189 Args[0] = ArgsRes0.take();
10190
10191 ExprResult ArgsRes1 =
10192 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10193 Best->Conversions[1], AA_Passing);
10194 if (ArgsRes1.isInvalid())
10195 return ExprError();
10196 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010197
10198 break;
10199 }
10200 }
10201
10202 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010203 if (CandidateSet.empty())
10204 Diag(LLoc, diag::err_ovl_no_oper)
10205 << Args[0]->getType() << /*subscript*/ 0
10206 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10207 else
10208 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10209 << Args[0]->getType()
10210 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010211 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10212 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010213 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010214 }
10215
10216 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010217 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010218 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010219 << Args[0]->getType() << Args[1]->getType()
10220 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010221 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10222 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010223 return ExprError();
10224
10225 case OR_Deleted:
10226 Diag(LLoc, diag::err_ovl_deleted_oper)
10227 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010228 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010229 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010230 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10231 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010232 return ExprError();
10233 }
10234
10235 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010236 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010237}
10238
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010239/// BuildCallToMemberFunction - Build a call to a member
10240/// function. MemExpr is the expression that refers to the member
10241/// function (and includes the object parameter), Args/NumArgs are the
10242/// arguments to the function call (not including the object
10243/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010244/// expression refers to a non-static member function or an overloaded
10245/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010246ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010247Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10248 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010249 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010250 assert(MemExprE->getType() == Context.BoundMemberTy ||
10251 MemExprE->getType() == Context.OverloadTy);
10252
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010253 // Dig out the member expression. This holds both the object
10254 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010255 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010256
John McCall0009fcc2011-04-26 20:42:42 +000010257 // Determine whether this is a call to a pointer-to-member function.
10258 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10259 assert(op->getType() == Context.BoundMemberTy);
10260 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10261
10262 QualType fnType =
10263 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10264
10265 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10266 QualType resultType = proto->getCallResultType(Context);
10267 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10268
10269 // Check that the object type isn't more qualified than the
10270 // member function we're calling.
10271 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10272
10273 QualType objectType = op->getLHS()->getType();
10274 if (op->getOpcode() == BO_PtrMemI)
10275 objectType = objectType->castAs<PointerType>()->getPointeeType();
10276 Qualifiers objectQuals = objectType.getQualifiers();
10277
10278 Qualifiers difference = objectQuals - funcQuals;
10279 difference.removeObjCGCAttr();
10280 difference.removeAddressSpace();
10281 if (difference) {
10282 std::string qualsString = difference.getAsString();
10283 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10284 << fnType.getUnqualifiedType()
10285 << qualsString
10286 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10287 }
10288
10289 CXXMemberCallExpr *call
10290 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10291 resultType, valueKind, RParenLoc);
10292
10293 if (CheckCallReturnType(proto->getResultType(),
10294 op->getRHS()->getSourceRange().getBegin(),
10295 call, 0))
10296 return ExprError();
10297
10298 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10299 return ExprError();
10300
10301 return MaybeBindToTemporary(call);
10302 }
10303
John McCall4124c492011-10-17 18:40:02 +000010304 UnbridgedCastsSet UnbridgedCasts;
10305 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10306 return ExprError();
10307
John McCall10eae182009-11-30 22:42:35 +000010308 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010309 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010310 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010311 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010312 if (isa<MemberExpr>(NakedMemExpr)) {
10313 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010314 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010315 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010316 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010317 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010318 } else {
10319 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010320 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010321
John McCall6e9f8f62009-12-03 04:06:58 +000010322 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010323 Expr::Classification ObjectClassification
10324 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10325 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010326
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010327 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010328 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010329
John McCall2d74de92009-12-01 22:10:20 +000010330 // FIXME: avoid copy.
10331 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10332 if (UnresExpr->hasExplicitTemplateArgs()) {
10333 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10334 TemplateArgs = &TemplateArgsBuffer;
10335 }
10336
John McCall10eae182009-11-30 22:42:35 +000010337 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10338 E = UnresExpr->decls_end(); I != E; ++I) {
10339
John McCall6e9f8f62009-12-03 04:06:58 +000010340 NamedDecl *Func = *I;
10341 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10342 if (isa<UsingShadowDecl>(Func))
10343 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10344
Douglas Gregor02824322011-01-26 19:30:28 +000010345
Francois Pichet64225792011-01-18 05:04:39 +000010346 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +000010347 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +000010348 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10349 CandidateSet);
10350 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010351 // If explicit template arguments were provided, we can't call a
10352 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010353 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010354 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010355
John McCalla0296f72010-03-19 07:35:19 +000010356 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010357 ObjectClassification,
10358 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010359 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010360 } else {
John McCall10eae182009-11-30 22:42:35 +000010361 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010362 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010363 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +000010364 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010365 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010366 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010367 }
Mike Stump11289f42009-09-09 15:08:12 +000010368
John McCall10eae182009-11-30 22:42:35 +000010369 DeclarationName DeclName = UnresExpr->getMemberName();
10370
John McCall4124c492011-10-17 18:40:02 +000010371 UnbridgedCasts.restore();
10372
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010373 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010374 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010375 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010376 case OR_Success:
10377 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010378 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010379 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010380 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010381 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010382 break;
10383
10384 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010385 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010386 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010387 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010388 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010389 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010390 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010391
10392 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010393 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010394 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010395 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010396 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010397 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010398
10399 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010400 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010401 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010402 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010403 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010404 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010405 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010406 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010407 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010408 }
10409
John McCall16df1e52010-03-30 21:47:33 +000010410 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010411
John McCall2d74de92009-12-01 22:10:20 +000010412 // If overload resolution picked a static member, build a
10413 // non-member call based on that function.
10414 if (Method->isStatic()) {
10415 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10416 Args, NumArgs, RParenLoc);
10417 }
10418
John McCall10eae182009-11-30 22:42:35 +000010419 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010420 }
10421
John McCall7decc9e2010-11-18 06:31:45 +000010422 QualType ResultType = Method->getResultType();
10423 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10424 ResultType = ResultType.getNonLValueExprType(Context);
10425
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010426 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010427 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010428 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010429 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010430
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010431 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010432 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010433 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010434 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010435
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010436 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010437 // We only need to do this if there was actually an overload; otherwise
10438 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010439 if (!Method->isStatic()) {
10440 ExprResult ObjectArg =
10441 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10442 FoundDecl, Method);
10443 if (ObjectArg.isInvalid())
10444 return ExprError();
10445 MemExpr->setBase(ObjectArg.take());
10446 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010447
10448 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010449 const FunctionProtoType *Proto =
10450 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010451 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010452 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010453 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010454
Eli Friedmanff4b4072012-02-18 04:48:30 +000010455 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10456
John McCallb268a282010-08-23 23:25:46 +000010457 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010458 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010459
Anders Carlsson47061ee2011-05-06 14:25:31 +000010460 if ((isa<CXXConstructorDecl>(CurContext) ||
10461 isa<CXXDestructorDecl>(CurContext)) &&
10462 TheCall->getMethodDecl()->isPure()) {
10463 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10464
Chandler Carruth59259262011-06-27 08:31:58 +000010465 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010466 Diag(MemExpr->getLocStart(),
10467 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10468 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10469 << MD->getParent()->getDeclName();
10470
10471 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010472 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010473 }
John McCallb268a282010-08-23 23:25:46 +000010474 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010475}
10476
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010477/// BuildCallToObjectOfClassType - Build a call to an object of class
10478/// type (C++ [over.call.object]), which can end up invoking an
10479/// overloaded function call operator (@c operator()) or performing a
10480/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010481ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010482Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010483 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010484 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010485 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010486 if (checkPlaceholderForOverload(*this, Obj))
10487 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010488 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010489
10490 UnbridgedCastsSet UnbridgedCasts;
10491 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10492 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010493
John Wiegley01296292011-04-08 18:41:53 +000010494 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10495 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010496
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010497 // C++ [over.call.object]p1:
10498 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010499 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010500 // candidate functions includes at least the function call
10501 // operators of T. The function call operators of T are obtained by
10502 // ordinary lookup of the name operator() in the context of
10503 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010504 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010505 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010506
John Wiegley01296292011-04-08 18:41:53 +000010507 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010508 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010509 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010510 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010511
John McCall27b18f82009-11-17 02:14:36 +000010512 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10513 LookupQualifiedName(R, Record->getDecl());
10514 R.suppressDiagnostics();
10515
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010516 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010517 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010518 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10519 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010520 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010522
Douglas Gregorab7897a2008-11-19 22:57:39 +000010523 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010524 // In addition, for each (non-explicit in C++0x) conversion function
10525 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010526 //
10527 // operator conversion-type-id () cv-qualifier;
10528 //
10529 // where cv-qualifier is the same cv-qualification as, or a
10530 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010531 // denotes the type "pointer to function of (P1,...,Pn) returning
10532 // R", or the type "reference to pointer to function of
10533 // (P1,...,Pn) returning R", or the type "reference to function
10534 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010535 // is also considered as a candidate function. Similarly,
10536 // surrogate call functions are added to the set of candidate
10537 // functions for each conversion function declared in an
10538 // accessible base class provided the function is not hidden
10539 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010540 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010541 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010542 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010543 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010544 NamedDecl *D = *I;
10545 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10546 if (isa<UsingShadowDecl>(D))
10547 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010548
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010549 // Skip over templated conversion functions; they aren't
10550 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010551 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010552 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010553
John McCall6e9f8f62009-12-03 04:06:58 +000010554 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010555 if (!Conv->isExplicit()) {
10556 // Strip the reference type (if any) and then the pointer type (if
10557 // any) to get down to what might be a function type.
10558 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10559 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10560 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010561
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010562 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10563 {
10564 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10565 Object.get(), Args, NumArgs, CandidateSet);
10566 }
10567 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010568 }
Mike Stump11289f42009-09-09 15:08:12 +000010569
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010570 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10571
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010572 // Perform overload resolution.
10573 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010574 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010575 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010576 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010577 // Overload resolution succeeded; we'll build the appropriate call
10578 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010579 break;
10580
10581 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010582 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +000010583 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10584 << Object.get()->getType() << /*call*/ 1
10585 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010586 else
John Wiegley01296292011-04-08 18:41:53 +000010587 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +000010588 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010589 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010591 break;
10592
10593 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +000010594 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010595 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010596 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010597 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010598 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010599
10600 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010601 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010602 diag::err_ovl_deleted_object_call)
10603 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010604 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010605 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010606 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010607 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010608 break;
Mike Stump11289f42009-09-09 15:08:12 +000010609 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010610
Douglas Gregorb412e172010-07-25 18:17:45 +000010611 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010612 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010613
John McCall4124c492011-10-17 18:40:02 +000010614 UnbridgedCasts.restore();
10615
Douglas Gregorab7897a2008-11-19 22:57:39 +000010616 if (Best->Function == 0) {
10617 // Since there is no function declaration, this is one of the
10618 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010619 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010620 = cast<CXXConversionDecl>(
10621 Best->Conversions[0].UserDefined.ConversionFunction);
10622
John Wiegley01296292011-04-08 18:41:53 +000010623 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010624 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010625
Douglas Gregorab7897a2008-11-19 22:57:39 +000010626 // We selected one of the surrogate functions that converts the
10627 // object parameter to a function pointer. Perform the conversion
10628 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010629
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010630 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010631 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010632 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10633 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010634 if (Call.isInvalid())
10635 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010636 // Record usage of conversion in an implicit cast.
10637 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10638 CK_UserDefinedConversion,
10639 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010640
Douglas Gregor668443e2011-01-20 00:18:04 +000010641 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010642 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010643 }
10644
Eli Friedmanfa0df832012-02-02 03:46:19 +000010645 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010646 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010647 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010648
Douglas Gregorab7897a2008-11-19 22:57:39 +000010649 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10650 // that calls this method, using Object for the implicit object
10651 // parameter and passing along the remaining arguments.
10652 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010653 const FunctionProtoType *Proto =
10654 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010655
10656 unsigned NumArgsInProto = Proto->getNumArgs();
10657 unsigned NumArgsToCheck = NumArgs;
10658
10659 // Build the full argument list for the method call (the
10660 // implicit object parameter is placed at the beginning of the
10661 // list).
10662 Expr **MethodArgs;
10663 if (NumArgs < NumArgsInProto) {
10664 NumArgsToCheck = NumArgsInProto;
10665 MethodArgs = new Expr*[NumArgsInProto + 1];
10666 } else {
10667 MethodArgs = new Expr*[NumArgs + 1];
10668 }
John Wiegley01296292011-04-08 18:41:53 +000010669 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10671 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010672
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010673 DeclarationNameInfo OpLocInfo(
10674 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10675 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010676 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010677 HadMultipleCandidates,
10678 OpLocInfo.getLoc(),
10679 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010680 if (NewFn.isInvalid())
10681 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010682
10683 // Once we've built TheCall, all of the expressions are properly
10684 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010685 QualType ResultTy = Method->getResultType();
10686 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10687 ResultTy = ResultTy.getNonLValueExprType(Context);
10688
John McCallb268a282010-08-23 23:25:46 +000010689 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010690 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010691 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010692 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010693 delete [] MethodArgs;
10694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010695 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010696 Method))
10697 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010698
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010699 // We may have default arguments. If so, we need to allocate more
10700 // slots in the call for them.
10701 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010702 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010703 else if (NumArgs > NumArgsInProto)
10704 NumArgsToCheck = NumArgsInProto;
10705
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010706 bool IsError = false;
10707
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010708 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010709 ExprResult ObjRes =
10710 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10711 Best->FoundDecl, Method);
10712 if (ObjRes.isInvalid())
10713 IsError = true;
10714 else
10715 Object = move(ObjRes);
10716 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010717
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010718 // Check the argument types.
10719 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010720 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010721 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010722 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010723
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010724 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010725
John McCalldadc5752010-08-24 06:29:42 +000010726 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010727 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010728 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010729 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010730 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010731
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010732 IsError |= InputInit.isInvalid();
10733 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010734 } else {
John McCalldadc5752010-08-24 06:29:42 +000010735 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010736 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10737 if (DefArg.isInvalid()) {
10738 IsError = true;
10739 break;
10740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010741
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010742 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010743 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010744
10745 TheCall->setArg(i + 1, Arg);
10746 }
10747
10748 // If this is a variadic call, handle args passed through "...".
10749 if (Proto->isVariadic()) {
10750 // Promote the arguments (C99 6.5.2.2p7).
10751 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010752 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10753 IsError |= Arg.isInvalid();
10754 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010755 }
10756 }
10757
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010758 if (IsError) return true;
10759
Eli Friedmanff4b4072012-02-18 04:48:30 +000010760 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10761
John McCallb268a282010-08-23 23:25:46 +000010762 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010763 return true;
10764
John McCalle172be52010-08-24 06:09:16 +000010765 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010766}
10767
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010768/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010769/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010770/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010771ExprResult
John McCallb268a282010-08-23 23:25:46 +000010772Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010773 assert(Base->getType()->isRecordType() &&
10774 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010775
John McCall4124c492011-10-17 18:40:02 +000010776 if (checkPlaceholderForOverload(*this, Base))
10777 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010778
John McCallbc077cf2010-02-08 23:07:23 +000010779 SourceLocation Loc = Base->getExprLoc();
10780
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010781 // C++ [over.ref]p1:
10782 //
10783 // [...] An expression x->m is interpreted as (x.operator->())->m
10784 // for a class object x of type T if T::operator->() exists and if
10785 // the operator is selected as the best match function by the
10786 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010787 DeclarationName OpName =
10788 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010789 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010790 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010791
John McCallbc077cf2010-02-08 23:07:23 +000010792 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010793 PDiag(diag::err_typecheck_incomplete_tag)
10794 << Base->getSourceRange()))
10795 return ExprError();
10796
John McCall27b18f82009-11-17 02:14:36 +000010797 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10798 LookupQualifiedName(R, BaseRecord->getDecl());
10799 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010800
10801 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010802 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010803 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10804 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010805 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010806
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010807 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10808
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010809 // Perform overload resolution.
10810 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010811 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010812 case OR_Success:
10813 // Overload resolution succeeded; we'll build the call below.
10814 break;
10815
10816 case OR_No_Viable_Function:
10817 if (CandidateSet.empty())
10818 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010819 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010820 else
10821 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010822 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010824 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010825
10826 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010827 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10828 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010829 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010830 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010831
10832 case OR_Deleted:
10833 Diag(OpLoc, diag::err_ovl_deleted_oper)
10834 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010835 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010836 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010837 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010838 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010839 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010840 }
10841
Eli Friedmanfa0df832012-02-02 03:46:19 +000010842 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010843 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010844 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010845
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010846 // Convert the object parameter.
10847 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010848 ExprResult BaseResult =
10849 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10850 Best->FoundDecl, Method);
10851 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010852 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010853 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010854
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010855 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010856 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010857 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010858 if (FnExpr.isInvalid())
10859 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010860
John McCall7decc9e2010-11-18 06:31:45 +000010861 QualType ResultTy = Method->getResultType();
10862 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10863 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010864 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010865 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010866 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010867
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010868 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010869 Method))
10870 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010871
10872 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010873}
10874
Douglas Gregorcd695e52008-11-10 20:40:00 +000010875/// FixOverloadedFunctionReference - E is an expression that refers to
10876/// a C++ overloaded function (possibly with some parentheses and
10877/// perhaps a '&' around it). We have resolved the overloaded function
10878/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010879/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010880Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010881 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010882 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010883 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10884 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010885 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010886 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010887
Douglas Gregor51c538b2009-11-20 19:42:02 +000010888 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010889 }
10890
Douglas Gregor51c538b2009-11-20 19:42:02 +000010891 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010892 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10893 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010894 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010895 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010896 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010897 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010898 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010899 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010900
10901 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010902 ICE->getCastKind(),
10903 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010904 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010905 }
10906
Douglas Gregor51c538b2009-11-20 19:42:02 +000010907 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010908 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010909 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10911 if (Method->isStatic()) {
10912 // Do nothing: static member functions aren't any different
10913 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010914 } else {
John McCalle66edc12009-11-24 19:00:30 +000010915 // Fix the sub expression, which really has to be an
10916 // UnresolvedLookupExpr holding an overloaded member function
10917 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010918 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10919 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010920 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010921 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010922
John McCalld14a8642009-11-21 08:51:07 +000010923 assert(isa<DeclRefExpr>(SubExpr)
10924 && "fixed to something other than a decl ref");
10925 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10926 && "fixed to a member ref with no nested name qualifier");
10927
10928 // We have taken the address of a pointer to member
10929 // function. Perform the computation here so that we get the
10930 // appropriate pointer to member type.
10931 QualType ClassType
10932 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10933 QualType MemPtrType
10934 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10935
John McCall7decc9e2010-11-18 06:31:45 +000010936 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10937 VK_RValue, OK_Ordinary,
10938 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010939 }
10940 }
John McCall16df1e52010-03-30 21:47:33 +000010941 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10942 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010943 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010944 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010945
John McCalle3027922010-08-25 11:45:40 +000010946 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010947 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010948 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010949 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010950 }
John McCalld14a8642009-11-21 08:51:07 +000010951
10952 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010953 // FIXME: avoid copy.
10954 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010955 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010956 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10957 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010958 }
10959
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010960 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10961 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000010962 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010963 Fn,
10964 ULE->getNameLoc(),
10965 Fn->getType(),
10966 VK_LValue,
10967 Found.getDecl(),
10968 TemplateArgs);
10969 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10970 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010971 }
10972
John McCall10eae182009-11-30 22:42:35 +000010973 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010974 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010975 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10976 if (MemExpr->hasExplicitTemplateArgs()) {
10977 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10978 TemplateArgs = &TemplateArgsBuffer;
10979 }
John McCall6b51f282009-11-23 01:53:49 +000010980
John McCall2d74de92009-12-01 22:10:20 +000010981 Expr *Base;
10982
John McCall7decc9e2010-11-18 06:31:45 +000010983 // If we're filling in a static method where we used to have an
10984 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010985 if (MemExpr->isImplicitAccess()) {
10986 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010987 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10988 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000010989 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010990 Fn,
10991 MemExpr->getMemberLoc(),
10992 Fn->getType(),
10993 VK_LValue,
10994 Found.getDecl(),
10995 TemplateArgs);
10996 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10997 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010998 } else {
10999 SourceLocation Loc = MemExpr->getMemberLoc();
11000 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011001 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011002 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011003 Base = new (Context) CXXThisExpr(Loc,
11004 MemExpr->getBaseType(),
11005 /*isImplicit=*/true);
11006 }
John McCall2d74de92009-12-01 22:10:20 +000011007 } else
John McCallc3007a22010-10-26 07:05:15 +000011008 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011009
John McCall4adb38c2011-04-27 00:36:17 +000011010 ExprValueKind valueKind;
11011 QualType type;
11012 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11013 valueKind = VK_LValue;
11014 type = Fn->getType();
11015 } else {
11016 valueKind = VK_RValue;
11017 type = Context.BoundMemberTy;
11018 }
11019
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011020 MemberExpr *ME = MemberExpr::Create(Context, Base,
11021 MemExpr->isArrow(),
11022 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011023 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011024 Fn,
11025 Found,
11026 MemExpr->getMemberNameInfo(),
11027 TemplateArgs,
11028 type, valueKind, OK_Ordinary);
11029 ME->setHadMultipleCandidates(true);
11030 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011032
John McCallc3007a22010-10-26 07:05:15 +000011033 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011034}
11035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011036ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011037 DeclAccessPair Found,
11038 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011039 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011040}
11041
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011042} // end namespace clang