blob: ff227eee6e17aa73bf2a50c240097646661e5af9 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000044 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith66e05fe2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000296
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) {
John McCall4124c492011-10-17 18:40:02 +0000743 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
744 // We can't handle overloaded expressions here because overload
745 // resolution might reasonably tweak them.
746 if (placeholder->getKind() == BuiltinType::Overload) return false;
747
748 // If the context potentially accepts unbridged ARC casts, strip
749 // the unbridged cast and add it to the collection for later restoration.
750 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
751 unbridgedCasts) {
752 unbridgedCasts->save(S, E);
753 return false;
754 }
755
756 // Go ahead and check everything else.
757 ExprResult result = S.CheckPlaceholderExpr(E);
758 if (result.isInvalid())
759 return true;
760
761 E = result.take();
762 return false;
763 }
764
765 // Nothing to do.
766 return false;
767}
768
769/// checkArgPlaceholdersForOverload - Check a set of call operands for
770/// placeholders.
771static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
772 unsigned numArgs,
773 UnbridgedCastsSet &unbridged) {
774 for (unsigned i = 0; i != numArgs; ++i)
775 if (checkPlaceholderForOverload(S, args[i], &unbridged))
776 return true;
777
778 return false;
779}
780
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000782// overload of the declarations in Old. This routine returns false if
783// New and Old cannot be overloaded, e.g., if New has the same
784// signature as some function in Old (C++ 1.3.10) or if the Old
785// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000786// it does return false, MatchedDecl will point to the decl that New
787// cannot be overloaded with. This decl may be a UsingShadowDecl on
788// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789//
790// Example: Given the following input:
791//
792// void f(int, float); // #1
793// void f(int, int); // #2
794// int f(int, int); // #3
795//
796// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000797// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798//
John McCall3d988d92009-12-02 08:47:38 +0000799// When we process #2, Old contains only the FunctionDecl for #1. By
800// comparing the parameter types, we see that #1 and #2 are overloaded
801// (since they have different signatures), so this routine returns
802// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803//
John McCall3d988d92009-12-02 08:47:38 +0000804// When we process #3, Old is an overload set containing #1 and #2. We
805// compare the signatures of #3 to #1 (they're overloaded, so we do
806// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
807// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808// signature), IsOverload returns false and MatchedDecl will be set to
809// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000810//
811// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
812// into a class by a using declaration. The rules for whether to hide
813// shadow declarations ignore some properties which otherwise figure
814// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000815Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000816Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
817 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000818 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000819 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000820 NamedDecl *OldD = *I;
821
822 bool OldIsUsingDecl = false;
823 if (isa<UsingShadowDecl>(OldD)) {
824 OldIsUsingDecl = true;
825
826 // We can always introduce two using declarations into the same
827 // context, even if they have identical signatures.
828 if (NewIsUsingDecl) continue;
829
830 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
831 }
832
833 // If either declaration was introduced by a using declaration,
834 // we'll need to use slightly different rules for matching.
835 // Essentially, these rules are the normal rules, except that
836 // function templates hide function templates with different
837 // return types or template parameter lists.
838 bool UseMemberUsingDeclRules =
839 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
840
John McCall3d988d92009-12-02 08:47:38 +0000841 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000842 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
843 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
844 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
845 continue;
846 }
847
John McCalldaa3d6b2009-12-09 03:35:25 +0000848 Match = *I;
849 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000850 }
John McCall3d988d92009-12-02 08:47:38 +0000851 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000852 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
853 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
854 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
855 continue;
856 }
857
John McCalldaa3d6b2009-12-09 03:35:25 +0000858 Match = *I;
859 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000860 }
John McCalla8987a2942010-11-10 03:01:53 +0000861 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000862 // We can overload with these, which can show up when doing
863 // redeclaration checks for UsingDecls.
864 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000865 } else if (isa<TagDecl>(OldD)) {
866 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000867 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
868 // Optimistically assume that an unresolved using decl will
869 // overload; if it doesn't, we'll have to diagnose during
870 // template instantiation.
871 } else {
John McCall1f82f242009-11-18 22:49:29 +0000872 // (C++ 13p1):
873 // Only function declarations can be overloaded; object and type
874 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000875 Match = *I;
876 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000877 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 }
John McCall1f82f242009-11-18 22:49:29 +0000879
John McCalldaa3d6b2009-12-09 03:35:25 +0000880 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000881}
882
John McCalle9cccd82010-06-16 08:42:20 +0000883bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
884 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000885 // If both of the functions are extern "C", then they are not
886 // overloads.
887 if (Old->isExternC() && New->isExternC())
888 return false;
889
John McCall1f82f242009-11-18 22:49:29 +0000890 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
891 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
892
893 // C++ [temp.fct]p2:
894 // A function template can be overloaded with other function templates
895 // and with normal (non-template) functions.
896 if ((OldTemplate == 0) != (NewTemplate == 0))
897 return true;
898
899 // Is the function New an overload of the function Old?
900 QualType OldQType = Context.getCanonicalType(Old->getType());
901 QualType NewQType = Context.getCanonicalType(New->getType());
902
903 // Compare the signatures (C++ 1.3.10) of the two functions to
904 // determine whether they are overloads. If we find any mismatch
905 // in the signature, they are overloads.
906
907 // If either of these functions is a K&R-style function (no
908 // prototype), then we consider them to have matching signatures.
909 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
910 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
911 return false;
912
John McCall424cec92011-01-19 06:33:43 +0000913 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
914 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000915
916 // The signature of a function includes the types of its
917 // parameters (C++ 1.3.10), which includes the presence or absence
918 // of the ellipsis; see C++ DR 357).
919 if (OldQType != NewQType &&
920 (OldType->getNumArgs() != NewType->getNumArgs() ||
921 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000922 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000923 return true;
924
925 // C++ [temp.over.link]p4:
926 // The signature of a function template consists of its function
927 // signature, its return type and its template parameter list. The names
928 // of the template parameters are significant only for establishing the
929 // relationship between the template parameters and the rest of the
930 // signature.
931 //
932 // We check the return type and template parameter lists for function
933 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000934 //
935 // However, we don't consider either of these when deciding whether
936 // a member introduced by a shadow declaration is hidden.
937 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000938 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
939 OldTemplate->getTemplateParameters(),
940 false, TPL_TemplateMatch) ||
941 OldType->getResultType() != NewType->getResultType()))
942 return true;
943
944 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000945 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000946 //
947 // As part of this, also check whether one of the member functions
948 // is static, in which case they are not overloads (C++
949 // 13.1p2). While not part of the definition of the signature,
950 // this check is important to determine whether these functions
951 // can be overloaded.
952 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
953 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
954 if (OldMethod && NewMethod &&
955 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000956 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000957 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
958 if (!UseUsingDeclRules &&
959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
960 (OldMethod->getRefQualifier() == RQ_None ||
961 NewMethod->getRefQualifier() == RQ_None)) {
962 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963 // - Member function declarations with the same name and the same
964 // parameter-type-list as well as member function template
965 // declarations with the same name, the same parameter-type-list, and
966 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000967 // them, but not all, have a ref-qualifier (8.3.5).
968 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
969 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
970 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
John McCall1f82f242009-11-18 22:49:29 +0000973 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
John McCall1f82f242009-11-18 22:49:29 +0000976 // The signatures match; this is not an overload.
977 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000978}
979
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000980/// \brief Checks availability of the function depending on the current
981/// function context. Inside an unavailable function, unavailability is ignored.
982///
983/// \returns true if \arg FD is unavailable and current context is inside
984/// an available function, false otherwise.
985bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
986 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
987}
988
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000989/// \brief Tries a user-defined conversion from From to ToType.
990///
991/// Produces an implicit conversion sequence for when a standard conversion
992/// is not an option. See TryImplicitConversion for more information.
993static ImplicitConversionSequence
994TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
995 bool SuppressUserConversions,
996 bool AllowExplicit,
997 bool InOverloadResolution,
998 bool CStyle,
999 bool AllowObjCWritebackConversion) {
1000 ImplicitConversionSequence ICS;
1001
1002 if (SuppressUserConversions) {
1003 // We're not in the case above, so there is no conversion that
1004 // we can perform.
1005 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1006 return ICS;
1007 }
1008
1009 // Attempt user-defined conversion.
1010 OverloadCandidateSet Conversions(From->getExprLoc());
1011 OverloadingResult UserDefResult
1012 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1013 AllowExplicit);
1014
1015 if (UserDefResult == OR_Success) {
1016 ICS.setUserDefined();
1017 // C++ [over.ics.user]p4:
1018 // A conversion of an expression of class type to the same class
1019 // type is given Exact Match rank, and a conversion of an
1020 // expression of class type to a base class of that type is
1021 // given Conversion rank, in spite of the fact that a copy
1022 // constructor (i.e., a user-defined conversion function) is
1023 // called for those cases.
1024 if (CXXConstructorDecl *Constructor
1025 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1026 QualType FromCanon
1027 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1028 QualType ToCanon
1029 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1030 if (Constructor->isCopyConstructor() &&
1031 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1032 // Turn this into a "standard" conversion sequence, so that it
1033 // gets ranked with standard conversion sequences.
1034 ICS.setStandard();
1035 ICS.Standard.setAsIdentityConversion();
1036 ICS.Standard.setFromType(From->getType());
1037 ICS.Standard.setAllToTypes(ToType);
1038 ICS.Standard.CopyConstructor = Constructor;
1039 if (ToCanon != FromCanon)
1040 ICS.Standard.Second = ICK_Derived_To_Base;
1041 }
1042 }
1043
1044 // C++ [over.best.ics]p4:
1045 // However, when considering the argument of a user-defined
1046 // conversion function that is a candidate by 13.3.1.3 when
1047 // invoked for the copying of the temporary in the second step
1048 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1049 // 13.3.1.6 in all cases, only standard conversion sequences and
1050 // ellipsis conversion sequences are allowed.
1051 if (SuppressUserConversions && ICS.isUserDefined()) {
1052 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1053 }
1054 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1055 ICS.setAmbiguous();
1056 ICS.Ambiguous.setFromType(From->getType());
1057 ICS.Ambiguous.setToType(ToType);
1058 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1059 Cand != Conversions.end(); ++Cand)
1060 if (Cand->Viable)
1061 ICS.Ambiguous.addConversion(Cand->Function);
1062 } else {
1063 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064 }
1065
1066 return ICS;
1067}
1068
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001069/// TryImplicitConversion - Attempt to perform an implicit conversion
1070/// from the given expression (Expr) to the given type (ToType). This
1071/// function returns an implicit conversion sequence that can be used
1072/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073///
1074/// void f(float f);
1075/// void g(int i) { f(i); }
1076///
1077/// this routine would produce an implicit conversion sequence to
1078/// describe the initialization of f from i, which will be a standard
1079/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1080/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1081//
1082/// Note that this routine only determines how the conversion can be
1083/// performed; it does not actually perform the conversion. As such,
1084/// it will not produce any diagnostics if no conversion is available,
1085/// but will instead return an implicit conversion sequence of kind
1086/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001087///
1088/// If @p SuppressUserConversions, then user-defined conversions are
1089/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001090/// If @p AllowExplicit, then explicit user-defined conversions are
1091/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001092///
1093/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1094/// writeback conversion, which allows __autoreleasing id* parameters to
1095/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001096static ImplicitConversionSequence
1097TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1098 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001100 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001101 bool CStyle,
1102 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001104 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001105 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001106 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001107 return ICS;
1108 }
1109
David Blaikiebbafb8a2012-03-11 07:00:24 +00001110 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001111 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001112 return ICS;
1113 }
1114
Douglas Gregor836a7e82010-08-11 02:15:33 +00001115 // C++ [over.ics.user]p4:
1116 // A conversion of an expression of class type to the same class
1117 // type is given Exact Match rank, and a conversion of an
1118 // expression of class type to a base class of that type is
1119 // given Conversion rank, in spite of the fact that a copy/move
1120 // constructor (i.e., a user-defined conversion function) is
1121 // called for those cases.
1122 QualType FromType = From->getType();
1123 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001124 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1125 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001126 ICS.setStandard();
1127 ICS.Standard.setAsIdentityConversion();
1128 ICS.Standard.setFromType(FromType);
1129 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130
Douglas Gregor5ab11652010-04-17 22:01:05 +00001131 // We don't actually check at this point whether there is a valid
1132 // copy/move constructor, since overloading just assumes that it
1133 // exists. When we actually perform initialization, we'll find the
1134 // appropriate constructor to copy the returned object, if needed.
1135 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136
Douglas Gregor5ab11652010-04-17 22:01:05 +00001137 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001138 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001139 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Douglas Gregor836a7e82010-08-11 02:15:33 +00001141 return ICS;
1142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001144 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1145 AllowExplicit, InOverloadResolution, CStyle,
1146 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147}
1148
John McCall31168b02011-06-15 23:02:42 +00001149ImplicitConversionSequence
1150Sema::TryImplicitConversion(Expr *From, QualType ToType,
1151 bool SuppressUserConversions,
1152 bool AllowExplicit,
1153 bool InOverloadResolution,
1154 bool CStyle,
1155 bool AllowObjCWritebackConversion) {
1156 return clang::TryImplicitConversion(*this, From, ToType,
1157 SuppressUserConversions, AllowExplicit,
1158 InOverloadResolution, CStyle,
1159 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001160}
1161
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001162/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001163/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001164/// converted expression. Flavor is the kind of conversion we're
1165/// performing, used in the error message. If @p AllowExplicit,
1166/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001167ExprResult
1168Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001169 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001170 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001171 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001172}
1173
John Wiegley01296292011-04-08 18:41:53 +00001174ExprResult
1175Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001176 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001177 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001178 if (checkPlaceholderForOverload(*this, From))
1179 return ExprError();
1180
John McCall31168b02011-06-15 23:02:42 +00001181 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1182 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001183 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001184 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001185
John McCall5c32be02010-08-24 20:38:10 +00001186 ICS = clang::TryImplicitConversion(*this, From, ToType,
1187 /*SuppressUserConversions=*/false,
1188 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001189 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001190 /*CStyle=*/false,
1191 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001192 return PerformImplicitConversion(From, ToType, ICS, Action);
1193}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194
1195/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001196/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001197bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1198 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001199 if (Context.hasSameUnqualifiedType(FromType, ToType))
1200 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001201
John McCall991eb4b2010-12-21 00:44:39 +00001202 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1203 // where F adds one of the following at most once:
1204 // - a pointer
1205 // - a member pointer
1206 // - a block pointer
1207 CanQualType CanTo = Context.getCanonicalType(ToType);
1208 CanQualType CanFrom = Context.getCanonicalType(FromType);
1209 Type::TypeClass TyClass = CanTo->getTypeClass();
1210 if (TyClass != CanFrom->getTypeClass()) return false;
1211 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1212 if (TyClass == Type::Pointer) {
1213 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1214 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1215 } else if (TyClass == Type::BlockPointer) {
1216 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1217 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1218 } else if (TyClass == Type::MemberPointer) {
1219 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1220 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1221 } else {
1222 return false;
1223 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001224
John McCall991eb4b2010-12-21 00:44:39 +00001225 TyClass = CanTo->getTypeClass();
1226 if (TyClass != CanFrom->getTypeClass()) return false;
1227 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1228 return false;
1229 }
1230
1231 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1232 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1233 if (!EInfo.getNoReturn()) return false;
1234
1235 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1236 assert(QualType(FromFn, 0).isCanonical());
1237 if (QualType(FromFn, 0) != CanTo) return false;
1238
1239 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001240 return true;
1241}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242
Douglas Gregor46188682010-05-18 22:42:18 +00001243/// \brief Determine whether the conversion from FromType to ToType is a valid
1244/// vector conversion.
1245///
1246/// \param ICK Will be set to the vector conversion kind, if this is a vector
1247/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1249 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001250 // We need at least one of these types to be a vector type to have a vector
1251 // conversion.
1252 if (!ToType->isVectorType() && !FromType->isVectorType())
1253 return false;
1254
1255 // Identical types require no conversions.
1256 if (Context.hasSameUnqualifiedType(FromType, ToType))
1257 return false;
1258
1259 // There are no conversions between extended vector types, only identity.
1260 if (ToType->isExtVectorType()) {
1261 // There are no conversions between extended vector types other than the
1262 // identity conversion.
1263 if (FromType->isExtVectorType())
1264 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor46188682010-05-18 22:42:18 +00001266 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001267 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001268 ICK = ICK_Vector_Splat;
1269 return true;
1270 }
1271 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001272
1273 // We can perform the conversion between vector types in the following cases:
1274 // 1)vector types are equivalent AltiVec and GCC vector types
1275 // 2)lax vector conversions are permitted and the vector types are of the
1276 // same size
1277 if (ToType->isVectorType() && FromType->isVectorType()) {
1278 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001279 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001280 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001281 ICK = ICK_Vector_Conversion;
1282 return true;
1283 }
Douglas Gregor46188682010-05-18 22:42:18 +00001284 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001285
Douglas Gregor46188682010-05-18 22:42:18 +00001286 return false;
1287}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001288
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001289/// IsStandardConversion - Determines whether there is a standard
1290/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1291/// expression From to the type ToType. Standard conversion sequences
1292/// only consider non-class types; for conversions that involve class
1293/// types, use TryImplicitConversion. If a conversion exists, SCS will
1294/// contain the standard conversion sequence required to perform this
1295/// conversion and this routine will return true. Otherwise, this
1296/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001297static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1298 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001299 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001300 bool CStyle,
1301 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001303
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001304 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001305 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001306 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001307 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001308 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001309 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001310
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001311 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001312 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001313 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001314 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001315 return false;
1316
Mike Stump11289f42009-09-09 15:08:12 +00001317 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001318 }
1319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001320 // The first conversion can be an lvalue-to-rvalue conversion,
1321 // array-to-pointer conversion, or function-to-pointer conversion
1322 // (C++ 4p1).
1323
John McCall5c32be02010-08-24 20:38:10 +00001324 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001325 DeclAccessPair AccessPair;
1326 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001328 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001329 // We were able to resolve the address of the overloaded function,
1330 // so we can convert to the type of that function.
1331 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001332
1333 // we can sometimes resolve &foo<int> regardless of ToType, so check
1334 // if the type matches (identity) or we are converting to bool
1335 if (!S.Context.hasSameUnqualifiedType(
1336 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1337 QualType resultTy;
1338 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001339 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001340 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1341 // otherwise, only a boolean conversion is standard
1342 if (!ToType->isBooleanType())
1343 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Chandler Carruthffce2452011-03-29 08:08:18 +00001346 // Check if the "from" expression is taking the address of an overloaded
1347 // function and recompute the FromType accordingly. Take advantage of the
1348 // fact that non-static member functions *must* have such an address-of
1349 // expression.
1350 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1351 if (Method && !Method->isStatic()) {
1352 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1353 "Non-unary operator on non-static member address");
1354 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1355 == UO_AddrOf &&
1356 "Non-address-of operator on non-static member address");
1357 const Type *ClassType
1358 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1359 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001360 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1361 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1362 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001363 "Non-address-of operator for overloaded function expression");
1364 FromType = S.Context.getPointerType(FromType);
1365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
Douglas Gregor980fb162010-04-29 18:24:40 +00001367 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001368 assert(S.Context.hasSameType(
1369 FromType,
1370 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001371 } else {
1372 return false;
1373 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001374 }
John McCall154a2fd2011-08-30 00:57:29 +00001375 // Lvalue-to-rvalue conversion (C++11 4.1):
1376 // A glvalue (3.10) of a non-function, non-array type T can
1377 // be converted to a prvalue.
1378 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001379 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001380 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001381 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001382 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001383
1384 // If T is a non-class type, the type of the rvalue is the
1385 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001386 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1387 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001388 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001389 } else if (FromType->isArrayType()) {
1390 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001391 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392
1393 // An lvalue or rvalue of type "array of N T" or "array of unknown
1394 // bound of T" can be converted to an rvalue of type "pointer to
1395 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001396 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397
John McCall5c32be02010-08-24 20:38:10 +00001398 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001400 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001401
1402 // For the purpose of ranking in overload resolution
1403 // (13.3.3.1.1), this conversion is considered an
1404 // array-to-pointer conversion followed by a qualification
1405 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001406 SCS.Second = ICK_Identity;
1407 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001408 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001409 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001410 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411 }
John McCall086a4642010-11-24 05:12:34 +00001412 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001413 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001414 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415
1416 // An lvalue of function type T can be converted to an rvalue of
1417 // type "pointer to T." The result is a pointer to the
1418 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001419 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001420 } else {
1421 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001422 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001424 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425
1426 // The second conversion can be an integral promotion, floating
1427 // point promotion, integral conversion, floating point conversion,
1428 // floating-integral conversion, pointer conversion,
1429 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001430 // For overloading in C, this can also be a "compatible-type"
1431 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001432 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001433 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001434 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435 // The unqualified versions of the types are the same: there's no
1436 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001437 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001438 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001439 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001440 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001441 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001442 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001443 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001446 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001447 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001448 SCS.Second = ICK_Complex_Promotion;
1449 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001450 } else if (ToType->isBooleanType() &&
1451 (FromType->isArithmeticType() ||
1452 FromType->isAnyPointerType() ||
1453 FromType->isBlockPointerType() ||
1454 FromType->isMemberPointerType() ||
1455 FromType->isNullPtrType())) {
1456 // Boolean conversions (C++ 4.12).
1457 SCS.Second = ICK_Boolean_Conversion;
1458 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001459 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001460 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001461 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001463 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001464 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001465 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001466 SCS.Second = ICK_Complex_Conversion;
1467 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001468 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1469 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001470 // Complex-real conversions (C99 6.3.1.7)
1471 SCS.Second = ICK_Complex_Real;
1472 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001473 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001474 // Floating point conversions (C++ 4.8).
1475 SCS.Second = ICK_Floating_Conversion;
1476 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001478 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001479 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001480 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001481 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001484 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001485 SCS.Second = ICK_Block_Pointer_Conversion;
1486 } else if (AllowObjCWritebackConversion &&
1487 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1488 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001489 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1490 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001491 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001493 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001494 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001496 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001497 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001498 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001499 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001500 SCS.Second = SecondICK;
1501 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001502 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001503 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001504 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001505 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001506 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001507 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001508 // Treat a conversion that strips "noreturn" as an identity conversion.
1509 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001510 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1511 InOverloadResolution,
1512 SCS, CStyle)) {
1513 SCS.Second = ICK_TransparentUnionConversion;
1514 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001515 } else {
1516 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001518 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001519 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001521 QualType CanonFrom;
1522 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001524 bool ObjCLifetimeConversion;
1525 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1526 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001528 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001530 CanonFrom = S.Context.getCanonicalType(FromType);
1531 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001532 } else {
1533 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 SCS.Third = ICK_Identity;
1535
Mike Stump11289f42009-09-09 15:08:12 +00001536 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 // [...] Any difference in top-level cv-qualification is
1538 // subsumed by the initialization itself and does not constitute
1539 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001540 CanonFrom = S.Context.getCanonicalType(FromType);
1541 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001543 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001544 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001545 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1546 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001547 FromType = ToType;
1548 CanonFrom = CanonTo;
1549 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001551 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552
1553 // If we have not converted the argument type to the parameter type,
1554 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001555 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001560
1561static bool
1562IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1563 QualType &ToType,
1564 bool InOverloadResolution,
1565 StandardConversionSequence &SCS,
1566 bool CStyle) {
1567
1568 const RecordType *UT = ToType->getAsUnionType();
1569 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1570 return false;
1571 // The field to initialize within the transparent union.
1572 RecordDecl *UD = UT->getDecl();
1573 // It's compatible if the expression matches any of the fields.
1574 for (RecordDecl::field_iterator it = UD->field_begin(),
1575 itend = UD->field_end();
1576 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001577 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1578 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001579 ToType = it->getType();
1580 return true;
1581 }
1582 }
1583 return false;
1584}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585
1586/// IsIntegralPromotion - Determines whether the conversion from the
1587/// expression From (whose potentially-adjusted type is FromType) to
1588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1589/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001591 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001592 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001593 if (!To) {
1594 return false;
1595 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596
1597 // An rvalue of type char, signed char, unsigned char, short int, or
1598 // unsigned short int can be converted to an rvalue of type int if
1599 // int can represent all the values of the source type; otherwise,
1600 // the source rvalue can be converted to an rvalue of type unsigned
1601 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001602 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1603 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604 if (// We can promote any signed, promotable integer type to an int
1605 (FromType->isSignedIntegerType() ||
1606 // We can promote any unsigned integer type whose size is
1607 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001608 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001609 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001611 }
1612
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001613 return To->getKind() == BuiltinType::UInt;
1614 }
1615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616 // C++0x [conv.prom]p3:
1617 // A prvalue of an unscoped enumeration type whose underlying type is not
1618 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1619 // following types that can represent all the values of the enumeration
1620 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1621 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001622 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001624 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001625 // with lowest integer conversion rank (4.13) greater than the rank of long
1626 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001627 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001628 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1629 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1630 // provided for a scoped enumeration.
1631 if (FromEnumType->getDecl()->isScoped())
1632 return false;
1633
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001634 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001635 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001636 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001637 return Context.hasSameUnqualifiedType(ToType,
1638 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001639 }
John McCall56774992009-12-09 09:09:27 +00001640
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001641 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1643 // to an rvalue a prvalue of the first of the following types that can
1644 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001645 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001647 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001649 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001651 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001652 // Determine whether the type we're converting from is signed or
1653 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001654 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 // The types we'll try to promote to, in the appropriate
1658 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001659 QualType PromoteTypes[6] = {
1660 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001661 Context.LongTy, Context.UnsignedLongTy ,
1662 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001664 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1666 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001667 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1669 // We found the type that we can promote to. If this is the
1670 // type we wanted, we have a promotion. Otherwise, no
1671 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
1674 }
1675 }
1676
1677 // An rvalue for an integral bit-field (9.6) can be converted to an
1678 // rvalue of type int if int can represent all the values of the
1679 // bit-field; otherwise, it can be converted to unsigned int if
1680 // unsigned int can represent all the values of the bit-field. If
1681 // the bit-field is larger yet, no integral promotion applies to
1682 // it. If the bit-field has an enumerated type, it is treated as any
1683 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001684 // FIXME: We should delay checking of bit-fields until we actually perform the
1685 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001686 using llvm::APSInt;
1687 if (From)
1688 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001689 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001690 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001691 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1692 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1693 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001695 // Are we promoting to an int from a bitfield that fits in an int?
1696 if (BitWidth < ToSize ||
1697 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1698 return To->getKind() == BuiltinType::Int;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001701 // Are we promoting to an unsigned int from an unsigned bitfield
1702 // that fits into an unsigned int?
1703 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1704 return To->getKind() == BuiltinType::UInt;
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001707 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 // An rvalue of type bool can be converted to an rvalue of type int,
1712 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001713 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716
1717 return false;
1718}
1719
1720/// IsFloatingPointPromotion - Determines whether the conversion from
1721/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1722/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001723bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001724 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1725 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001726 /// An rvalue of type float can be converted to an rvalue of type
1727 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 if (FromBuiltin->getKind() == BuiltinType::Float &&
1729 ToBuiltin->getKind() == BuiltinType::Double)
1730 return true;
1731
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001732 // C99 6.3.1.5p1:
1733 // When a float is promoted to double or long double, or a
1734 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001735 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001736 (FromBuiltin->getKind() == BuiltinType::Float ||
1737 FromBuiltin->getKind() == BuiltinType::Double) &&
1738 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1739 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001740
1741 // Half can be promoted to float.
1742 if (FromBuiltin->getKind() == BuiltinType::Half &&
1743 ToBuiltin->getKind() == BuiltinType::Float)
1744 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001745 }
1746
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 return false;
1748}
1749
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750/// \brief Determine if a conversion is a complex promotion.
1751///
1752/// A complex promotion is defined as a complex -> complex conversion
1753/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001754/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001755bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001756 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001757 if (!FromComplex)
1758 return false;
1759
John McCall9dd450b2009-09-21 23:43:11 +00001760 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001761 if (!ToComplex)
1762 return false;
1763
1764 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001765 ToComplex->getElementType()) ||
1766 IsIntegralPromotion(0, FromComplex->getElementType(),
1767 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001768}
1769
Douglas Gregor237f96c2008-11-26 23:31:11 +00001770/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1771/// the pointer type FromPtr to a pointer to type ToPointee, with the
1772/// same type qualifiers as FromPtr has on its pointee type. ToType,
1773/// if non-empty, will be a pointer to ToType that may or may not have
1774/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001775///
Mike Stump11289f42009-09-09 15:08:12 +00001776static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001777BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001778 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001779 ASTContext &Context,
1780 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001781 assert((FromPtr->getTypeClass() == Type::Pointer ||
1782 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1783 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
John McCall31168b02011-06-15 23:02:42 +00001785 /// Conversions to 'id' subsume cv-qualifier conversions.
1786 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001787 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788
1789 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001790 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001791 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001792 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001793
John McCall31168b02011-06-15 23:02:42 +00001794 if (StripObjCLifetime)
1795 Quals.removeObjCLifetime();
1796
Mike Stump11289f42009-09-09 15:08:12 +00001797 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001798 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001799 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001800 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001801 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001802
1803 // Build a pointer to ToPointee. It has the right qualifiers
1804 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001805 if (isa<ObjCObjectPointerType>(ToType))
1806 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001807 return Context.getPointerType(ToPointee);
1808 }
1809
1810 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001811 QualType QualifiedCanonToPointee
1812 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001814 if (isa<ObjCObjectPointerType>(ToType))
1815 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1816 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001817}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Mike Stump11289f42009-09-09 15:08:12 +00001819static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001820 bool InOverloadResolution,
1821 ASTContext &Context) {
1822 // Handle value-dependent integral null pointer constants correctly.
1823 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1824 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001825 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001826 return !InOverloadResolution;
1827
Douglas Gregor56751b52009-09-25 04:25:58 +00001828 return Expr->isNullPointerConstant(Context,
1829 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1830 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001831}
Mike Stump11289f42009-09-09 15:08:12 +00001832
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833/// IsPointerConversion - Determines whether the conversion of the
1834/// expression From, which has the (possibly adjusted) type FromType,
1835/// can be converted to the type ToType via a pointer conversion (C++
1836/// 4.10). If so, returns true and places the converted type (that
1837/// might differ from ToType in its cv-qualifiers at some level) into
1838/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001839///
Douglas Gregora29dc052008-11-27 01:19:21 +00001840/// This routine also supports conversions to and from block pointers
1841/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1842/// pointers to interfaces. FIXME: Once we've determined the
1843/// appropriate overloading rules for Objective-C, we may want to
1844/// split the Objective-C checks into a different routine; however,
1845/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001846/// conversions, so for now they live here. IncompatibleObjC will be
1847/// set if the conversion is an allowed Objective-C conversion that
1848/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001850 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001851 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001852 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001853 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001854 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1855 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001856 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001857
Mike Stump11289f42009-09-09 15:08:12 +00001858 // Conversion from a null pointer constant to any Objective-C pointer type.
1859 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001860 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001861 ConvertedType = ToType;
1862 return true;
1863 }
1864
Douglas Gregor231d1c62008-11-27 00:15:41 +00001865 // Blocks: Block pointers can be converted to void*.
1866 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001868 ConvertedType = ToType;
1869 return true;
1870 }
1871 // Blocks: A null pointer constant can be converted to a block
1872 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001873 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001874 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001875 ConvertedType = ToType;
1876 return true;
1877 }
1878
Sebastian Redl576fd422009-05-10 18:38:11 +00001879 // If the left-hand-side is nullptr_t, the right side can be a null
1880 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001881 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001887 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 if (!ToTypePtr)
1889 return false;
1890
1891 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001892 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001893 ConvertedType = ToType;
1894 return true;
1895 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001898 // , including objective-c pointers.
1899 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001900 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001902 ConvertedType = BuildSimilarlyQualifiedPointerType(
1903 FromType->getAs<ObjCObjectPointerType>(),
1904 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001905 ToType, Context);
1906 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001907 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001908 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001909 if (!FromTypePtr)
1910 return false;
1911
1912 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001915 // pointer conversion, so don't do all of the work below.
1916 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1917 return false;
1918
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001919 // An rvalue of type "pointer to cv T," where T is an object type,
1920 // can be converted to an rvalue of type "pointer to cv void" (C++
1921 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001922 if (FromPointeeType->isIncompleteOrObjectType() &&
1923 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001924 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001925 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001926 ToType, Context,
1927 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928 return true;
1929 }
1930
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001931 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001932 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001933 ToPointeeType->isVoidType()) {
1934 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1935 ToPointeeType,
1936 ToType, Context);
1937 return true;
1938 }
1939
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001940 // When we're overloading in C, we allow a special kind of pointer
1941 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001942 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001943 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001944 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001945 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001946 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001947 return true;
1948 }
1949
Douglas Gregor5c407d92008-10-23 00:40:37 +00001950 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001951 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001952 // An rvalue of type "pointer to cv D," where D is a class type,
1953 // can be converted to an rvalue of type "pointer to cv B," where
1954 // B is a base class (clause 10) of D. If B is an inaccessible
1955 // (clause 11) or ambiguous (10.2) base class of D, a program that
1956 // necessitates this conversion is ill-formed. The result of the
1957 // conversion is a pointer to the base class sub-object of the
1958 // derived class object. The null pointer value is converted to
1959 // the null pointer value of the destination type.
1960 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001961 // Note that we do not check for ambiguity or inaccessibility
1962 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001963 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001964 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001965 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001966 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001969 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001970 ToType, Context);
1971 return true;
1972 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001973
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001974 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1975 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1977 ToPointeeType,
1978 ToType, Context);
1979 return true;
1980 }
1981
Douglas Gregora119f102008-12-19 19:13:09 +00001982 return false;
1983}
Douglas Gregoraec25842011-04-26 23:16:46 +00001984
1985/// \brief Adopt the given qualifiers for the given type.
1986static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1987 Qualifiers TQs = T.getQualifiers();
1988
1989 // Check whether qualifiers already match.
1990 if (TQs == Qs)
1991 return T;
1992
1993 if (Qs.compatiblyIncludes(TQs))
1994 return Context.getQualifiedType(T, Qs);
1995
1996 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1997}
Douglas Gregora119f102008-12-19 19:13:09 +00001998
1999/// isObjCPointerConversion - Determines whether this is an
2000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2001/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002003 QualType& ConvertedType,
2004 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002005 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002006 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Douglas Gregoraec25842011-04-26 23:16:46 +00002008 // The set of qualifiers on the type we're converting from.
2009 Qualifiers FromQualifiers = FromType.getQualifiers();
2010
Steve Naroff7cae42b2009-07-10 23:34:53 +00002011 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002012 const ObjCObjectPointerType* ToObjCPtr =
2013 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002014 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002015 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002016
Steve Naroff7cae42b2009-07-10 23:34:53 +00002017 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002018 // If the pointee types are the same (ignoring qualifications),
2019 // then this is not a pointer conversion.
2020 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2021 FromObjCPtr->getPointeeType()))
2022 return false;
2023
Douglas Gregoraec25842011-04-26 23:16:46 +00002024 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002025 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002026 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002027 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002028 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002029 return true;
2030 }
2031 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002032 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002033 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002034 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002035 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Objective C++: We're able to convert from a pointer to an
2040 // interface to a pointer to a different interface.
2041 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002042 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2043 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002044 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002045 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2046 FromObjCPtr->getPointeeType()))
2047 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002049 ToObjCPtr->getPointeeType(),
2050 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002051 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002052 return true;
2053 }
2054
2055 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2056 // Okay: this is some kind of implicit downcast of Objective-C
2057 // interfaces, which is permitted. However, we're going to
2058 // complain about it.
2059 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002061 ToObjCPtr->getPointeeType(),
2062 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002063 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002064 return true;
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002067 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002068 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002069 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002070 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002072 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002073 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002074 // to a block pointer type.
2075 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002076 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002077 return true;
2078 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002079 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002082 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002084 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002085 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002086 return true;
2087 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002088 else
Douglas Gregora119f102008-12-19 19:13:09 +00002089 return false;
2090
Douglas Gregor033f56d2008-12-23 00:53:59 +00002091 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002092 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002093 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002094 else if (const BlockPointerType *FromBlockPtr =
2095 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002096 FromPointeeType = FromBlockPtr->getPointeeType();
2097 else
Douglas Gregora119f102008-12-19 19:13:09 +00002098 return false;
2099
Douglas Gregora119f102008-12-19 19:13:09 +00002100 // If we have pointers to pointers, recursively check whether this
2101 // is an Objective-C conversion.
2102 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2103 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2104 IncompatibleObjC)) {
2105 // We always complain about this conversion.
2106 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002107 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002108 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002109 return true;
2110 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002111 // Allow conversion of pointee being objective-c pointer to another one;
2112 // as in I* to id.
2113 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2114 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2115 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2116 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002117
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002118 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002119 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002120 return true;
2121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
Douglas Gregor033f56d2008-12-23 00:53:59 +00002123 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002124 // differences in the argument and result types are in Objective-C
2125 // pointer conversions. If so, we permit the conversion (but
2126 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002127 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002128 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002129 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002130 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002131 if (FromFunctionType && ToFunctionType) {
2132 // If the function types are exactly the same, this isn't an
2133 // Objective-C pointer conversion.
2134 if (Context.getCanonicalType(FromPointeeType)
2135 == Context.getCanonicalType(ToPointeeType))
2136 return false;
2137
2138 // Perform the quick checks that will tell us whether these
2139 // function types are obviously different.
2140 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2141 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2142 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2143 return false;
2144
2145 bool HasObjCConversion = false;
2146 if (Context.getCanonicalType(FromFunctionType->getResultType())
2147 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2148 // Okay, the types match exactly. Nothing to do.
2149 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2150 ToFunctionType->getResultType(),
2151 ConvertedType, IncompatibleObjC)) {
2152 // Okay, we have an Objective-C pointer conversion.
2153 HasObjCConversion = true;
2154 } else {
2155 // Function types are too different. Abort.
2156 return false;
2157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregora119f102008-12-19 19:13:09 +00002159 // Check argument types.
2160 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2161 ArgIdx != NumArgs; ++ArgIdx) {
2162 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2163 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2164 if (Context.getCanonicalType(FromArgType)
2165 == Context.getCanonicalType(ToArgType)) {
2166 // Okay, the types match exactly. Nothing to do.
2167 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2168 ConvertedType, IncompatibleObjC)) {
2169 // Okay, we have an Objective-C pointer conversion.
2170 HasObjCConversion = true;
2171 } else {
2172 // Argument types are too different. Abort.
2173 return false;
2174 }
2175 }
2176
2177 if (HasObjCConversion) {
2178 // We had an Objective-C conversion. Allow this pointer
2179 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002181 IncompatibleObjC = true;
2182 return true;
2183 }
2184 }
2185
Sebastian Redl72b597d2009-01-25 19:43:20 +00002186 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
John McCall31168b02011-06-15 23:02:42 +00002189/// \brief Determine whether this is an Objective-C writeback conversion,
2190/// used for parameter passing when performing automatic reference counting.
2191///
2192/// \param FromType The type we're converting form.
2193///
2194/// \param ToType The type we're converting to.
2195///
2196/// \param ConvertedType The type that will be produced after applying
2197/// this conversion.
2198bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2199 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002200 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002201 Context.hasSameUnqualifiedType(FromType, ToType))
2202 return false;
2203
2204 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2205 QualType ToPointee;
2206 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2207 ToPointee = ToPointer->getPointeeType();
2208 else
2209 return false;
2210
2211 Qualifiers ToQuals = ToPointee.getQualifiers();
2212 if (!ToPointee->isObjCLifetimeType() ||
2213 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002214 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002215 return false;
2216
2217 // Argument must be a pointer to __strong to __weak.
2218 QualType FromPointee;
2219 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2220 FromPointee = FromPointer->getPointeeType();
2221 else
2222 return false;
2223
2224 Qualifiers FromQuals = FromPointee.getQualifiers();
2225 if (!FromPointee->isObjCLifetimeType() ||
2226 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2227 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2228 return false;
2229
2230 // Make sure that we have compatible qualifiers.
2231 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2232 if (!ToQuals.compatiblyIncludes(FromQuals))
2233 return false;
2234
2235 // Remove qualifiers from the pointee type we're converting from; they
2236 // aren't used in the compatibility check belong, and we'll be adding back
2237 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2238 FromPointee = FromPointee.getUnqualifiedType();
2239
2240 // The unqualified form of the pointee types must be compatible.
2241 ToPointee = ToPointee.getUnqualifiedType();
2242 bool IncompatibleObjC;
2243 if (Context.typesAreCompatible(FromPointee, ToPointee))
2244 FromPointee = ToPointee;
2245 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2246 IncompatibleObjC))
2247 return false;
2248
2249 /// \brief Construct the type we're converting to, which is a pointer to
2250 /// __autoreleasing pointee.
2251 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2252 ConvertedType = Context.getPointerType(FromPointee);
2253 return true;
2254}
2255
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002256bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2257 QualType& ConvertedType) {
2258 QualType ToPointeeType;
2259 if (const BlockPointerType *ToBlockPtr =
2260 ToType->getAs<BlockPointerType>())
2261 ToPointeeType = ToBlockPtr->getPointeeType();
2262 else
2263 return false;
2264
2265 QualType FromPointeeType;
2266 if (const BlockPointerType *FromBlockPtr =
2267 FromType->getAs<BlockPointerType>())
2268 FromPointeeType = FromBlockPtr->getPointeeType();
2269 else
2270 return false;
2271 // We have pointer to blocks, check whether the only
2272 // differences in the argument and result types are in Objective-C
2273 // pointer conversions. If so, we permit the conversion.
2274
2275 const FunctionProtoType *FromFunctionType
2276 = FromPointeeType->getAs<FunctionProtoType>();
2277 const FunctionProtoType *ToFunctionType
2278 = ToPointeeType->getAs<FunctionProtoType>();
2279
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002280 if (!FromFunctionType || !ToFunctionType)
2281 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002282
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002283 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002284 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002285
2286 // Perform the quick checks that will tell us whether these
2287 // function types are obviously different.
2288 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2289 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2290 return false;
2291
2292 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2293 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2294 if (FromEInfo != ToEInfo)
2295 return false;
2296
2297 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002298 if (Context.hasSameType(FromFunctionType->getResultType(),
2299 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002300 // Okay, the types match exactly. Nothing to do.
2301 } else {
2302 QualType RHS = FromFunctionType->getResultType();
2303 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002305 !RHS.hasQualifiers() && LHS.hasQualifiers())
2306 LHS = LHS.getUnqualifiedType();
2307
2308 if (Context.hasSameType(RHS,LHS)) {
2309 // OK exact match.
2310 } else if (isObjCPointerConversion(RHS, LHS,
2311 ConvertedType, IncompatibleObjC)) {
2312 if (IncompatibleObjC)
2313 return false;
2314 // Okay, we have an Objective-C pointer conversion.
2315 }
2316 else
2317 return false;
2318 }
2319
2320 // Check argument types.
2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322 ArgIdx != NumArgs; ++ArgIdx) {
2323 IncompatibleObjC = false;
2324 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2325 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2326 if (Context.hasSameType(FromArgType, ToArgType)) {
2327 // Okay, the types match exactly. Nothing to do.
2328 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2329 ConvertedType, IncompatibleObjC)) {
2330 if (IncompatibleObjC)
2331 return false;
2332 // Okay, we have an Objective-C pointer conversion.
2333 } else
2334 // Argument types are too different. Abort.
2335 return false;
2336 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002337 if (LangOpts.ObjCAutoRefCount &&
2338 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2339 ToFunctionType))
2340 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002341
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002342 ConvertedType = ToType;
2343 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002344}
2345
Richard Trieucaff2472011-11-23 22:32:32 +00002346enum {
2347 ft_default,
2348 ft_different_class,
2349 ft_parameter_arity,
2350 ft_parameter_mismatch,
2351 ft_return_type,
2352 ft_qualifer_mismatch
2353};
2354
2355/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2356/// function types. Catches different number of parameter, mismatch in
2357/// parameter types, and different return types.
2358void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2359 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002360 // If either type is not valid, include no extra info.
2361 if (FromType.isNull() || ToType.isNull()) {
2362 PDiag << ft_default;
2363 return;
2364 }
2365
Richard Trieucaff2472011-11-23 22:32:32 +00002366 // Get the function type from the pointers.
2367 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2368 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2369 *ToMember = ToType->getAs<MemberPointerType>();
2370 if (FromMember->getClass() != ToMember->getClass()) {
2371 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2372 << QualType(FromMember->getClass(), 0);
2373 return;
2374 }
2375 FromType = FromMember->getPointeeType();
2376 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002377 }
2378
Richard Trieu96ed5b62011-12-13 23:19:45 +00002379 if (FromType->isPointerType())
2380 FromType = FromType->getPointeeType();
2381 if (ToType->isPointerType())
2382 ToType = ToType->getPointeeType();
2383
2384 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002385 FromType = FromType.getNonReferenceType();
2386 ToType = ToType.getNonReferenceType();
2387
Richard Trieucaff2472011-11-23 22:32:32 +00002388 // Don't print extra info for non-specialized template functions.
2389 if (FromType->isInstantiationDependentType() &&
2390 !FromType->getAs<TemplateSpecializationType>()) {
2391 PDiag << ft_default;
2392 return;
2393 }
2394
Richard Trieu96ed5b62011-12-13 23:19:45 +00002395 // No extra info for same types.
2396 if (Context.hasSameType(FromType, ToType)) {
2397 PDiag << ft_default;
2398 return;
2399 }
2400
Richard Trieucaff2472011-11-23 22:32:32 +00002401 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2402 *ToFunction = ToType->getAs<FunctionProtoType>();
2403
2404 // Both types need to be function types.
2405 if (!FromFunction || !ToFunction) {
2406 PDiag << ft_default;
2407 return;
2408 }
2409
2410 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2411 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2412 << FromFunction->getNumArgs();
2413 return;
2414 }
2415
2416 // Handle different parameter types.
2417 unsigned ArgPos;
2418 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2419 PDiag << ft_parameter_mismatch << ArgPos + 1
2420 << ToFunction->getArgType(ArgPos)
2421 << FromFunction->getArgType(ArgPos);
2422 return;
2423 }
2424
2425 // Handle different return type.
2426 if (!Context.hasSameType(FromFunction->getResultType(),
2427 ToFunction->getResultType())) {
2428 PDiag << ft_return_type << ToFunction->getResultType()
2429 << FromFunction->getResultType();
2430 return;
2431 }
2432
2433 unsigned FromQuals = FromFunction->getTypeQuals(),
2434 ToQuals = ToFunction->getTypeQuals();
2435 if (FromQuals != ToQuals) {
2436 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2437 return;
2438 }
2439
2440 // Unable to find a difference, so add no extra info.
2441 PDiag << ft_default;
2442}
2443
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002444/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002445/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002446/// they have same number of arguments. This routine assumes that Objective-C
2447/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002448/// If the parameters are different, ArgPos will have the the parameter index
2449/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002451 const FunctionProtoType *NewType,
2452 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002453 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002454 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2455 N = NewType->arg_type_begin(),
2456 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2457 if (!Context.hasSameType(*O, *N)) {
2458 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2459 return false;
2460 }
2461 }
2462 return true;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002465 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2466 N = NewType->arg_type_begin(),
2467 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2468 QualType ToType = (*O);
2469 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002470 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002471 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2472 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002473 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2474 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2475 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002477 continue;
2478 }
John McCall8b07ec22010-05-15 11:32:37 +00002479 else if (const ObjCObjectPointerType *PTTo =
2480 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002481 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002482 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002483 if (Context.hasSameUnqualifiedType(
2484 PTTo->getObjectType()->getBaseType(),
2485 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002486 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002487 }
Richard Trieucaff2472011-11-23 22:32:32 +00002488 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002490 }
2491 }
2492 return true;
2493}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002494
Douglas Gregor39c16d42008-10-24 04:54:22 +00002495/// CheckPointerConversion - Check the pointer conversion from the
2496/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002497/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002498/// conversions for which IsPointerConversion has already returned
2499/// true. It returns true and produces a diagnostic if there was an
2500/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002501bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002502 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002503 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002504 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002505 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002506 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002507
John McCall8cb679e2010-11-15 09:13:47 +00002508 Kind = CK_BitCast;
2509
Chandler Carruthffab8732011-04-09 07:32:05 +00002510 if (!IsCStyleOrFunctionalCast &&
2511 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2512 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2513 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002514 PDiag(diag::warn_impcast_bool_to_null_pointer)
2515 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002516
John McCall9320b872011-09-09 05:25:32 +00002517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2518 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002519 QualType FromPointeeType = FromPtrType->getPointeeType(),
2520 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002521
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002522 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2523 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002524 // We must have a derived-to-base conversion. Check an
2525 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002526 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2527 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002528 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002529 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002530 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002532 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002533 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002534 }
2535 }
John McCall9320b872011-09-09 05:25:32 +00002536 } else if (const ObjCObjectPointerType *ToPtrType =
2537 ToType->getAs<ObjCObjectPointerType>()) {
2538 if (const ObjCObjectPointerType *FromPtrType =
2539 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002540 // Objective-C++ conversions are always okay.
2541 // FIXME: We should have a different class of conversions for the
2542 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002543 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002544 return false;
John McCall9320b872011-09-09 05:25:32 +00002545 } else if (FromType->isBlockPointerType()) {
2546 Kind = CK_BlockPointerToObjCPointerCast;
2547 } else {
2548 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002549 }
John McCall9320b872011-09-09 05:25:32 +00002550 } else if (ToType->isBlockPointerType()) {
2551 if (!FromType->isBlockPointerType())
2552 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002553 }
John McCall8cb679e2010-11-15 09:13:47 +00002554
2555 // We shouldn't fall into this case unless it's valid for other
2556 // reasons.
2557 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2558 Kind = CK_NullToPointer;
2559
Douglas Gregor39c16d42008-10-24 04:54:22 +00002560 return false;
2561}
2562
Sebastian Redl72b597d2009-01-25 19:43:20 +00002563/// IsMemberPointerConversion - Determines whether the conversion of the
2564/// expression From, which has the (possibly adjusted) type FromType, can be
2565/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2566/// If so, returns true and places the converted type (that might differ from
2567/// ToType in its cv-qualifiers at some level) into ConvertedType.
2568bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002570 bool InOverloadResolution,
2571 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002572 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002573 if (!ToTypePtr)
2574 return false;
2575
2576 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002577 if (From->isNullPointerConstant(Context,
2578 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2579 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002580 ConvertedType = ToType;
2581 return true;
2582 }
2583
2584 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002585 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002586 if (!FromTypePtr)
2587 return false;
2588
2589 // A pointer to member of B can be converted to a pointer to member of D,
2590 // where D is derived from B (C++ 4.11p2).
2591 QualType FromClass(FromTypePtr->getClass(), 0);
2592 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002593
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002594 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2595 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2596 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002597 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2598 ToClass.getTypePtr());
2599 return true;
2600 }
2601
2602 return false;
2603}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604
Sebastian Redl72b597d2009-01-25 19:43:20 +00002605/// CheckMemberPointerConversion - Check the member pointer conversion from the
2606/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002607/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002608/// for which IsMemberPointerConversion has already returned true. It returns
2609/// true and produces a diagnostic if there was an error, or returns false
2610/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002611bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002612 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002613 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002614 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002615 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002616 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002617 if (!FromPtrType) {
2618 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002620 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002621 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002622 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002623 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002624 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002625
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002626 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002627 assert(ToPtrType && "No member pointer cast has a target type "
2628 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002629
Sebastian Redled8f2002009-01-28 18:33:18 +00002630 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2631 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002632
Sebastian Redled8f2002009-01-28 18:33:18 +00002633 // FIXME: What about dependent types?
2634 assert(FromClass->isRecordType() && "Pointer into non-class.");
2635 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002636
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002637 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002638 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002639 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2640 assert(DerivationOkay &&
2641 "Should not have been called if derivation isn't OK.");
2642 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002643
Sebastian Redled8f2002009-01-28 18:33:18 +00002644 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2645 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002646 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2648 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2649 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002650 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002651
Douglas Gregor89ee6822009-02-28 01:32:25 +00002652 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002653 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2654 << FromClass << ToClass << QualType(VBase, 0)
2655 << From->getSourceRange();
2656 return true;
2657 }
2658
John McCall5b0829a2010-02-10 09:31:12 +00002659 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002660 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2661 Paths.front(),
2662 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002663
Anders Carlssond7923c62009-08-22 23:33:40 +00002664 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002665 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002666 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002667 return false;
2668}
2669
Douglas Gregor9a657932008-10-21 23:43:52 +00002670/// IsQualificationConversion - Determines whether the conversion from
2671/// an rvalue of type FromType to ToType is a qualification conversion
2672/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002673///
2674/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2675/// when the qualification conversion involves a change in the Objective-C
2676/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002677bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002679 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002680 FromType = Context.getCanonicalType(FromType);
2681 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002682 ObjCLifetimeConversion = false;
2683
Douglas Gregor9a657932008-10-21 23:43:52 +00002684 // If FromType and ToType are the same type, this is not a
2685 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002686 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002687 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002688
Douglas Gregor9a657932008-10-21 23:43:52 +00002689 // (C++ 4.4p4):
2690 // A conversion can add cv-qualifiers at levels other than the first
2691 // in multi-level pointers, subject to the following rules: [...]
2692 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002693 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002694 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002695 // Within each iteration of the loop, we check the qualifiers to
2696 // determine if this still looks like a qualification
2697 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002698 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002699 // until there are no more pointers or pointers-to-members left to
2700 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002701 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002702
Douglas Gregor90609aa2011-04-25 18:40:17 +00002703 Qualifiers FromQuals = FromType.getQualifiers();
2704 Qualifiers ToQuals = ToType.getQualifiers();
2705
John McCall31168b02011-06-15 23:02:42 +00002706 // Objective-C ARC:
2707 // Check Objective-C lifetime conversions.
2708 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2709 UnwrappedAnyPointer) {
2710 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2711 ObjCLifetimeConversion = true;
2712 FromQuals.removeObjCLifetime();
2713 ToQuals.removeObjCLifetime();
2714 } else {
2715 // Qualification conversions cannot cast between different
2716 // Objective-C lifetime qualifiers.
2717 return false;
2718 }
2719 }
2720
Douglas Gregorf30053d2011-05-08 06:09:53 +00002721 // Allow addition/removal of GC attributes but not changing GC attributes.
2722 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2723 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2724 FromQuals.removeObjCGCAttr();
2725 ToQuals.removeObjCGCAttr();
2726 }
2727
Douglas Gregor9a657932008-10-21 23:43:52 +00002728 // -- for every j > 0, if const is in cv 1,j then const is in cv
2729 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002730 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002731 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Douglas Gregor9a657932008-10-21 23:43:52 +00002733 // -- if the cv 1,j and cv 2,j are different, then const is in
2734 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002735 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002736 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002737 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002738
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 // Keep track of whether all prior cv-qualifiers in the "to" type
2740 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002741 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002742 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002743 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002744
2745 // We are left with FromType and ToType being the pointee types
2746 // after unwrapping the original FromType and ToType the same number
2747 // of types. If we unwrapped any pointers, and if FromType and
2748 // ToType have the same unqualified type (since we checked
2749 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002750 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002751}
2752
Sebastian Redl82ace982012-02-11 23:51:08 +00002753static OverloadingResult
2754IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2755 CXXRecordDecl *To,
2756 UserDefinedConversionSequence &User,
2757 OverloadCandidateSet &CandidateSet,
2758 bool AllowExplicit) {
2759 DeclContext::lookup_iterator Con, ConEnd;
2760 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2761 Con != ConEnd; ++Con) {
2762 NamedDecl *D = *Con;
2763 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2764
2765 // Find the constructor (which may be a template).
2766 CXXConstructorDecl *Constructor = 0;
2767 FunctionTemplateDecl *ConstructorTmpl
2768 = dyn_cast<FunctionTemplateDecl>(D);
2769 if (ConstructorTmpl)
2770 Constructor
2771 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2772 else
2773 Constructor = cast<CXXConstructorDecl>(D);
2774
2775 bool Usable = !Constructor->isInvalidDecl() &&
2776 S.isInitListConstructor(Constructor) &&
2777 (AllowExplicit || !Constructor->isExplicit());
2778 if (Usable) {
2779 if (ConstructorTmpl)
2780 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2781 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002782 From, CandidateSet,
Sebastian Redl82ace982012-02-11 23:51:08 +00002783 /*SuppressUserConversions=*/true);
2784 else
2785 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002786 From, CandidateSet,
Sebastian Redl82ace982012-02-11 23:51:08 +00002787 /*SuppressUserConversions=*/true);
2788 }
2789 }
2790
2791 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2792
2793 OverloadCandidateSet::iterator Best;
2794 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2795 case OR_Success: {
2796 // Record the standard conversion we used and the conversion function.
2797 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2798 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2799
2800 QualType ThisType = Constructor->getThisType(S.Context);
2801 // Initializer lists don't have conversions as such.
2802 User.Before.setAsIdentityConversion();
2803 User.HadMultipleCandidates = HadMultipleCandidates;
2804 User.ConversionFunction = Constructor;
2805 User.FoundConversionFunction = Best->FoundDecl;
2806 User.After.setAsIdentityConversion();
2807 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2808 User.After.setAllToTypes(ToType);
2809 return OR_Success;
2810 }
2811
2812 case OR_No_Viable_Function:
2813 return OR_No_Viable_Function;
2814 case OR_Deleted:
2815 return OR_Deleted;
2816 case OR_Ambiguous:
2817 return OR_Ambiguous;
2818 }
2819
2820 llvm_unreachable("Invalid OverloadResult!");
2821}
2822
Douglas Gregor576e98c2009-01-30 23:27:23 +00002823/// Determines whether there is a user-defined conversion sequence
2824/// (C++ [over.ics.user]) that converts expression From to the type
2825/// ToType. If such a conversion exists, User will contain the
2826/// user-defined conversion sequence that performs such a conversion
2827/// and this routine will return true. Otherwise, this routine returns
2828/// false and User is unspecified.
2829///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002830/// \param AllowExplicit true if the conversion should consider C++0x
2831/// "explicit" conversion functions as well as non-explicit conversion
2832/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002833static OverloadingResult
2834IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002835 UserDefinedConversionSequence &User,
2836 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002837 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002838 // Whether we will only visit constructors.
2839 bool ConstructorsOnly = false;
2840
2841 // If the type we are conversion to is a class type, enumerate its
2842 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002843 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002844 // C++ [over.match.ctor]p1:
2845 // When objects of class type are direct-initialized (8.5), or
2846 // copy-initialized from an expression of the same or a
2847 // derived class type (8.5), overload resolution selects the
2848 // constructor. [...] For copy-initialization, the candidate
2849 // functions are all the converting constructors (12.3.1) of
2850 // that class. The argument list is the expression-list within
2851 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002852 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002853 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002854 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002855 ConstructorsOnly = true;
2856
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002857 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2858 // RequireCompleteType may have returned true due to some invalid decl
2859 // during template instantiation, but ToType may be complete enough now
2860 // to try to recover.
2861 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002862 // We're not going to find any constructors.
2863 } else if (CXXRecordDecl *ToRecordDecl
2864 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002865
2866 Expr **Args = &From;
2867 unsigned NumArgs = 1;
2868 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002869 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002870 // But first, see if there is an init-list-contructor that will work.
2871 OverloadingResult Result = IsInitializerListConstructorConversion(
2872 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2873 if (Result != OR_No_Viable_Function)
2874 return Result;
2875 // Never mind.
2876 CandidateSet.clear();
2877
2878 // If we're list-initializing, we pass the individual elements as
2879 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002880 Args = InitList->getInits();
2881 NumArgs = InitList->getNumInits();
2882 ListInitializing = true;
2883 }
2884
Douglas Gregor89ee6822009-02-28 01:32:25 +00002885 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002886 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002887 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002888 NamedDecl *D = *Con;
2889 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2890
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002891 // Find the constructor (which may be a template).
2892 CXXConstructorDecl *Constructor = 0;
2893 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002894 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002895 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002896 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002897 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2898 else
John McCalla0296f72010-03-19 07:35:19 +00002899 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002901 bool Usable = !Constructor->isInvalidDecl();
2902 if (ListInitializing)
2903 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2904 else
2905 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2906 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00002907 bool SuppressUserConversions = !ConstructorsOnly;
2908 if (SuppressUserConversions && ListInitializing) {
2909 SuppressUserConversions = false;
2910 if (NumArgs == 1) {
2911 // If the first argument is (a reference to) the target type,
2912 // suppress conversions.
2913 const FunctionProtoType *CtorType =
2914 Constructor->getType()->getAs<FunctionProtoType>();
2915 if (CtorType->getNumArgs() > 0) {
2916 QualType FirstArg = CtorType->getArgType(0);
2917 if (S.Context.hasSameUnqualifiedType(ToType,
2918 FirstArg.getNonReferenceType())) {
2919 SuppressUserConversions = true;
2920 }
2921 }
2922 }
2923 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002924 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002925 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2926 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002927 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002928 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002929 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002930 // Allow one user-defined conversion when user specifies a
2931 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002932 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002933 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00002934 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002935 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002936 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002937 }
2938 }
2939
Douglas Gregor5ab11652010-04-17 22:01:05 +00002940 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002941 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002942 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2943 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002944 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002945 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002946 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002947 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002948 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2949 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002950 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002951 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002952 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002953 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002954 DeclAccessPair FoundDecl = I.getPair();
2955 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002956 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2957 if (isa<UsingShadowDecl>(D))
2958 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2959
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002960 CXXConversionDecl *Conv;
2961 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002962 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2963 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002964 else
John McCallda4458e2010-03-31 01:36:47 +00002965 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002966
2967 if (AllowExplicit || !Conv->isExplicit()) {
2968 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002969 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2970 ActingContext, From, ToType,
2971 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002972 else
John McCall5c32be02010-08-24 20:38:10 +00002973 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2974 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002975 }
2976 }
2977 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002978 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002979
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002980 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2981
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002982 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002983 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002984 case OR_Success:
2985 // Record the standard conversion we used and the conversion function.
2986 if (CXXConstructorDecl *Constructor
2987 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002988 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00002989
John McCall5c32be02010-08-24 20:38:10 +00002990 // C++ [over.ics.user]p1:
2991 // If the user-defined conversion is specified by a
2992 // constructor (12.3.1), the initial standard conversion
2993 // sequence converts the source type to the type required by
2994 // the argument of the constructor.
2995 //
2996 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002997 if (isa<InitListExpr>(From)) {
2998 // Initializer lists don't have conversions as such.
2999 User.Before.setAsIdentityConversion();
3000 } else {
3001 if (Best->Conversions[0].isEllipsis())
3002 User.EllipsisConversion = true;
3003 else {
3004 User.Before = Best->Conversions[0].Standard;
3005 User.EllipsisConversion = false;
3006 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003007 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003008 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003009 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003010 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003011 User.After.setAsIdentityConversion();
3012 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3013 User.After.setAllToTypes(ToType);
3014 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003015 }
3016 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003017 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003018 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003019
John McCall5c32be02010-08-24 20:38:10 +00003020 // C++ [over.ics.user]p1:
3021 //
3022 // [...] If the user-defined conversion is specified by a
3023 // conversion function (12.3.2), the initial standard
3024 // conversion sequence converts the source type to the
3025 // implicit object parameter of the conversion function.
3026 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003027 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003028 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003029 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003030 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003031
John McCall5c32be02010-08-24 20:38:10 +00003032 // C++ [over.ics.user]p2:
3033 // The second standard conversion sequence converts the
3034 // result of the user-defined conversion to the target type
3035 // for the sequence. Since an implicit conversion sequence
3036 // is an initialization, the special rules for
3037 // initialization by user-defined conversion apply when
3038 // selecting the best user-defined conversion for a
3039 // user-defined conversion sequence (see 13.3.3 and
3040 // 13.3.3.1).
3041 User.After = Best->FinalConversion;
3042 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003043 }
David Blaikie8a40f702012-01-17 06:56:22 +00003044 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003045
John McCall5c32be02010-08-24 20:38:10 +00003046 case OR_No_Viable_Function:
3047 return OR_No_Viable_Function;
3048 case OR_Deleted:
3049 // No conversion here! We're done.
3050 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051
John McCall5c32be02010-08-24 20:38:10 +00003052 case OR_Ambiguous:
3053 return OR_Ambiguous;
3054 }
3055
David Blaikie8a40f702012-01-17 06:56:22 +00003056 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003057}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003059bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003060Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003061 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003062 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003064 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003065 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003066 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003067 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003068 diag::err_typecheck_ambiguous_condition)
3069 << From->getType() << ToType << From->getSourceRange();
3070 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003071 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003072 diag::err_typecheck_nonviable_condition)
3073 << From->getType() << ToType << From->getSourceRange();
3074 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003075 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003076 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003078}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003079
Douglas Gregor2837aa22012-02-22 17:32:19 +00003080/// \brief Compare the user-defined conversion functions or constructors
3081/// of two user-defined conversion sequences to determine whether any ordering
3082/// is possible.
3083static ImplicitConversionSequence::CompareKind
3084compareConversionFunctions(Sema &S,
3085 FunctionDecl *Function1,
3086 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003087 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003088 return ImplicitConversionSequence::Indistinguishable;
3089
3090 // Objective-C++:
3091 // If both conversion functions are implicitly-declared conversions from
3092 // a lambda closure type to a function pointer and a block pointer,
3093 // respectively, always prefer the conversion to a function pointer,
3094 // because the function pointer is more lightweight and is more likely
3095 // to keep code working.
3096 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3097 if (!Conv1)
3098 return ImplicitConversionSequence::Indistinguishable;
3099
3100 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3101 if (!Conv2)
3102 return ImplicitConversionSequence::Indistinguishable;
3103
3104 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3105 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3106 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3107 if (Block1 != Block2)
3108 return Block1? ImplicitConversionSequence::Worse
3109 : ImplicitConversionSequence::Better;
3110 }
3111
3112 return ImplicitConversionSequence::Indistinguishable;
3113}
3114
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003115/// CompareImplicitConversionSequences - Compare two implicit
3116/// conversion sequences to determine whether one is better than the
3117/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003118static ImplicitConversionSequence::CompareKind
3119CompareImplicitConversionSequences(Sema &S,
3120 const ImplicitConversionSequence& ICS1,
3121 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003122{
3123 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3124 // conversion sequences (as defined in 13.3.3.1)
3125 // -- a standard conversion sequence (13.3.3.1.1) is a better
3126 // conversion sequence than a user-defined conversion sequence or
3127 // an ellipsis conversion sequence, and
3128 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3129 // conversion sequence than an ellipsis conversion sequence
3130 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003131 //
John McCall0d1da222010-01-12 00:44:57 +00003132 // C++0x [over.best.ics]p10:
3133 // For the purpose of ranking implicit conversion sequences as
3134 // described in 13.3.3.2, the ambiguous conversion sequence is
3135 // treated as a user-defined sequence that is indistinguishable
3136 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003137 if (ICS1.getKindRank() < ICS2.getKindRank())
3138 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003139 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003140 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003141
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003142 // The following checks require both conversion sequences to be of
3143 // the same kind.
3144 if (ICS1.getKind() != ICS2.getKind())
3145 return ImplicitConversionSequence::Indistinguishable;
3146
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003147 ImplicitConversionSequence::CompareKind Result =
3148 ImplicitConversionSequence::Indistinguishable;
3149
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003150 // Two implicit conversion sequences of the same form are
3151 // indistinguishable conversion sequences unless one of the
3152 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003153 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003154 Result = CompareStandardConversionSequences(S,
3155 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003156 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003157 // User-defined conversion sequence U1 is a better conversion
3158 // sequence than another user-defined conversion sequence U2 if
3159 // they contain the same user-defined conversion function or
3160 // constructor and if the second standard conversion sequence of
3161 // U1 is better than the second standard conversion sequence of
3162 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003163 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003164 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003165 Result = CompareStandardConversionSequences(S,
3166 ICS1.UserDefined.After,
3167 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003168 else
3169 Result = compareConversionFunctions(S,
3170 ICS1.UserDefined.ConversionFunction,
3171 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003172 }
3173
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003174 // List-initialization sequence L1 is a better conversion sequence than
3175 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3176 // for some X and L2 does not.
3177 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003178 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003179 ICS1.isListInitializationSequence() &&
3180 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003181 if (ICS1.isStdInitializerListElement() &&
3182 !ICS2.isStdInitializerListElement())
3183 return ImplicitConversionSequence::Better;
3184 if (!ICS1.isStdInitializerListElement() &&
3185 ICS2.isStdInitializerListElement())
3186 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003187 }
3188
3189 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003190}
3191
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003192static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3193 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3194 Qualifiers Quals;
3195 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003199 return Context.hasSameUnqualifiedType(T1, T2);
3200}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003202// Per 13.3.3.2p3, compare the given standard conversion sequences to
3203// determine if one is a proper subset of the other.
3204static ImplicitConversionSequence::CompareKind
3205compareStandardConversionSubsets(ASTContext &Context,
3206 const StandardConversionSequence& SCS1,
3207 const StandardConversionSequence& SCS2) {
3208 ImplicitConversionSequence::CompareKind Result
3209 = ImplicitConversionSequence::Indistinguishable;
3210
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003211 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003212 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003213 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3214 return ImplicitConversionSequence::Better;
3215 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3216 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003217
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003218 if (SCS1.Second != SCS2.Second) {
3219 if (SCS1.Second == ICK_Identity)
3220 Result = ImplicitConversionSequence::Better;
3221 else if (SCS2.Second == ICK_Identity)
3222 Result = ImplicitConversionSequence::Worse;
3223 else
3224 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003225 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003226 return ImplicitConversionSequence::Indistinguishable;
3227
3228 if (SCS1.Third == SCS2.Third) {
3229 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3230 : ImplicitConversionSequence::Indistinguishable;
3231 }
3232
3233 if (SCS1.Third == ICK_Identity)
3234 return Result == ImplicitConversionSequence::Worse
3235 ? ImplicitConversionSequence::Indistinguishable
3236 : ImplicitConversionSequence::Better;
3237
3238 if (SCS2.Third == ICK_Identity)
3239 return Result == ImplicitConversionSequence::Better
3240 ? ImplicitConversionSequence::Indistinguishable
3241 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003243 return ImplicitConversionSequence::Indistinguishable;
3244}
3245
Douglas Gregore696ebb2011-01-26 14:52:12 +00003246/// \brief Determine whether one of the given reference bindings is better
3247/// than the other based on what kind of bindings they are.
3248static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3249 const StandardConversionSequence &SCS2) {
3250 // C++0x [over.ics.rank]p3b4:
3251 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3252 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003254 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003256 // reference*.
3257 //
3258 // FIXME: Rvalue references. We're going rogue with the above edits,
3259 // because the semantics in the current C++0x working paper (N3225 at the
3260 // time of this writing) break the standard definition of std::forward
3261 // and std::reference_wrapper when dealing with references to functions.
3262 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003263 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3264 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3265 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266
Douglas Gregore696ebb2011-01-26 14:52:12 +00003267 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3268 SCS2.IsLvalueReference) ||
3269 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3270 !SCS2.IsLvalueReference);
3271}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003273/// CompareStandardConversionSequences - Compare two standard
3274/// conversion sequences to determine whether one is better than the
3275/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003276static ImplicitConversionSequence::CompareKind
3277CompareStandardConversionSequences(Sema &S,
3278 const StandardConversionSequence& SCS1,
3279 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003280{
3281 // Standard conversion sequence S1 is a better conversion sequence
3282 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3283
3284 // -- S1 is a proper subsequence of S2 (comparing the conversion
3285 // sequences in the canonical form defined by 13.3.3.1.1,
3286 // excluding any Lvalue Transformation; the identity conversion
3287 // sequence is considered to be a subsequence of any
3288 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003289 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003290 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003291 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003292
3293 // -- the rank of S1 is better than the rank of S2 (by the rules
3294 // defined below), or, if not that,
3295 ImplicitConversionRank Rank1 = SCS1.getRank();
3296 ImplicitConversionRank Rank2 = SCS2.getRank();
3297 if (Rank1 < Rank2)
3298 return ImplicitConversionSequence::Better;
3299 else if (Rank2 < Rank1)
3300 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003301
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003302 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3303 // are indistinguishable unless one of the following rules
3304 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003305
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003306 // A conversion that is not a conversion of a pointer, or
3307 // pointer to member, to bool is better than another conversion
3308 // that is such a conversion.
3309 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3310 return SCS2.isPointerConversionToBool()
3311 ? ImplicitConversionSequence::Better
3312 : ImplicitConversionSequence::Worse;
3313
Douglas Gregor5c407d92008-10-23 00:40:37 +00003314 // C++ [over.ics.rank]p4b2:
3315 //
3316 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003317 // conversion of B* to A* is better than conversion of B* to
3318 // void*, and conversion of A* to void* is better than conversion
3319 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003320 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003321 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003322 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003323 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003324 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3325 // Exactly one of the conversion sequences is a conversion to
3326 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003327 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3328 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003329 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3330 // Neither conversion sequence converts to a void pointer; compare
3331 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003332 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003333 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003334 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003335 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3336 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003337 // Both conversion sequences are conversions to void
3338 // pointers. Compare the source types to determine if there's an
3339 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003340 QualType FromType1 = SCS1.getFromType();
3341 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003342
3343 // Adjust the types we're converting from via the array-to-pointer
3344 // conversion, if we need to.
3345 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003346 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003347 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003348 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003349
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003350 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3351 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003352
John McCall5c32be02010-08-24 20:38:10 +00003353 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003354 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003355 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003356 return ImplicitConversionSequence::Worse;
3357
3358 // Objective-C++: If one interface is more specific than the
3359 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003360 const ObjCObjectPointerType* FromObjCPtr1
3361 = FromType1->getAs<ObjCObjectPointerType>();
3362 const ObjCObjectPointerType* FromObjCPtr2
3363 = FromType2->getAs<ObjCObjectPointerType>();
3364 if (FromObjCPtr1 && FromObjCPtr2) {
3365 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3366 FromObjCPtr2);
3367 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3368 FromObjCPtr1);
3369 if (AssignLeft != AssignRight) {
3370 return AssignLeft? ImplicitConversionSequence::Better
3371 : ImplicitConversionSequence::Worse;
3372 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003373 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003374 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003375
3376 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3377 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003378 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003379 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003380 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003381
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003382 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003383 // Check for a better reference binding based on the kind of bindings.
3384 if (isBetterReferenceBindingKind(SCS1, SCS2))
3385 return ImplicitConversionSequence::Better;
3386 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3387 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388
Sebastian Redlb28b4072009-03-22 23:49:27 +00003389 // C++ [over.ics.rank]p3b4:
3390 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3391 // which the references refer are the same type except for
3392 // top-level cv-qualifiers, and the type to which the reference
3393 // initialized by S2 refers is more cv-qualified than the type
3394 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003395 QualType T1 = SCS1.getToType(2);
3396 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003397 T1 = S.Context.getCanonicalType(T1);
3398 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003399 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003400 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3401 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003402 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003403 // Objective-C++ ARC: If the references refer to objects with different
3404 // lifetimes, prefer bindings that don't change lifetime.
3405 if (SCS1.ObjCLifetimeConversionBinding !=
3406 SCS2.ObjCLifetimeConversionBinding) {
3407 return SCS1.ObjCLifetimeConversionBinding
3408 ? ImplicitConversionSequence::Worse
3409 : ImplicitConversionSequence::Better;
3410 }
3411
Chandler Carruth8e543b32010-12-12 08:17:55 +00003412 // If the type is an array type, promote the element qualifiers to the
3413 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003414 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003415 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003416 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003417 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003418 if (T2.isMoreQualifiedThan(T1))
3419 return ImplicitConversionSequence::Better;
3420 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003421 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003422 }
3423 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003424
Francois Pichet08d2fa02011-09-18 21:37:37 +00003425 // In Microsoft mode, prefer an integral conversion to a
3426 // floating-to-integral conversion if the integral conversion
3427 // is between types of the same size.
3428 // For example:
3429 // void f(float);
3430 // void f(int);
3431 // int main {
3432 // long a;
3433 // f(a);
3434 // }
3435 // Here, MSVC will call f(int) instead of generating a compile error
3436 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003437 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003438 SCS1.Second == ICK_Integral_Conversion &&
3439 SCS2.Second == ICK_Floating_Integral &&
3440 S.Context.getTypeSize(SCS1.getFromType()) ==
3441 S.Context.getTypeSize(SCS1.getToType(2)))
3442 return ImplicitConversionSequence::Better;
3443
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003444 return ImplicitConversionSequence::Indistinguishable;
3445}
3446
3447/// CompareQualificationConversions - Compares two standard conversion
3448/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003449/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3450ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003451CompareQualificationConversions(Sema &S,
3452 const StandardConversionSequence& SCS1,
3453 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003454 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003455 // -- S1 and S2 differ only in their qualification conversion and
3456 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3457 // cv-qualification signature of type T1 is a proper subset of
3458 // the cv-qualification signature of type T2, and S1 is not the
3459 // deprecated string literal array-to-pointer conversion (4.2).
3460 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3461 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3462 return ImplicitConversionSequence::Indistinguishable;
3463
3464 // FIXME: the example in the standard doesn't use a qualification
3465 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003466 QualType T1 = SCS1.getToType(2);
3467 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003468 T1 = S.Context.getCanonicalType(T1);
3469 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003470 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003471 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3472 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003473
3474 // If the types are the same, we won't learn anything by unwrapped
3475 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003476 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003477 return ImplicitConversionSequence::Indistinguishable;
3478
Chandler Carruth607f38e2009-12-29 07:16:59 +00003479 // If the type is an array type, promote the element qualifiers to the type
3480 // for comparison.
3481 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003482 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003483 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003484 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003485
Mike Stump11289f42009-09-09 15:08:12 +00003486 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003487 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003488
3489 // Objective-C++ ARC:
3490 // Prefer qualification conversions not involving a change in lifetime
3491 // to qualification conversions that do not change lifetime.
3492 if (SCS1.QualificationIncludesObjCLifetime !=
3493 SCS2.QualificationIncludesObjCLifetime) {
3494 Result = SCS1.QualificationIncludesObjCLifetime
3495 ? ImplicitConversionSequence::Worse
3496 : ImplicitConversionSequence::Better;
3497 }
3498
John McCall5c32be02010-08-24 20:38:10 +00003499 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003500 // Within each iteration of the loop, we check the qualifiers to
3501 // determine if this still looks like a qualification
3502 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003503 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003504 // until there are no more pointers or pointers-to-members left
3505 // to unwrap. This essentially mimics what
3506 // IsQualificationConversion does, but here we're checking for a
3507 // strict subset of qualifiers.
3508 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3509 // The qualifiers are the same, so this doesn't tell us anything
3510 // about how the sequences rank.
3511 ;
3512 else if (T2.isMoreQualifiedThan(T1)) {
3513 // T1 has fewer qualifiers, so it could be the better sequence.
3514 if (Result == ImplicitConversionSequence::Worse)
3515 // Neither has qualifiers that are a subset of the other's
3516 // qualifiers.
3517 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003518
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003519 Result = ImplicitConversionSequence::Better;
3520 } else if (T1.isMoreQualifiedThan(T2)) {
3521 // T2 has fewer qualifiers, so it could be the better sequence.
3522 if (Result == ImplicitConversionSequence::Better)
3523 // Neither has qualifiers that are a subset of the other's
3524 // qualifiers.
3525 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003526
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003527 Result = ImplicitConversionSequence::Worse;
3528 } else {
3529 // Qualifiers are disjoint.
3530 return ImplicitConversionSequence::Indistinguishable;
3531 }
3532
3533 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003534 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003535 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003536 }
3537
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003538 // Check that the winning standard conversion sequence isn't using
3539 // the deprecated string literal array to pointer conversion.
3540 switch (Result) {
3541 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003542 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003543 Result = ImplicitConversionSequence::Indistinguishable;
3544 break;
3545
3546 case ImplicitConversionSequence::Indistinguishable:
3547 break;
3548
3549 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003550 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003551 Result = ImplicitConversionSequence::Indistinguishable;
3552 break;
3553 }
3554
3555 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003556}
3557
Douglas Gregor5c407d92008-10-23 00:40:37 +00003558/// CompareDerivedToBaseConversions - Compares two standard conversion
3559/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003560/// various kinds of derived-to-base conversions (C++
3561/// [over.ics.rank]p4b3). As part of these checks, we also look at
3562/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003563ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003564CompareDerivedToBaseConversions(Sema &S,
3565 const StandardConversionSequence& SCS1,
3566 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003567 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003568 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003569 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003570 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003571
3572 // Adjust the types we're converting from via the array-to-pointer
3573 // conversion, if we need to.
3574 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003575 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003576 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003577 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003578
3579 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003580 FromType1 = S.Context.getCanonicalType(FromType1);
3581 ToType1 = S.Context.getCanonicalType(ToType1);
3582 FromType2 = S.Context.getCanonicalType(FromType2);
3583 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003584
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003585 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003586 //
3587 // If class B is derived directly or indirectly from class A and
3588 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003589 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003590 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003591 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003592 SCS2.Second == ICK_Pointer_Conversion &&
3593 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3594 FromType1->isPointerType() && FromType2->isPointerType() &&
3595 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003596 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003597 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003598 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003599 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003600 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003601 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003602 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003603 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003604
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003605 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003606 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003607 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003608 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003609 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003610 return ImplicitConversionSequence::Worse;
3611 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003612
3613 // -- conversion of B* to A* is better than conversion of C* to A*,
3614 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003615 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003616 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003617 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003618 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003619 }
3620 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3621 SCS2.Second == ICK_Pointer_Conversion) {
3622 const ObjCObjectPointerType *FromPtr1
3623 = FromType1->getAs<ObjCObjectPointerType>();
3624 const ObjCObjectPointerType *FromPtr2
3625 = FromType2->getAs<ObjCObjectPointerType>();
3626 const ObjCObjectPointerType *ToPtr1
3627 = ToType1->getAs<ObjCObjectPointerType>();
3628 const ObjCObjectPointerType *ToPtr2
3629 = ToType2->getAs<ObjCObjectPointerType>();
3630
3631 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3632 // Apply the same conversion ranking rules for Objective-C pointer types
3633 // that we do for C++ pointers to class types. However, we employ the
3634 // Objective-C pseudo-subtyping relationship used for assignment of
3635 // Objective-C pointer types.
3636 bool FromAssignLeft
3637 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3638 bool FromAssignRight
3639 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3640 bool ToAssignLeft
3641 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3642 bool ToAssignRight
3643 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3644
3645 // A conversion to an a non-id object pointer type or qualified 'id'
3646 // type is better than a conversion to 'id'.
3647 if (ToPtr1->isObjCIdType() &&
3648 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3649 return ImplicitConversionSequence::Worse;
3650 if (ToPtr2->isObjCIdType() &&
3651 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3652 return ImplicitConversionSequence::Better;
3653
3654 // A conversion to a non-id object pointer type is better than a
3655 // conversion to a qualified 'id' type
3656 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3657 return ImplicitConversionSequence::Worse;
3658 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3659 return ImplicitConversionSequence::Better;
3660
3661 // A conversion to an a non-Class object pointer type or qualified 'Class'
3662 // type is better than a conversion to 'Class'.
3663 if (ToPtr1->isObjCClassType() &&
3664 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3665 return ImplicitConversionSequence::Worse;
3666 if (ToPtr2->isObjCClassType() &&
3667 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3668 return ImplicitConversionSequence::Better;
3669
3670 // A conversion to a non-Class object pointer type is better than a
3671 // conversion to a qualified 'Class' type.
3672 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3673 return ImplicitConversionSequence::Worse;
3674 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3675 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003676
Douglas Gregor058d3de2011-01-31 18:51:41 +00003677 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3678 if (S.Context.hasSameType(FromType1, FromType2) &&
3679 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3680 (ToAssignLeft != ToAssignRight))
3681 return ToAssignLeft? ImplicitConversionSequence::Worse
3682 : ImplicitConversionSequence::Better;
3683
3684 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3685 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3686 (FromAssignLeft != FromAssignRight))
3687 return FromAssignLeft? ImplicitConversionSequence::Better
3688 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003689 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003690 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003691
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003692 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003693 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3694 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3695 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003697 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003699 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003701 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003703 ToType2->getAs<MemberPointerType>();
3704 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3705 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3706 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3707 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3708 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3709 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3710 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3711 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003712 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003713 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003714 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003715 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003716 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003717 return ImplicitConversionSequence::Better;
3718 }
3719 // conversion of B::* to C::* is better than conversion of A::* to C::*
3720 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003721 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003722 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003723 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003724 return ImplicitConversionSequence::Worse;
3725 }
3726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Douglas Gregor5ab11652010-04-17 22:01:05 +00003728 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003729 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003730 // -- binding of an expression of type C to a reference of type
3731 // B& is better than binding an expression of type C to a
3732 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003733 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3734 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3735 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003736 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003737 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003738 return ImplicitConversionSequence::Worse;
3739 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003740
Douglas Gregor2fe98832008-11-03 19:09:14 +00003741 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003742 // -- binding of an expression of type B to a reference of type
3743 // A& is better than binding an expression of type C to a
3744 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003745 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3746 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3747 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003748 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003749 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003750 return ImplicitConversionSequence::Worse;
3751 }
3752 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003753
Douglas Gregor5c407d92008-10-23 00:40:37 +00003754 return ImplicitConversionSequence::Indistinguishable;
3755}
3756
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003757/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3758/// determine whether they are reference-related,
3759/// reference-compatible, reference-compatible with added
3760/// qualification, or incompatible, for use in C++ initialization by
3761/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3762/// type, and the first type (T1) is the pointee type of the reference
3763/// type being initialized.
3764Sema::ReferenceCompareResult
3765Sema::CompareReferenceRelationship(SourceLocation Loc,
3766 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003767 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003768 bool &ObjCConversion,
3769 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003770 assert(!OrigT1->isReferenceType() &&
3771 "T1 must be the pointee type of the reference type");
3772 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3773
3774 QualType T1 = Context.getCanonicalType(OrigT1);
3775 QualType T2 = Context.getCanonicalType(OrigT2);
3776 Qualifiers T1Quals, T2Quals;
3777 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3778 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3779
3780 // C++ [dcl.init.ref]p4:
3781 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3782 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3783 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003784 DerivedToBase = false;
3785 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003786 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003787 if (UnqualT1 == UnqualT2) {
3788 // Nothing to do.
3789 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003790 IsDerivedFrom(UnqualT2, UnqualT1))
3791 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003792 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3793 UnqualT2->isObjCObjectOrInterfaceType() &&
3794 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3795 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003796 else
3797 return Ref_Incompatible;
3798
3799 // At this point, we know that T1 and T2 are reference-related (at
3800 // least).
3801
3802 // If the type is an array type, promote the element qualifiers to the type
3803 // for comparison.
3804 if (isa<ArrayType>(T1) && T1Quals)
3805 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3806 if (isa<ArrayType>(T2) && T2Quals)
3807 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3808
3809 // C++ [dcl.init.ref]p4:
3810 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3811 // reference-related to T2 and cv1 is the same cv-qualification
3812 // as, or greater cv-qualification than, cv2. For purposes of
3813 // overload resolution, cases for which cv1 is greater
3814 // cv-qualification than cv2 are identified as
3815 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003816 //
3817 // Note that we also require equivalence of Objective-C GC and address-space
3818 // qualifiers when performing these computations, so that e.g., an int in
3819 // address space 1 is not reference-compatible with an int in address
3820 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003821 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3822 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3823 T1Quals.removeObjCLifetime();
3824 T2Quals.removeObjCLifetime();
3825 ObjCLifetimeConversion = true;
3826 }
3827
Douglas Gregord517d552011-04-28 17:56:11 +00003828 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003829 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003830 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003831 return Ref_Compatible_With_Added_Qualification;
3832 else
3833 return Ref_Related;
3834}
3835
Douglas Gregor836a7e82010-08-11 02:15:33 +00003836/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003837/// with DeclType. Return true if something definite is found.
3838static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003839FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3840 QualType DeclType, SourceLocation DeclLoc,
3841 Expr *Init, QualType T2, bool AllowRvalues,
3842 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003843 assert(T2->isRecordType() && "Can only find conversions of record types.");
3844 CXXRecordDecl *T2RecordDecl
3845 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3846
3847 OverloadCandidateSet CandidateSet(DeclLoc);
3848 const UnresolvedSetImpl *Conversions
3849 = T2RecordDecl->getVisibleConversionFunctions();
3850 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3851 E = Conversions->end(); I != E; ++I) {
3852 NamedDecl *D = *I;
3853 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3854 if (isa<UsingShadowDecl>(D))
3855 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3856
3857 FunctionTemplateDecl *ConvTemplate
3858 = dyn_cast<FunctionTemplateDecl>(D);
3859 CXXConversionDecl *Conv;
3860 if (ConvTemplate)
3861 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3862 else
3863 Conv = cast<CXXConversionDecl>(D);
3864
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003866 // explicit conversions, skip it.
3867 if (!AllowExplicit && Conv->isExplicit())
3868 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregor836a7e82010-08-11 02:15:33 +00003870 if (AllowRvalues) {
3871 bool DerivedToBase = false;
3872 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003873 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003874
3875 // If we are initializing an rvalue reference, don't permit conversion
3876 // functions that return lvalues.
3877 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3878 const ReferenceType *RefType
3879 = Conv->getConversionType()->getAs<LValueReferenceType>();
3880 if (RefType && !RefType->getPointeeType()->isFunctionType())
3881 continue;
3882 }
3883
Douglas Gregor836a7e82010-08-11 02:15:33 +00003884 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003885 S.CompareReferenceRelationship(
3886 DeclLoc,
3887 Conv->getConversionType().getNonReferenceType()
3888 .getUnqualifiedType(),
3889 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003890 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003891 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003892 continue;
3893 } else {
3894 // If the conversion function doesn't return a reference type,
3895 // it can't be considered for this conversion. An rvalue reference
3896 // is only acceptable if its referencee is a function type.
3897
3898 const ReferenceType *RefType =
3899 Conv->getConversionType()->getAs<ReferenceType>();
3900 if (!RefType ||
3901 (!RefType->isLValueReferenceType() &&
3902 !RefType->getPointeeType()->isFunctionType()))
3903 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregor836a7e82010-08-11 02:15:33 +00003906 if (ConvTemplate)
3907 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003908 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003909 else
3910 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003911 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003912 }
3913
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003914 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3915
Sebastian Redld92badf2010-06-30 18:13:39 +00003916 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003917 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003918 case OR_Success:
3919 // C++ [over.ics.ref]p1:
3920 //
3921 // [...] If the parameter binds directly to the result of
3922 // applying a conversion function to the argument
3923 // expression, the implicit conversion sequence is a
3924 // user-defined conversion sequence (13.3.3.1.2), with the
3925 // second standard conversion sequence either an identity
3926 // conversion or, if the conversion function returns an
3927 // entity of a type that is a derived class of the parameter
3928 // type, a derived-to-base Conversion.
3929 if (!Best->FinalConversion.DirectBinding)
3930 return false;
3931
Chandler Carruth30141632011-02-25 19:41:05 +00003932 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003933 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003934 ICS.setUserDefined();
3935 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3936 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003937 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003938 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003939 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003940 ICS.UserDefined.EllipsisConversion = false;
3941 assert(ICS.UserDefined.After.ReferenceBinding &&
3942 ICS.UserDefined.After.DirectBinding &&
3943 "Expected a direct reference binding!");
3944 return true;
3945
3946 case OR_Ambiguous:
3947 ICS.setAmbiguous();
3948 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3949 Cand != CandidateSet.end(); ++Cand)
3950 if (Cand->Viable)
3951 ICS.Ambiguous.addConversion(Cand->Function);
3952 return true;
3953
3954 case OR_No_Viable_Function:
3955 case OR_Deleted:
3956 // There was no suitable conversion, or we found a deleted
3957 // conversion; continue with other checks.
3958 return false;
3959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003960
David Blaikie8a40f702012-01-17 06:56:22 +00003961 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00003962}
3963
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003964/// \brief Compute an implicit conversion sequence for reference
3965/// initialization.
3966static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003967TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003968 SourceLocation DeclLoc,
3969 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003970 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003971 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3972
3973 // Most paths end in a failed conversion.
3974 ImplicitConversionSequence ICS;
3975 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3976
3977 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3978 QualType T2 = Init->getType();
3979
3980 // If the initializer is the address of an overloaded function, try
3981 // to resolve the overloaded function. If all goes well, T2 is the
3982 // type of the resulting function.
3983 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3984 DeclAccessPair Found;
3985 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3986 false, Found))
3987 T2 = Fn->getType();
3988 }
3989
3990 // Compute some basic properties of the types and the initializer.
3991 bool isRValRef = DeclType->isRValueReferenceType();
3992 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003993 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003994 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003995 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003996 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003997 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003998 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003999
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004000
Sebastian Redld92badf2010-06-30 18:13:39 +00004001 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004002 // A reference to type "cv1 T1" is initialized by an expression
4003 // of type "cv2 T2" as follows:
4004
Sebastian Redld92badf2010-06-30 18:13:39 +00004005 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004006 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004007 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4008 // reference-compatible with "cv2 T2," or
4009 //
4010 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4011 if (InitCategory.isLValue() &&
4012 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004013 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004014 // When a parameter of reference type binds directly (8.5.3)
4015 // to an argument expression, the implicit conversion sequence
4016 // is the identity conversion, unless the argument expression
4017 // has a type that is a derived class of the parameter type,
4018 // in which case the implicit conversion sequence is a
4019 // derived-to-base Conversion (13.3.3.1).
4020 ICS.setStandard();
4021 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004022 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4023 : ObjCConversion? ICK_Compatible_Conversion
4024 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004025 ICS.Standard.Third = ICK_Identity;
4026 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4027 ICS.Standard.setToType(0, T2);
4028 ICS.Standard.setToType(1, T1);
4029 ICS.Standard.setToType(2, T1);
4030 ICS.Standard.ReferenceBinding = true;
4031 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004032 ICS.Standard.IsLvalueReference = !isRValRef;
4033 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4034 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004035 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004036 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004037 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004038
Sebastian Redld92badf2010-06-30 18:13:39 +00004039 // Nothing more to do: the inaccessibility/ambiguity check for
4040 // derived-to-base conversions is suppressed when we're
4041 // computing the implicit conversion sequence (C++
4042 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004043 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004044 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004045
Sebastian Redld92badf2010-06-30 18:13:39 +00004046 // -- has a class type (i.e., T2 is a class type), where T1 is
4047 // not reference-related to T2, and can be implicitly
4048 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4049 // is reference-compatible with "cv3 T3" 92) (this
4050 // conversion is selected by enumerating the applicable
4051 // conversion functions (13.3.1.6) and choosing the best
4052 // one through overload resolution (13.3)),
4053 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004055 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004056 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4057 Init, T2, /*AllowRvalues=*/false,
4058 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004059 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004060 }
4061 }
4062
Sebastian Redld92badf2010-06-30 18:13:39 +00004063 // -- Otherwise, the reference shall be an lvalue reference to a
4064 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004065 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004067 // We actually handle one oddity of C++ [over.ics.ref] at this
4068 // point, which is that, due to p2 (which short-circuits reference
4069 // binding by only attempting a simple conversion for non-direct
4070 // bindings) and p3's strange wording, we allow a const volatile
4071 // reference to bind to an rvalue. Hence the check for the presence
4072 // of "const" rather than checking for "const" being the only
4073 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004074 // This is also the point where rvalue references and lvalue inits no longer
4075 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004076 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004077 return ICS;
4078
Douglas Gregorf143cd52011-01-24 16:14:37 +00004079 // -- If the initializer expression
4080 //
4081 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004082 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004083 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4084 (InitCategory.isXValue() ||
4085 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4086 (InitCategory.isLValue() && T2->isFunctionType()))) {
4087 ICS.setStandard();
4088 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004090 : ObjCConversion? ICK_Compatible_Conversion
4091 : ICK_Identity;
4092 ICS.Standard.Third = ICK_Identity;
4093 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4094 ICS.Standard.setToType(0, T2);
4095 ICS.Standard.setToType(1, T1);
4096 ICS.Standard.setToType(2, T1);
4097 ICS.Standard.ReferenceBinding = true;
4098 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4099 // binding unless we're binding to a class prvalue.
4100 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4101 // allow the use of rvalue references in C++98/03 for the benefit of
4102 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004104 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004105 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004106 ICS.Standard.IsLvalueReference = !isRValRef;
4107 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004109 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004110 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004111 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114
Douglas Gregorf143cd52011-01-24 16:14:37 +00004115 // -- has a class type (i.e., T2 is a class type), where T1 is not
4116 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117 // an xvalue, class prvalue, or function lvalue of type
4118 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004119 // "cv3 T3",
4120 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004122 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004124 // class subobject).
4125 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004127 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4128 Init, T2, /*AllowRvalues=*/true,
4129 AllowExplicit)) {
4130 // In the second case, if the reference is an rvalue reference
4131 // and the second standard conversion sequence of the
4132 // user-defined conversion sequence includes an lvalue-to-rvalue
4133 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004135 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4136 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4137
Douglas Gregor95273c32011-01-21 16:36:05 +00004138 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004141 // -- Otherwise, a temporary of type "cv1 T1" is created and
4142 // initialized from the initializer expression using the
4143 // rules for a non-reference copy initialization (8.5). The
4144 // reference is then bound to the temporary. If T1 is
4145 // reference-related to T2, cv1 must be the same
4146 // cv-qualification as, or greater cv-qualification than,
4147 // cv2; otherwise, the program is ill-formed.
4148 if (RefRelationship == Sema::Ref_Related) {
4149 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4150 // we would be reference-compatible or reference-compatible with
4151 // added qualification. But that wasn't the case, so the reference
4152 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004153 //
4154 // Note that we only want to check address spaces and cvr-qualifiers here.
4155 // ObjC GC and lifetime qualifiers aren't important.
4156 Qualifiers T1Quals = T1.getQualifiers();
4157 Qualifiers T2Quals = T2.getQualifiers();
4158 T1Quals.removeObjCGCAttr();
4159 T1Quals.removeObjCLifetime();
4160 T2Quals.removeObjCGCAttr();
4161 T2Quals.removeObjCLifetime();
4162 if (!T1Quals.compatiblyIncludes(T2Quals))
4163 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004164 }
4165
4166 // If at least one of the types is a class type, the types are not
4167 // related, and we aren't allowed any user conversions, the
4168 // reference binding fails. This case is important for breaking
4169 // recursion, since TryImplicitConversion below will attempt to
4170 // create a temporary through the use of a copy constructor.
4171 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4172 (T1->isRecordType() || T2->isRecordType()))
4173 return ICS;
4174
Douglas Gregorcba72b12011-01-21 05:18:22 +00004175 // If T1 is reference-related to T2 and the reference is an rvalue
4176 // reference, the initializer expression shall not be an lvalue.
4177 if (RefRelationship >= Sema::Ref_Related &&
4178 isRValRef && Init->Classify(S.Context).isLValue())
4179 return ICS;
4180
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004181 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004182 // When a parameter of reference type is not bound directly to
4183 // an argument expression, the conversion sequence is the one
4184 // required to convert the argument expression to the
4185 // underlying type of the reference according to
4186 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4187 // to copy-initializing a temporary of the underlying type with
4188 // the argument expression. Any difference in top-level
4189 // cv-qualification is subsumed by the initialization itself
4190 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004191 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4192 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004193 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004194 /*CStyle=*/false,
4195 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004196
4197 // Of course, that's still a reference binding.
4198 if (ICS.isStandard()) {
4199 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004200 ICS.Standard.IsLvalueReference = !isRValRef;
4201 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4202 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004203 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004204 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004205 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004206 // Don't allow rvalue references to bind to lvalues.
4207 if (DeclType->isRValueReferenceType()) {
4208 if (const ReferenceType *RefType
4209 = ICS.UserDefined.ConversionFunction->getResultType()
4210 ->getAs<LValueReferenceType>()) {
4211 if (!RefType->getPointeeType()->isFunctionType()) {
4212 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4213 DeclType);
4214 return ICS;
4215 }
4216 }
4217 }
4218
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004219 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004220 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4221 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4222 ICS.UserDefined.After.BindsToRvalue = true;
4223 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4224 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004225 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004226
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227 return ICS;
4228}
4229
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004230static ImplicitConversionSequence
4231TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4232 bool SuppressUserConversions,
4233 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004234 bool AllowObjCWritebackConversion,
4235 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004236
4237/// TryListConversion - Try to copy-initialize a value of type ToType from the
4238/// initializer list From.
4239static ImplicitConversionSequence
4240TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4241 bool SuppressUserConversions,
4242 bool InOverloadResolution,
4243 bool AllowObjCWritebackConversion) {
4244 // C++11 [over.ics.list]p1:
4245 // When an argument is an initializer list, it is not an expression and
4246 // special rules apply for converting it to a parameter type.
4247
4248 ImplicitConversionSequence Result;
4249 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004250 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004251
Sebastian Redl09edce02012-01-23 22:09:39 +00004252 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004253 // initialized from init lists.
4254 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4255 return Result;
4256
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004257 // C++11 [over.ics.list]p2:
4258 // If the parameter type is std::initializer_list<X> or "array of X" and
4259 // all the elements can be implicitly converted to X, the implicit
4260 // conversion sequence is the worst conversion necessary to convert an
4261 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004262 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004263 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004264 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004265 X = S.Context.getBaseElementType(ToType);
4266 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004267 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004268 if (!X.isNull()) {
4269 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4270 Expr *Init = From->getInit(i);
4271 ImplicitConversionSequence ICS =
4272 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4273 InOverloadResolution,
4274 AllowObjCWritebackConversion);
4275 // If a single element isn't convertible, fail.
4276 if (ICS.isBad()) {
4277 Result = ICS;
4278 break;
4279 }
4280 // Otherwise, look for the worst conversion.
4281 if (Result.isBad() ||
4282 CompareImplicitConversionSequences(S, ICS, Result) ==
4283 ImplicitConversionSequence::Worse)
4284 Result = ICS;
4285 }
4286 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004287 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004288 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004289 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004290
4291 // C++11 [over.ics.list]p3:
4292 // Otherwise, if the parameter is a non-aggregate class X and overload
4293 // resolution chooses a single best constructor [...] the implicit
4294 // conversion sequence is a user-defined conversion sequence. If multiple
4295 // constructors are viable but none is better than the others, the
4296 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004297 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4298 // This function can deal with initializer lists.
4299 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4300 /*AllowExplicit=*/false,
4301 InOverloadResolution, /*CStyle=*/false,
4302 AllowObjCWritebackConversion);
4303 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004304 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004305 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004306
4307 // C++11 [over.ics.list]p4:
4308 // Otherwise, if the parameter has an aggregate type which can be
4309 // initialized from the initializer list [...] the implicit conversion
4310 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004311 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004312 // Type is an aggregate, argument is an init list. At this point it comes
4313 // down to checking whether the initialization works.
4314 // FIXME: Find out whether this parameter is consumed or not.
4315 InitializedEntity Entity =
4316 InitializedEntity::InitializeParameter(S.Context, ToType,
4317 /*Consumed=*/false);
4318 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4319 Result.setUserDefined();
4320 Result.UserDefined.Before.setAsIdentityConversion();
4321 // Initializer lists don't have a type.
4322 Result.UserDefined.Before.setFromType(QualType());
4323 Result.UserDefined.Before.setAllToTypes(QualType());
4324
4325 Result.UserDefined.After.setAsIdentityConversion();
4326 Result.UserDefined.After.setFromType(ToType);
4327 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004328 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004329 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004330 return Result;
4331 }
4332
4333 // C++11 [over.ics.list]p5:
4334 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004335 if (ToType->isReferenceType()) {
4336 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4337 // mention initializer lists in any way. So we go by what list-
4338 // initialization would do and try to extrapolate from that.
4339
4340 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4341
4342 // If the initializer list has a single element that is reference-related
4343 // to the parameter type, we initialize the reference from that.
4344 if (From->getNumInits() == 1) {
4345 Expr *Init = From->getInit(0);
4346
4347 QualType T2 = Init->getType();
4348
4349 // If the initializer is the address of an overloaded function, try
4350 // to resolve the overloaded function. If all goes well, T2 is the
4351 // type of the resulting function.
4352 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4353 DeclAccessPair Found;
4354 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4355 Init, ToType, false, Found))
4356 T2 = Fn->getType();
4357 }
4358
4359 // Compute some basic properties of the types and the initializer.
4360 bool dummy1 = false;
4361 bool dummy2 = false;
4362 bool dummy3 = false;
4363 Sema::ReferenceCompareResult RefRelationship
4364 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4365 dummy2, dummy3);
4366
4367 if (RefRelationship >= Sema::Ref_Related)
4368 return TryReferenceInit(S, Init, ToType,
4369 /*FIXME:*/From->getLocStart(),
4370 SuppressUserConversions,
4371 /*AllowExplicit=*/false);
4372 }
4373
4374 // Otherwise, we bind the reference to a temporary created from the
4375 // initializer list.
4376 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4377 InOverloadResolution,
4378 AllowObjCWritebackConversion);
4379 if (Result.isFailure())
4380 return Result;
4381 assert(!Result.isEllipsis() &&
4382 "Sub-initialization cannot result in ellipsis conversion.");
4383
4384 // Can we even bind to a temporary?
4385 if (ToType->isRValueReferenceType() ||
4386 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4387 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4388 Result.UserDefined.After;
4389 SCS.ReferenceBinding = true;
4390 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4391 SCS.BindsToRvalue = true;
4392 SCS.BindsToFunctionLvalue = false;
4393 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4394 SCS.ObjCLifetimeConversionBinding = false;
4395 } else
4396 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4397 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004398 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004399 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004400
4401 // C++11 [over.ics.list]p6:
4402 // Otherwise, if the parameter type is not a class:
4403 if (!ToType->isRecordType()) {
4404 // - if the initializer list has one element, the implicit conversion
4405 // sequence is the one required to convert the element to the
4406 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004407 unsigned NumInits = From->getNumInits();
4408 if (NumInits == 1)
4409 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4410 SuppressUserConversions,
4411 InOverloadResolution,
4412 AllowObjCWritebackConversion);
4413 // - if the initializer list has no elements, the implicit conversion
4414 // sequence is the identity conversion.
4415 else if (NumInits == 0) {
4416 Result.setStandard();
4417 Result.Standard.setAsIdentityConversion();
4418 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004419 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004420 return Result;
4421 }
4422
4423 // C++11 [over.ics.list]p7:
4424 // In all cases other than those enumerated above, no conversion is possible
4425 return Result;
4426}
4427
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004428/// TryCopyInitialization - Try to copy-initialize a value of type
4429/// ToType from the expression From. Return the implicit conversion
4430/// sequence required to pass this argument, which may be a bad
4431/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004432/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004433/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004434static ImplicitConversionSequence
4435TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004437 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004438 bool AllowObjCWritebackConversion,
4439 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004440 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4441 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4442 InOverloadResolution,AllowObjCWritebackConversion);
4443
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004444 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004445 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004446 /*FIXME:*/From->getLocStart(),
4447 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004448 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004449
John McCall5c32be02010-08-24 20:38:10 +00004450 return TryImplicitConversion(S, From, ToType,
4451 SuppressUserConversions,
4452 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004453 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004454 /*CStyle=*/false,
4455 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004456}
4457
Anna Zaks1b068122011-07-28 19:46:48 +00004458static bool TryCopyInitialization(const CanQualType FromQTy,
4459 const CanQualType ToQTy,
4460 Sema &S,
4461 SourceLocation Loc,
4462 ExprValueKind FromVK) {
4463 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4464 ImplicitConversionSequence ICS =
4465 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4466
4467 return !ICS.isBad();
4468}
4469
Douglas Gregor436424c2008-11-18 23:14:02 +00004470/// TryObjectArgumentInitialization - Try to initialize the object
4471/// parameter of the given member function (@c Method) from the
4472/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004473static ImplicitConversionSequence
4474TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004475 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004476 CXXMethodDecl *Method,
4477 CXXRecordDecl *ActingContext) {
4478 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004479 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4480 // const volatile object.
4481 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4482 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004483 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004484
4485 // Set up the conversion sequence as a "bad" conversion, to allow us
4486 // to exit early.
4487 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004488
4489 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004490 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004491 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004492 FromType = PT->getPointeeType();
4493
Douglas Gregor02824322011-01-26 19:30:28 +00004494 // When we had a pointer, it's implicitly dereferenced, so we
4495 // better have an lvalue.
4496 assert(FromClassification.isLValue());
4497 }
4498
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004499 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004500
Douglas Gregor02824322011-01-26 19:30:28 +00004501 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004503 // parameter is
4504 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004505 // - "lvalue reference to cv X" for functions declared without a
4506 // ref-qualifier or with the & ref-qualifier
4507 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004508 // ref-qualifier
4509 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004511 // cv-qualification on the member function declaration.
4512 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004514 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004515 // (C++ [over.match.funcs]p5). We perform a simplified version of
4516 // reference binding here, that allows class rvalues to bind to
4517 // non-constant references.
4518
Douglas Gregor02824322011-01-26 19:30:28 +00004519 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004520 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004522 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004523 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004524 ICS.setBad(BadConversionSequence::bad_qualifiers,
4525 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004526 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004527 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004528
4529 // Check that we have either the same type or a derived type. It
4530 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004531 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004532 ImplicitConversionKind SecondKind;
4533 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4534 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004535 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004536 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004537 else {
John McCall65eb8792010-02-25 01:37:24 +00004538 ICS.setBad(BadConversionSequence::unrelated_class,
4539 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004540 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004541 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004542
Douglas Gregor02824322011-01-26 19:30:28 +00004543 // Check the ref-qualifier.
4544 switch (Method->getRefQualifier()) {
4545 case RQ_None:
4546 // Do nothing; we don't care about lvalueness or rvalueness.
4547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
Douglas Gregor02824322011-01-26 19:30:28 +00004549 case RQ_LValue:
4550 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4551 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004553 ImplicitParamType);
4554 return ICS;
4555 }
4556 break;
4557
4558 case RQ_RValue:
4559 if (!FromClassification.isRValue()) {
4560 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004562 ImplicitParamType);
4563 return ICS;
4564 }
4565 break;
4566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
Douglas Gregor436424c2008-11-18 23:14:02 +00004568 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004569 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004570 ICS.Standard.setAsIdentityConversion();
4571 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004572 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004573 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004574 ICS.Standard.ReferenceBinding = true;
4575 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004577 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004578 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4579 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4580 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004581 return ICS;
4582}
4583
4584/// PerformObjectArgumentInitialization - Perform initialization of
4585/// the implicit object parameter for the given Method with the given
4586/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004587ExprResult
4588Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004590 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004591 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004592 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004593 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004594 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004595
Douglas Gregor02824322011-01-26 19:30:28 +00004596 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004597 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004598 FromRecordType = PT->getPointeeType();
4599 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004600 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004601 } else {
4602 FromRecordType = From->getType();
4603 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004604 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004605 }
4606
John McCall6e9f8f62009-12-03 04:06:58 +00004607 // Note that we always use the true parent context when performing
4608 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004609 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004610 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4611 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004612 if (ICS.isBad()) {
4613 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4614 Qualifiers FromQs = FromRecordType.getQualifiers();
4615 Qualifiers ToQs = DestType.getQualifiers();
4616 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4617 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004618 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004619 diag::err_member_function_call_bad_cvr)
4620 << Method->getDeclName() << FromRecordType << (CVR - 1)
4621 << From->getSourceRange();
4622 Diag(Method->getLocation(), diag::note_previous_decl)
4623 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004624 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004625 }
4626 }
4627
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004628 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004629 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004630 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004631 }
Mike Stump11289f42009-09-09 15:08:12 +00004632
John Wiegley01296292011-04-08 18:41:53 +00004633 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4634 ExprResult FromRes =
4635 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4636 if (FromRes.isInvalid())
4637 return ExprError();
4638 From = FromRes.take();
4639 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004640
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004641 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004642 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004643 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004644 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004645}
4646
Douglas Gregor5fb53972009-01-14 15:45:31 +00004647/// TryContextuallyConvertToBool - Attempt to contextually convert the
4648/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004649static ImplicitConversionSequence
4650TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004651 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004652 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004653 // FIXME: Are these flags correct?
4654 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004655 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004656 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004657 /*CStyle=*/false,
4658 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004659}
4660
4661/// PerformContextuallyConvertToBool - Perform a contextual conversion
4662/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004663ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004664 if (checkPlaceholderForOverload(*this, From))
4665 return ExprError();
4666
John McCall5c32be02010-08-24 20:38:10 +00004667 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004668 if (!ICS.isBad())
4669 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670
Fariborz Jahanian76197412009-11-18 18:26:29 +00004671 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004672 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004673 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004674 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004675 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004676}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Richard Smithf8379a02012-01-18 23:55:52 +00004678/// Check that the specified conversion is permitted in a converted constant
4679/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4680/// is acceptable.
4681static bool CheckConvertedConstantConversions(Sema &S,
4682 StandardConversionSequence &SCS) {
4683 // Since we know that the target type is an integral or unscoped enumeration
4684 // type, most conversion kinds are impossible. All possible First and Third
4685 // conversions are fine.
4686 switch (SCS.Second) {
4687 case ICK_Identity:
4688 case ICK_Integral_Promotion:
4689 case ICK_Integral_Conversion:
4690 return true;
4691
4692 case ICK_Boolean_Conversion:
4693 // Conversion from an integral or unscoped enumeration type to bool is
4694 // classified as ICK_Boolean_Conversion, but it's also an integral
4695 // conversion, so it's permitted in a converted constant expression.
4696 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4697 SCS.getToType(2)->isBooleanType();
4698
4699 case ICK_Floating_Integral:
4700 case ICK_Complex_Real:
4701 return false;
4702
4703 case ICK_Lvalue_To_Rvalue:
4704 case ICK_Array_To_Pointer:
4705 case ICK_Function_To_Pointer:
4706 case ICK_NoReturn_Adjustment:
4707 case ICK_Qualification:
4708 case ICK_Compatible_Conversion:
4709 case ICK_Vector_Conversion:
4710 case ICK_Vector_Splat:
4711 case ICK_Derived_To_Base:
4712 case ICK_Pointer_Conversion:
4713 case ICK_Pointer_Member:
4714 case ICK_Block_Pointer_Conversion:
4715 case ICK_Writeback_Conversion:
4716 case ICK_Floating_Promotion:
4717 case ICK_Complex_Promotion:
4718 case ICK_Complex_Conversion:
4719 case ICK_Floating_Conversion:
4720 case ICK_TransparentUnionConversion:
4721 llvm_unreachable("unexpected second conversion kind");
4722
4723 case ICK_Num_Conversion_Kinds:
4724 break;
4725 }
4726
4727 llvm_unreachable("unknown conversion kind");
4728}
4729
4730/// CheckConvertedConstantExpression - Check that the expression From is a
4731/// converted constant expression of type T, perform the conversion and produce
4732/// the converted expression, per C++11 [expr.const]p3.
4733ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4734 llvm::APSInt &Value,
4735 CCEKind CCE) {
4736 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4737 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4738
4739 if (checkPlaceholderForOverload(*this, From))
4740 return ExprError();
4741
4742 // C++11 [expr.const]p3 with proposed wording fixes:
4743 // A converted constant expression of type T is a core constant expression,
4744 // implicitly converted to a prvalue of type T, where the converted
4745 // expression is a literal constant expression and the implicit conversion
4746 // sequence contains only user-defined conversions, lvalue-to-rvalue
4747 // conversions, integral promotions, and integral conversions other than
4748 // narrowing conversions.
4749 ImplicitConversionSequence ICS =
4750 TryImplicitConversion(From, T,
4751 /*SuppressUserConversions=*/false,
4752 /*AllowExplicit=*/false,
4753 /*InOverloadResolution=*/false,
4754 /*CStyle=*/false,
4755 /*AllowObjcWritebackConversion=*/false);
4756 StandardConversionSequence *SCS = 0;
4757 switch (ICS.getKind()) {
4758 case ImplicitConversionSequence::StandardConversion:
4759 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004760 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004761 diag::err_typecheck_converted_constant_expression_disallowed)
4762 << From->getType() << From->getSourceRange() << T;
4763 SCS = &ICS.Standard;
4764 break;
4765 case ImplicitConversionSequence::UserDefinedConversion:
4766 // We are converting from class type to an integral or enumeration type, so
4767 // the Before sequence must be trivial.
4768 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004769 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004770 diag::err_typecheck_converted_constant_expression_disallowed)
4771 << From->getType() << From->getSourceRange() << T;
4772 SCS = &ICS.UserDefined.After;
4773 break;
4774 case ImplicitConversionSequence::AmbiguousConversion:
4775 case ImplicitConversionSequence::BadConversion:
4776 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004777 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004778 diag::err_typecheck_converted_constant_expression)
4779 << From->getType() << From->getSourceRange() << T;
4780 return ExprError();
4781
4782 case ImplicitConversionSequence::EllipsisConversion:
4783 llvm_unreachable("ellipsis conversion in converted constant expression");
4784 }
4785
4786 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4787 if (Result.isInvalid())
4788 return Result;
4789
4790 // Check for a narrowing implicit conversion.
4791 APValue PreNarrowingValue;
Richard Smith911e1422012-01-30 22:27:01 +00004792 bool Diagnosed = false;
Richard Smithf8379a02012-01-18 23:55:52 +00004793 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4794 case NK_Variable_Narrowing:
4795 // Implicit conversion to a narrower type, and the value is not a constant
4796 // expression. We'll diagnose this in a moment.
4797 case NK_Not_Narrowing:
4798 break;
4799
4800 case NK_Constant_Narrowing:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004801 Diag(From->getLocStart(), diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004802 << CCE << /*Constant*/1
4803 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smith911e1422012-01-30 22:27:01 +00004804 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004805 break;
4806
4807 case NK_Type_Narrowing:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004808 Diag(From->getLocStart(), diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004809 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smith911e1422012-01-30 22:27:01 +00004810 Diagnosed = true;
Richard Smithf8379a02012-01-18 23:55:52 +00004811 break;
4812 }
4813
4814 // Check the expression is a constant expression.
4815 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4816 Expr::EvalResult Eval;
4817 Eval.Diag = &Notes;
4818
4819 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4820 // The expression can't be folded, so we can't keep it at this position in
4821 // the AST.
4822 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004823 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004824 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004825
4826 if (Notes.empty()) {
4827 // It's a constant expression.
4828 return Result;
4829 }
Richard Smithf8379a02012-01-18 23:55:52 +00004830 }
4831
Richard Smith911e1422012-01-30 22:27:01 +00004832 // Only issue one narrowing diagnostic.
4833 if (Diagnosed)
4834 return Result;
4835
Richard Smithf8379a02012-01-18 23:55:52 +00004836 // It's not a constant expression. Produce an appropriate diagnostic.
4837 if (Notes.size() == 1 &&
4838 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4839 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4840 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004841 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004842 << CCE << From->getSourceRange();
4843 for (unsigned I = 0; I < Notes.size(); ++I)
4844 Diag(Notes[I].first, Notes[I].second);
4845 }
Richard Smith911e1422012-01-30 22:27:01 +00004846 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004847}
4848
John McCallfec112d2011-09-09 06:11:02 +00004849/// dropPointerConversions - If the given standard conversion sequence
4850/// involves any pointer conversions, remove them. This may change
4851/// the result type of the conversion sequence.
4852static void dropPointerConversion(StandardConversionSequence &SCS) {
4853 if (SCS.Second == ICK_Pointer_Conversion) {
4854 SCS.Second = ICK_Identity;
4855 SCS.Third = ICK_Identity;
4856 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4857 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004858}
John McCall5c32be02010-08-24 20:38:10 +00004859
John McCallfec112d2011-09-09 06:11:02 +00004860/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4861/// convert the expression From to an Objective-C pointer type.
4862static ImplicitConversionSequence
4863TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4864 // Do an implicit conversion to 'id'.
4865 QualType Ty = S.Context.getObjCIdType();
4866 ImplicitConversionSequence ICS
4867 = TryImplicitConversion(S, From, Ty,
4868 // FIXME: Are these flags correct?
4869 /*SuppressUserConversions=*/false,
4870 /*AllowExplicit=*/true,
4871 /*InOverloadResolution=*/false,
4872 /*CStyle=*/false,
4873 /*AllowObjCWritebackConversion=*/false);
4874
4875 // Strip off any final conversions to 'id'.
4876 switch (ICS.getKind()) {
4877 case ImplicitConversionSequence::BadConversion:
4878 case ImplicitConversionSequence::AmbiguousConversion:
4879 case ImplicitConversionSequence::EllipsisConversion:
4880 break;
4881
4882 case ImplicitConversionSequence::UserDefinedConversion:
4883 dropPointerConversion(ICS.UserDefined.After);
4884 break;
4885
4886 case ImplicitConversionSequence::StandardConversion:
4887 dropPointerConversion(ICS.Standard);
4888 break;
4889 }
4890
4891 return ICS;
4892}
4893
4894/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4895/// conversion of the expression From to an Objective-C pointer type.
4896ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004897 if (checkPlaceholderForOverload(*this, From))
4898 return ExprError();
4899
John McCall8b07ec22010-05-15 11:32:37 +00004900 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004901 ImplicitConversionSequence ICS =
4902 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004903 if (!ICS.isBad())
4904 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004905 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004906}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004907
Richard Smith8dd34252012-02-04 07:07:42 +00004908/// Determine whether the provided type is an integral type, or an enumeration
4909/// type of a permitted flavor.
4910static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4911 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4912 : T->isIntegralOrUnscopedEnumerationType();
4913}
4914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004916/// enumeration type.
4917///
4918/// This routine will attempt to convert an expression of class type to an
4919/// integral or enumeration type, if that class type only has a single
4920/// conversion to an integral or enumeration type.
4921///
Douglas Gregor4799d032010-06-30 00:20:43 +00004922/// \param Loc The source location of the construct that requires the
4923/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004924///
Douglas Gregor4799d032010-06-30 00:20:43 +00004925/// \param FromE The expression we're converting from.
4926///
4927/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4928/// have integral or enumeration type.
4929///
4930/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4931/// incomplete class type.
4932///
4933/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4934/// explicit conversion function (because no implicit conversion functions
4935/// were available). This is a recovery mode.
4936///
4937/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4938/// showing which conversion was picked.
4939///
4940/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4941/// conversion function that could convert to integral or enumeration type.
4942///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004944/// usable conversion function.
4945///
4946/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4947/// function, which may be an extension in this case.
4948///
Richard Smith8dd34252012-02-04 07:07:42 +00004949/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4950/// enumerations should be considered.
4951///
Douglas Gregor4799d032010-06-30 00:20:43 +00004952/// \returns The expression, converted to an integral or enumeration type if
4953/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954ExprResult
John McCallb268a282010-08-23 23:25:46 +00004955Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004956 const PartialDiagnostic &NotIntDiag,
4957 const PartialDiagnostic &IncompleteDiag,
4958 const PartialDiagnostic &ExplicitConvDiag,
4959 const PartialDiagnostic &ExplicitConvNote,
4960 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004961 const PartialDiagnostic &AmbigNote,
Richard Smith8dd34252012-02-04 07:07:42 +00004962 const PartialDiagnostic &ConvDiag,
4963 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004964 // We can't perform any more checking for type-dependent expressions.
4965 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004966 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
Eli Friedman1da70392012-01-26 00:26:18 +00004968 // Process placeholders immediately.
4969 if (From->hasPlaceholderType()) {
4970 ExprResult result = CheckPlaceholderExpr(From);
4971 if (result.isInvalid()) return result;
4972 From = result.take();
4973 }
4974
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004975 // If the expression already has integral or enumeration type, we're golden.
4976 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00004977 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00004978 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004979
4980 // FIXME: Check for missing '()' if T is a function type?
4981
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982 // 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 +00004983 // expression of integral or enumeration type.
4984 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004985 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithf4c51d92012-02-04 09:53:13 +00004986 if (NotIntDiag.getDiagID())
4987 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004988 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004991 // We must have a complete class type.
4992 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004993 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004995 // Look for a conversion to an integral or enumeration type.
4996 UnresolvedSet<4> ViableConversions;
4997 UnresolvedSet<4> ExplicitConversions;
4998 const UnresolvedSetImpl *Conversions
4999 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005001 bool HadMultipleCandidates = (Conversions->size() > 1);
5002
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005003 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004 E = Conversions->end();
5005 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005006 ++I) {
5007 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005008 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5009 if (isIntegralOrEnumerationType(
5010 Conversion->getConversionType().getNonReferenceType(),
5011 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005012 if (Conversion->isExplicit())
5013 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5014 else
5015 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5016 }
Richard Smith8dd34252012-02-04 07:07:42 +00005017 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005020 switch (ViableConversions.size()) {
5021 case 0:
Richard Smithf4c51d92012-02-04 09:53:13 +00005022 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005023 DeclAccessPair Found = ExplicitConversions[0];
5024 CXXConversionDecl *Conversion
5025 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005027 // The user probably meant to invoke the given explicit
5028 // conversion; use it.
5029 QualType ConvTy
5030 = Conversion->getConversionType().getNonReferenceType();
5031 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005032 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005034 Diag(Loc, ExplicitConvDiag)
5035 << T << ConvTy
5036 << FixItHint::CreateInsertion(From->getLocStart(),
5037 "static_cast<" + TypeStr + ">(")
5038 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5039 ")");
5040 Diag(Conversion->getLocation(), ExplicitConvNote)
5041 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042
5043 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005044 // explicit conversion function.
5045 if (isSFINAEContext())
5046 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005048 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005049 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5050 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005051 if (Result.isInvalid())
5052 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005053 // Record usage of conversion in an implicit cast.
5054 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5055 CK_UserDefinedConversion,
5056 Result.get(), 0,
5057 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005060 // We'll complain below about a non-integral condition type.
5061 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 case 1: {
5064 // Apply this conversion.
5065 DeclAccessPair Found = ViableConversions[0];
5066 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Douglas Gregor4799d032010-06-30 00:20:43 +00005068 CXXConversionDecl *Conversion
5069 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5070 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00005072 if (ConvDiag.getDiagID()) {
5073 if (isSFINAEContext())
5074 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregor4799d032010-06-30 00:20:43 +00005076 Diag(Loc, ConvDiag)
5077 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005080 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5081 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005082 if (Result.isInvalid())
5083 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005084 // Record usage of conversion in an implicit cast.
5085 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5086 CK_UserDefinedConversion,
5087 Result.get(), 0,
5088 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005089 break;
5090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005092 default:
Richard Smithf4c51d92012-02-04 09:53:13 +00005093 if (!AmbigDiag.getDiagID())
5094 return Owned(From);
5095
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005096 Diag(Loc, AmbigDiag)
5097 << T << From->getSourceRange();
5098 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5099 CXXConversionDecl *Conv
5100 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5101 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5102 Diag(Conv->getLocation(), AmbigNote)
5103 << ConvTy->isEnumeralType() << ConvTy;
5104 }
John McCallb268a282010-08-23 23:25:46 +00005105 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107
Richard Smithf4c51d92012-02-04 09:53:13 +00005108 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5109 NotIntDiag.getDiagID())
5110 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005111
Eli Friedman1da70392012-01-26 00:26:18 +00005112 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005113}
5114
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005115/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005116/// candidate functions, using the given function call arguments. If
5117/// @p SuppressUserConversions, then don't allow user-defined
5118/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005119///
5120/// \para PartialOverloading true if we are performing "partial" overloading
5121/// based on an incomplete set of function arguments. This feature is used by
5122/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005123void
5124Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005125 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005126 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005127 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005128 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005129 bool PartialOverloading,
5130 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005131 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005132 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005133 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005134 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005135 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005136
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005138 if (!isa<CXXConstructorDecl>(Method)) {
5139 // If we get here, it's because we're calling a member function
5140 // that is named without a member access expression (e.g.,
5141 // "this->f") that was either written explicitly or created
5142 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005143 // function, e.g., X::f(). We use an empty type for the implied
5144 // object argument (C++ [over.call.func]p3), and the acting context
5145 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005146 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005148 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005149 return;
5150 }
5151 // We treat a constructor like a non-member function, since its object
5152 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005153 }
5154
Douglas Gregorff7028a2009-11-13 23:59:09 +00005155 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005156 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005157
Douglas Gregor27381f32009-11-23 12:27:39 +00005158 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005159 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005160
Douglas Gregorffe14e32009-11-14 01:20:54 +00005161 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5162 // C++ [class.copy]p3:
5163 // A member function template is never instantiated to perform the copy
5164 // of a class object to an object of its class type.
5165 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005166 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005167 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005168 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5169 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005170 return;
5171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005173 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005174 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005175 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005176 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005177 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005178 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005179 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005180 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005182 unsigned NumArgsInProto = Proto->getNumArgs();
5183
5184 // (C++ 13.3.2p2): A candidate function having fewer than m
5185 // parameters is viable only if it has an ellipsis in its parameter
5186 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005187 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005188 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005189 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005190 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005191 return;
5192 }
5193
5194 // (C++ 13.3.2p2): A candidate function having more than m parameters
5195 // is viable only if the (m+1)st parameter has a default argument
5196 // (8.3.6). For the purposes of overload resolution, the
5197 // parameter list is truncated on the right, so that there are
5198 // exactly m parameters.
5199 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005200 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005201 // Not enough arguments.
5202 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005203 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005204 return;
5205 }
5206
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005207 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005208 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005209 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5210 if (CheckCUDATarget(Caller, Function)) {
5211 Candidate.Viable = false;
5212 Candidate.FailureKind = ovl_fail_bad_target;
5213 return;
5214 }
5215
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005216 // Determine the implicit conversion sequences for each of the
5217 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005218 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005219 if (ArgIdx < NumArgsInProto) {
5220 // (C++ 13.3.2p3): for F to be a viable function, there shall
5221 // exist for each argument an implicit conversion sequence
5222 // (13.3.3.1) that converts that argument to the corresponding
5223 // parameter of F.
5224 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005225 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005226 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005227 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005228 /*InOverloadResolution=*/true,
5229 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005230 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005231 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005232 if (Candidate.Conversions[ArgIdx].isBad()) {
5233 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005234 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005235 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005236 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005237 } else {
5238 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5239 // argument for which there is no corresponding parameter is
5240 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005241 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005242 }
5243 }
5244}
5245
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005246/// \brief Add all of the function declarations in the given function set to
5247/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005248void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005249 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005250 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005251 bool SuppressUserConversions,
5252 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005253 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005254 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5255 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005256 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005257 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005258 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005259 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005260 Args.slice(1), CandidateSet,
5261 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005262 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005263 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005264 SuppressUserConversions);
5265 } else {
John McCalla0296f72010-03-19 07:35:19 +00005266 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005267 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5268 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005269 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005270 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005271 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005273 Args[0]->Classify(Context), Args.slice(1),
5274 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005275 else
John McCalla0296f72010-03-19 07:35:19 +00005276 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005277 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005278 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005279 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005280 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005281}
5282
John McCallf0f1cf02009-11-17 07:50:12 +00005283/// AddMethodCandidate - Adds a named decl (which is some kind of
5284/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005285void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005286 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005287 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005288 Expr **Args, unsigned NumArgs,
5289 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005290 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005291 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005292 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005293
5294 if (isa<UsingShadowDecl>(Decl))
5295 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296
John McCallf0f1cf02009-11-17 07:50:12 +00005297 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5298 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5299 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005300 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5301 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005302 ObjectType, ObjectClassification,
5303 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005304 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005305 } else {
John McCalla0296f72010-03-19 07:35:19 +00005306 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005307 ObjectType, ObjectClassification,
5308 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005309 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005310 }
5311}
5312
Douglas Gregor436424c2008-11-18 23:14:02 +00005313/// AddMethodCandidate - Adds the given C++ member function to the set
5314/// of candidate functions, using the given function call arguments
5315/// and the object argument (@c Object). For example, in a call
5316/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5317/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5318/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005319/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005320void
John McCalla0296f72010-03-19 07:35:19 +00005321Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005322 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005323 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005324 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005325 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005326 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005327 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005328 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005329 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005330 assert(!isa<CXXConstructorDecl>(Method) &&
5331 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005332
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005333 if (!CandidateSet.isNewCandidate(Method))
5334 return;
5335
Douglas Gregor27381f32009-11-23 12:27:39 +00005336 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005337 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005338
Douglas Gregor436424c2008-11-18 23:14:02 +00005339 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005340 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005341 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005342 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005343 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005344 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005345 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005346
5347 unsigned NumArgsInProto = Proto->getNumArgs();
5348
5349 // (C++ 13.3.2p2): A candidate function having fewer than m
5350 // parameters is viable only if it has an ellipsis in its parameter
5351 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005352 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005353 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005354 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005355 return;
5356 }
5357
5358 // (C++ 13.3.2p2): A candidate function having more than m parameters
5359 // is viable only if the (m+1)st parameter has a default argument
5360 // (8.3.6). For the purposes of overload resolution, the
5361 // parameter list is truncated on the right, so that there are
5362 // exactly m parameters.
5363 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005364 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005365 // Not enough arguments.
5366 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005367 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005368 return;
5369 }
5370
5371 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005372
John McCall6e9f8f62009-12-03 04:06:58 +00005373 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005374 // The implicit object argument is ignored.
5375 Candidate.IgnoreObjectArgument = true;
5376 else {
5377 // Determine the implicit conversion sequence for the object
5378 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005379 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005380 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5381 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005382 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005383 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005384 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005385 return;
5386 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005387 }
5388
5389 // Determine the implicit conversion sequences for each of the
5390 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005391 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005392 if (ArgIdx < NumArgsInProto) {
5393 // (C++ 13.3.2p3): for F to be a viable function, there shall
5394 // exist for each argument an implicit conversion sequence
5395 // (13.3.3.1) that converts that argument to the corresponding
5396 // parameter of F.
5397 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005398 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005399 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005400 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005401 /*InOverloadResolution=*/true,
5402 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005403 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005404 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005405 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005406 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005407 break;
5408 }
5409 } else {
5410 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5411 // argument for which there is no corresponding parameter is
5412 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005413 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005414 }
5415 }
5416}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417
Douglas Gregor97628d62009-08-21 00:16:32 +00005418/// \brief Add a C++ member function template as a candidate to the candidate
5419/// set, using template argument deduction to produce an appropriate member
5420/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005421void
Douglas Gregor97628d62009-08-21 00:16:32 +00005422Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005423 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005424 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005425 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005426 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005427 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005428 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005429 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005430 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005431 if (!CandidateSet.isNewCandidate(MethodTmpl))
5432 return;
5433
Douglas Gregor97628d62009-08-21 00:16:32 +00005434 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005435 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005436 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005437 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005438 // candidate functions in the usual way.113) A given name can refer to one
5439 // or more function templates and also to a set of overloaded non-template
5440 // functions. In such a case, the candidate functions generated from each
5441 // function template are combined with the set of non-template candidate
5442 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005443 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005444 FunctionDecl *Specialization = 0;
5445 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005446 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5447 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005448 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005449 Candidate.FoundDecl = FoundDecl;
5450 Candidate.Function = MethodTmpl->getTemplatedDecl();
5451 Candidate.Viable = false;
5452 Candidate.FailureKind = ovl_fail_bad_deduction;
5453 Candidate.IsSurrogate = false;
5454 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005455 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005457 Info);
5458 return;
5459 }
Mike Stump11289f42009-09-09 15:08:12 +00005460
Douglas Gregor97628d62009-08-21 00:16:32 +00005461 // Add the function template specialization produced by template argument
5462 // deduction as a candidate.
5463 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005464 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005465 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005466 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005467 ActingContext, ObjectType, ObjectClassification, Args,
5468 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005469}
5470
Douglas Gregor05155d82009-08-21 23:19:43 +00005471/// \brief Add a C++ function template specialization as a candidate
5472/// in the candidate set, using template argument deduction to produce
5473/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005474void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005475Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005476 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005477 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005478 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005479 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005480 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005481 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5482 return;
5483
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005484 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005485 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005486 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005487 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005488 // candidate functions in the usual way.113) A given name can refer to one
5489 // or more function templates and also to a set of overloaded non-template
5490 // functions. In such a case, the candidate functions generated from each
5491 // function template are combined with the set of non-template candidate
5492 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005493 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005494 FunctionDecl *Specialization = 0;
5495 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005496 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5497 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005498 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005499 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005500 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5501 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005502 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005503 Candidate.IsSurrogate = false;
5504 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005505 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005506 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005507 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005508 return;
5509 }
Mike Stump11289f42009-09-09 15:08:12 +00005510
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005511 // Add the function template specialization produced by template argument
5512 // deduction as a candidate.
5513 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005514 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005515 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005516}
Mike Stump11289f42009-09-09 15:08:12 +00005517
Douglas Gregora1f013e2008-11-07 22:36:19 +00005518/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005519/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005520/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005521/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005522/// (which may or may not be the same type as the type that the
5523/// conversion function produces).
5524void
5525Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005526 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005527 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005528 Expr *From, QualType ToType,
5529 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005530 assert(!Conversion->getDescribedFunctionTemplate() &&
5531 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005532 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005533 if (!CandidateSet.isNewCandidate(Conversion))
5534 return;
5535
Douglas Gregor27381f32009-11-23 12:27:39 +00005536 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005537 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005538
Douglas Gregora1f013e2008-11-07 22:36:19 +00005539 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005540 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005541 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005542 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005543 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005544 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005545 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005546 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005547 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005548 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005549 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005550
Douglas Gregor6affc782010-08-19 15:37:02 +00005551 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552 // For conversion functions, the function is considered to be a member of
5553 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005554 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005555 //
5556 // Determine the implicit conversion sequence for the implicit
5557 // object parameter.
5558 QualType ImplicitParamType = From->getType();
5559 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5560 ImplicitParamType = FromPtrType->getPointeeType();
5561 CXXRecordDecl *ConversionContext
5562 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005564 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005565 = TryObjectArgumentInitialization(*this, From->getType(),
5566 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005567 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005568
John McCall0d1da222010-01-12 00:44:57 +00005569 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005570 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005571 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005572 return;
5573 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005576 // derived to base as such conversions are given Conversion Rank. They only
5577 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5578 QualType FromCanon
5579 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5580 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5581 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5582 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005583 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005584 return;
5585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005586
Douglas Gregora1f013e2008-11-07 22:36:19 +00005587 // To determine what the conversion from the result of calling the
5588 // conversion function to the type we're eventually trying to
5589 // convert to (ToType), we need to synthesize a call to the
5590 // conversion function and attempt copy initialization from it. This
5591 // makes sure that we get the right semantics with respect to
5592 // lvalues/rvalues and the type. Fortunately, we can allocate this
5593 // call on the stack and we don't need its arguments to be
5594 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005595 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005596 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005597 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5598 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005599 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005600 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005601
Richard Smith48d24642011-07-13 22:53:21 +00005602 QualType ConversionType = Conversion->getConversionType();
5603 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005604 Candidate.Viable = false;
5605 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5606 return;
5607 }
5608
Richard Smith48d24642011-07-13 22:53:21 +00005609 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005610
Mike Stump11289f42009-09-09 15:08:12 +00005611 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005612 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5613 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005614 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005615 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005616 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005617 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005618 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005619 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005620 /*InOverloadResolution=*/false,
5621 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall0d1da222010-01-12 00:44:57 +00005623 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005624 case ImplicitConversionSequence::StandardConversion:
5625 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005627 // C++ [over.ics.user]p3:
5628 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005630 // shall have exact match rank.
5631 if (Conversion->getPrimaryTemplate() &&
5632 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5633 Candidate.Viable = false;
5634 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636
Douglas Gregorcba72b12011-01-21 05:18:22 +00005637 // C++0x [dcl.init.ref]p5:
5638 // In the second case, if the reference is an rvalue reference and
5639 // the second standard conversion sequence of the user-defined
5640 // conversion sequence includes an lvalue-to-rvalue conversion, the
5641 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005643 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5646 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005647 break;
5648
5649 case ImplicitConversionSequence::BadConversion:
5650 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005651 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005652 break;
5653
5654 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005655 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005656 "Can only end up with a standard conversion sequence or failure");
5657 }
5658}
5659
Douglas Gregor05155d82009-08-21 23:19:43 +00005660/// \brief Adds a conversion function template specialization
5661/// candidate to the overload set, using template argument deduction
5662/// to deduce the template arguments of the conversion function
5663/// template from the type that we are converting to (C++
5664/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005665void
Douglas Gregor05155d82009-08-21 23:19:43 +00005666Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005667 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005668 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005669 Expr *From, QualType ToType,
5670 OverloadCandidateSet &CandidateSet) {
5671 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5672 "Only conversion function templates permitted here");
5673
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005674 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5675 return;
5676
John McCallbc077cf2010-02-08 23:07:23 +00005677 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005678 CXXConversionDecl *Specialization = 0;
5679 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005680 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005681 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005682 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005683 Candidate.FoundDecl = FoundDecl;
5684 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5685 Candidate.Viable = false;
5686 Candidate.FailureKind = ovl_fail_bad_deduction;
5687 Candidate.IsSurrogate = false;
5688 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005689 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005690 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005691 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005692 return;
5693 }
Mike Stump11289f42009-09-09 15:08:12 +00005694
Douglas Gregor05155d82009-08-21 23:19:43 +00005695 // Add the conversion function template specialization produced by
5696 // template argument deduction as a candidate.
5697 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005698 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005699 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005700}
5701
Douglas Gregorab7897a2008-11-19 22:57:39 +00005702/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5703/// converts the given @c Object to a function pointer via the
5704/// conversion function @c Conversion, and then attempts to call it
5705/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5706/// the type of function that we'll eventually be calling.
5707void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005708 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005709 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005710 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005711 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005712 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005713 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005714 if (!CandidateSet.isNewCandidate(Conversion))
5715 return;
5716
Douglas Gregor27381f32009-11-23 12:27:39 +00005717 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005718 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005719
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005720 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005721 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005722 Candidate.Function = 0;
5723 Candidate.Surrogate = Conversion;
5724 Candidate.Viable = true;
5725 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005726 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005727 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005728
5729 // Determine the implicit conversion sequence for the implicit
5730 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005731 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005733 Object->Classify(Context),
5734 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005735 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005736 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005737 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005738 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005739 return;
5740 }
5741
5742 // The first conversion is actually a user-defined conversion whose
5743 // first conversion is ObjectInit's standard conversion (which is
5744 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005745 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005746 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005747 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005748 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005749 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005750 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005751 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005752 = Candidate.Conversions[0].UserDefined.Before;
5753 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5754
Mike Stump11289f42009-09-09 15:08:12 +00005755 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005756 unsigned NumArgsInProto = Proto->getNumArgs();
5757
5758 // (C++ 13.3.2p2): A candidate function having fewer than m
5759 // parameters is viable only if it has an ellipsis in its parameter
5760 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005761 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005762 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005763 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005764 return;
5765 }
5766
5767 // Function types don't have any default arguments, so just check if
5768 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005769 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005770 // Not enough arguments.
5771 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005772 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005773 return;
5774 }
5775
5776 // Determine the implicit conversion sequences for each of the
5777 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005778 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005779 if (ArgIdx < NumArgsInProto) {
5780 // (C++ 13.3.2p3): for F to be a viable function, there shall
5781 // exist for each argument an implicit conversion sequence
5782 // (13.3.3.1) that converts that argument to the corresponding
5783 // parameter of F.
5784 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005785 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005786 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005787 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005788 /*InOverloadResolution=*/false,
5789 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005790 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005791 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005792 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005793 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005794 break;
5795 }
5796 } else {
5797 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5798 // argument for which there is no corresponding parameter is
5799 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005800 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005801 }
5802 }
5803}
5804
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005805/// \brief Add overload candidates for overloaded operators that are
5806/// member functions.
5807///
5808/// Add the overloaded operator candidates that are member functions
5809/// for the operator Op that was used in an operator expression such
5810/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5811/// CandidateSet will store the added overload candidates. (C++
5812/// [over.match.oper]).
5813void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5814 SourceLocation OpLoc,
5815 Expr **Args, unsigned NumArgs,
5816 OverloadCandidateSet& CandidateSet,
5817 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005818 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5819
5820 // C++ [over.match.oper]p3:
5821 // For a unary operator @ with an operand of a type whose
5822 // cv-unqualified version is T1, and for a binary operator @ with
5823 // a left operand of a type whose cv-unqualified version is T1 and
5824 // a right operand of a type whose cv-unqualified version is T2,
5825 // three sets of candidate functions, designated member
5826 // candidates, non-member candidates and built-in candidates, are
5827 // constructed as follows:
5828 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005829
5830 // -- If T1 is a class type, the set of member candidates is the
5831 // result of the qualified lookup of T1::operator@
5832 // (13.3.1.1.1); otherwise, the set of member candidates is
5833 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005834 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005835 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005836 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005837 return;
Mike Stump11289f42009-09-09 15:08:12 +00005838
John McCall27b18f82009-11-17 02:14:36 +00005839 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5840 LookupQualifiedName(Operators, T1Rec->getDecl());
5841 Operators.suppressDiagnostics();
5842
Mike Stump11289f42009-09-09 15:08:12 +00005843 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005844 OperEnd = Operators.end();
5845 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005846 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005847 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005849 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005850 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005851 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005852}
5853
Douglas Gregora11693b2008-11-12 17:17:38 +00005854/// AddBuiltinCandidate - Add a candidate for a built-in
5855/// operator. ResultTy and ParamTys are the result and parameter types
5856/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005857/// arguments being passed to the candidate. IsAssignmentOperator
5858/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005859/// operator. NumContextualBoolArguments is the number of arguments
5860/// (at the beginning of the argument list) that will be contextually
5861/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005862void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005863 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005864 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005865 bool IsAssignmentOperator,
5866 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005867 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005868 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005869
Douglas Gregora11693b2008-11-12 17:17:38 +00005870 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005871 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005872 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005873 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005874 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005875 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005876 Candidate.BuiltinTypes.ResultTy = ResultTy;
5877 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5878 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5879
5880 // Determine the implicit conversion sequences for each of the
5881 // arguments.
5882 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005883 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005884 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005885 // C++ [over.match.oper]p4:
5886 // For the built-in assignment operators, conversions of the
5887 // left operand are restricted as follows:
5888 // -- no temporaries are introduced to hold the left operand, and
5889 // -- no user-defined conversions are applied to the left
5890 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005891 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005892 //
5893 // We block these conversions by turning off user-defined
5894 // conversions, since that is the only way that initialization of
5895 // a reference to a non-class type can occur from something that
5896 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005897 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005898 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005899 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005900 Candidate.Conversions[ArgIdx]
5901 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005902 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005903 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005904 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005905 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005906 /*InOverloadResolution=*/false,
5907 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005908 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005909 }
John McCall0d1da222010-01-12 00:44:57 +00005910 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005911 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005912 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005913 break;
5914 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005915 }
5916}
5917
5918/// BuiltinCandidateTypeSet - A set of types that will be used for the
5919/// candidate operator functions for built-in operators (C++
5920/// [over.built]). The types are separated into pointer types and
5921/// enumeration types.
5922class BuiltinCandidateTypeSet {
5923 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005924 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005925
5926 /// PointerTypes - The set of pointer types that will be used in the
5927 /// built-in candidates.
5928 TypeSet PointerTypes;
5929
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005930 /// MemberPointerTypes - The set of member pointer types that will be
5931 /// used in the built-in candidates.
5932 TypeSet MemberPointerTypes;
5933
Douglas Gregora11693b2008-11-12 17:17:38 +00005934 /// EnumerationTypes - The set of enumeration types that will be
5935 /// used in the built-in candidates.
5936 TypeSet EnumerationTypes;
5937
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005938 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005939 /// candidates.
5940 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005941
5942 /// \brief A flag indicating non-record types are viable candidates
5943 bool HasNonRecordTypes;
5944
5945 /// \brief A flag indicating whether either arithmetic or enumeration types
5946 /// were present in the candidate set.
5947 bool HasArithmeticOrEnumeralTypes;
5948
Douglas Gregor80af3132011-05-21 23:15:46 +00005949 /// \brief A flag indicating whether the nullptr type was present in the
5950 /// candidate set.
5951 bool HasNullPtrType;
5952
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005953 /// Sema - The semantic analysis instance where we are building the
5954 /// candidate type set.
5955 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005956
Douglas Gregora11693b2008-11-12 17:17:38 +00005957 /// Context - The AST context in which we will build the type sets.
5958 ASTContext &Context;
5959
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005960 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5961 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005962 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005963
5964public:
5965 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005966 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005967
Mike Stump11289f42009-09-09 15:08:12 +00005968 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005969 : HasNonRecordTypes(false),
5970 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005971 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005972 SemaRef(SemaRef),
5973 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005974
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005975 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005976 SourceLocation Loc,
5977 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005978 bool AllowExplicitConversions,
5979 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005980
5981 /// pointer_begin - First pointer type found;
5982 iterator pointer_begin() { return PointerTypes.begin(); }
5983
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005984 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005985 iterator pointer_end() { return PointerTypes.end(); }
5986
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005987 /// member_pointer_begin - First member pointer type found;
5988 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5989
5990 /// member_pointer_end - Past the last member pointer type found;
5991 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5992
Douglas Gregora11693b2008-11-12 17:17:38 +00005993 /// enumeration_begin - First enumeration type found;
5994 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5995
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005996 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005997 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005998
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005999 iterator vector_begin() { return VectorTypes.begin(); }
6000 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006001
6002 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6003 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006004 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006005};
6006
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006007/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006008/// the set of pointer types along with any more-qualified variants of
6009/// that type. For example, if @p Ty is "int const *", this routine
6010/// will add "int const *", "int const volatile *", "int const
6011/// restrict *", and "int const volatile restrict *" to the set of
6012/// pointer types. Returns true if the add of @p Ty itself succeeded,
6013/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006014///
6015/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006016bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006017BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6018 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006019
Douglas Gregora11693b2008-11-12 17:17:38 +00006020 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006021 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006022 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006023
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006024 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006025 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006026 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006027 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006028 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006029 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006030 buildObjCPtr = true;
6031 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006032 else
David Blaikie83d382b2011-09-23 05:06:16 +00006033 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006034 }
6035 else
6036 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037
Sebastian Redl4990a632009-11-18 20:39:26 +00006038 // Don't add qualified variants of arrays. For one, they're not allowed
6039 // (the qualifier would sink to the element type), and for another, the
6040 // only overload situation where it matters is subscript or pointer +- int,
6041 // and those shouldn't have qualifier variants anyway.
6042 if (PointeeTy->isArrayType())
6043 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006044 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006045 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006046 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006047 bool hasVolatile = VisibleQuals.hasVolatile();
6048 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006049
John McCall8ccfcb52009-09-24 19:53:00 +00006050 // Iterate through all strict supersets of BaseCVR.
6051 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6052 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006053 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6054 // in the types.
6055 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6056 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006057 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006058 if (!buildObjCPtr)
6059 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6060 else
6061 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006062 }
6063
6064 return true;
6065}
6066
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006067/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6068/// to the set of pointer types along with any more-qualified variants of
6069/// that type. For example, if @p Ty is "int const *", this routine
6070/// will add "int const *", "int const volatile *", "int const
6071/// restrict *", and "int const volatile restrict *" to the set of
6072/// pointer types. Returns true if the add of @p Ty itself succeeded,
6073/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006074///
6075/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006076bool
6077BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6078 QualType Ty) {
6079 // Insert this type.
6080 if (!MemberPointerTypes.insert(Ty))
6081 return false;
6082
John McCall8ccfcb52009-09-24 19:53:00 +00006083 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6084 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006085
John McCall8ccfcb52009-09-24 19:53:00 +00006086 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006087 // Don't add qualified variants of arrays. For one, they're not allowed
6088 // (the qualifier would sink to the element type), and for another, the
6089 // only overload situation where it matters is subscript or pointer +- int,
6090 // and those shouldn't have qualifier variants anyway.
6091 if (PointeeTy->isArrayType())
6092 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006093 const Type *ClassTy = PointerTy->getClass();
6094
6095 // Iterate through all strict supersets of the pointee type's CVR
6096 // qualifiers.
6097 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6098 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6099 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
John McCall8ccfcb52009-09-24 19:53:00 +00006101 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006102 MemberPointerTypes.insert(
6103 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006104 }
6105
6106 return true;
6107}
6108
Douglas Gregora11693b2008-11-12 17:17:38 +00006109/// AddTypesConvertedFrom - Add each of the types to which the type @p
6110/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006111/// primarily interested in pointer types and enumeration types. We also
6112/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006113/// AllowUserConversions is true if we should look at the conversion
6114/// functions of a class type, and AllowExplicitConversions if we
6115/// should also include the explicit conversion functions of a class
6116/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006117void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006118BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006119 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006120 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006121 bool AllowExplicitConversions,
6122 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006123 // Only deal with canonical types.
6124 Ty = Context.getCanonicalType(Ty);
6125
6126 // Look through reference types; they aren't part of the type of an
6127 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006128 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006129 Ty = RefTy->getPointeeType();
6130
John McCall33ddac02011-01-19 10:06:00 +00006131 // If we're dealing with an array type, decay to the pointer.
6132 if (Ty->isArrayType())
6133 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6134
6135 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006136 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006137
Chandler Carruth00a38332010-12-13 01:44:01 +00006138 // Flag if we ever add a non-record type.
6139 const RecordType *TyRec = Ty->getAs<RecordType>();
6140 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6141
Chandler Carruth00a38332010-12-13 01:44:01 +00006142 // Flag if we encounter an arithmetic type.
6143 HasArithmeticOrEnumeralTypes =
6144 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6145
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006146 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6147 PointerTypes.insert(Ty);
6148 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006149 // Insert our type, and its more-qualified variants, into the set
6150 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006151 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006152 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006153 } else if (Ty->isMemberPointerType()) {
6154 // Member pointers are far easier, since the pointee can't be converted.
6155 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6156 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006157 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006158 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006159 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006160 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006161 // We treat vector types as arithmetic types in many contexts as an
6162 // extension.
6163 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006164 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006165 } else if (Ty->isNullPtrType()) {
6166 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006167 } else if (AllowUserConversions && TyRec) {
6168 // No conversion functions in incomplete types.
6169 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6170 return;
Mike Stump11289f42009-09-09 15:08:12 +00006171
Chandler Carruth00a38332010-12-13 01:44:01 +00006172 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6173 const UnresolvedSetImpl *Conversions
6174 = ClassDecl->getVisibleConversionFunctions();
6175 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6176 E = Conversions->end(); I != E; ++I) {
6177 NamedDecl *D = I.getDecl();
6178 if (isa<UsingShadowDecl>(D))
6179 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006180
Chandler Carruth00a38332010-12-13 01:44:01 +00006181 // Skip conversion function templates; they don't tell us anything
6182 // about which builtin types we can convert to.
6183 if (isa<FunctionTemplateDecl>(D))
6184 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006185
Chandler Carruth00a38332010-12-13 01:44:01 +00006186 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6187 if (AllowExplicitConversions || !Conv->isExplicit()) {
6188 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6189 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006190 }
6191 }
6192 }
6193}
6194
Douglas Gregor84605ae2009-08-24 13:43:27 +00006195/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6196/// the volatile- and non-volatile-qualified assignment operators for the
6197/// given type to the candidate set.
6198static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6199 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006200 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006201 unsigned NumArgs,
6202 OverloadCandidateSet &CandidateSet) {
6203 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006204
Douglas Gregor84605ae2009-08-24 13:43:27 +00006205 // T& operator=(T&, T)
6206 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6207 ParamTypes[1] = T;
6208 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6209 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006210
Douglas Gregor84605ae2009-08-24 13:43:27 +00006211 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6212 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006213 ParamTypes[0]
6214 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006215 ParamTypes[1] = T;
6216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006217 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006218 }
6219}
Mike Stump11289f42009-09-09 15:08:12 +00006220
Sebastian Redl1054fae2009-10-25 17:03:50 +00006221/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6222/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006223static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6224 Qualifiers VRQuals;
6225 const RecordType *TyRec;
6226 if (const MemberPointerType *RHSMPType =
6227 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006228 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006229 else
6230 TyRec = ArgExpr->getType()->getAs<RecordType>();
6231 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006232 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006233 VRQuals.addVolatile();
6234 VRQuals.addRestrict();
6235 return VRQuals;
6236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006238 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006239 if (!ClassDecl->hasDefinition())
6240 return VRQuals;
6241
John McCallad371252010-01-20 00:46:10 +00006242 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006243 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006244
John McCallad371252010-01-20 00:46:10 +00006245 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006246 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006247 NamedDecl *D = I.getDecl();
6248 if (isa<UsingShadowDecl>(D))
6249 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6250 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006251 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6252 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6253 CanTy = ResTypeRef->getPointeeType();
6254 // Need to go down the pointer/mempointer chain and add qualifiers
6255 // as see them.
6256 bool done = false;
6257 while (!done) {
6258 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6259 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006260 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006261 CanTy->getAs<MemberPointerType>())
6262 CanTy = ResTypeMPtr->getPointeeType();
6263 else
6264 done = true;
6265 if (CanTy.isVolatileQualified())
6266 VRQuals.addVolatile();
6267 if (CanTy.isRestrictQualified())
6268 VRQuals.addRestrict();
6269 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6270 return VRQuals;
6271 }
6272 }
6273 }
6274 return VRQuals;
6275}
John McCall52872982010-11-13 05:51:15 +00006276
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006277namespace {
John McCall52872982010-11-13 05:51:15 +00006278
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006279/// \brief Helper class to manage the addition of builtin operator overload
6280/// candidates. It provides shared state and utility methods used throughout
6281/// the process, as well as a helper method to add each group of builtin
6282/// operator overloads from the standard to a candidate set.
6283class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006284 // Common instance state available to all overload candidate addition methods.
6285 Sema &S;
6286 Expr **Args;
6287 unsigned NumArgs;
6288 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006289 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006290 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006291 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006292
Chandler Carruthc6586e52010-12-12 10:35:00 +00006293 // Define some constants used to index and iterate over the arithemetic types
6294 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006295 // The "promoted arithmetic types" are the arithmetic
6296 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006297 static const unsigned FirstIntegralType = 3;
6298 static const unsigned LastIntegralType = 18;
6299 static const unsigned FirstPromotedIntegralType = 3,
6300 LastPromotedIntegralType = 9;
6301 static const unsigned FirstPromotedArithmeticType = 0,
6302 LastPromotedArithmeticType = 9;
6303 static const unsigned NumArithmeticTypes = 18;
6304
Chandler Carruthc6586e52010-12-12 10:35:00 +00006305 /// \brief Get the canonical type for a given arithmetic type index.
6306 CanQualType getArithmeticType(unsigned index) {
6307 assert(index < NumArithmeticTypes);
6308 static CanQualType ASTContext::* const
6309 ArithmeticTypes[NumArithmeticTypes] = {
6310 // Start of promoted types.
6311 &ASTContext::FloatTy,
6312 &ASTContext::DoubleTy,
6313 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006314
Chandler Carruthc6586e52010-12-12 10:35:00 +00006315 // Start of integral types.
6316 &ASTContext::IntTy,
6317 &ASTContext::LongTy,
6318 &ASTContext::LongLongTy,
6319 &ASTContext::UnsignedIntTy,
6320 &ASTContext::UnsignedLongTy,
6321 &ASTContext::UnsignedLongLongTy,
6322 // End of promoted types.
6323
6324 &ASTContext::BoolTy,
6325 &ASTContext::CharTy,
6326 &ASTContext::WCharTy,
6327 &ASTContext::Char16Ty,
6328 &ASTContext::Char32Ty,
6329 &ASTContext::SignedCharTy,
6330 &ASTContext::ShortTy,
6331 &ASTContext::UnsignedCharTy,
6332 &ASTContext::UnsignedShortTy,
6333 // End of integral types.
6334 // FIXME: What about complex?
6335 };
6336 return S.Context.*ArithmeticTypes[index];
6337 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006338
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006339 /// \brief Gets the canonical type resulting from the usual arithemetic
6340 /// converions for the given arithmetic types.
6341 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6342 // Accelerator table for performing the usual arithmetic conversions.
6343 // The rules are basically:
6344 // - if either is floating-point, use the wider floating-point
6345 // - if same signedness, use the higher rank
6346 // - if same size, use unsigned of the higher rank
6347 // - use the larger type
6348 // These rules, together with the axiom that higher ranks are
6349 // never smaller, are sufficient to precompute all of these results
6350 // *except* when dealing with signed types of higher rank.
6351 // (we could precompute SLL x UI for all known platforms, but it's
6352 // better not to make any assumptions).
6353 enum PromotedType {
6354 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6355 };
6356 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6357 [LastPromotedArithmeticType] = {
6358 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6359 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6360 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6361 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6362 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6363 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6364 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6365 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6366 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6367 };
6368
6369 assert(L < LastPromotedArithmeticType);
6370 assert(R < LastPromotedArithmeticType);
6371 int Idx = ConversionsTable[L][R];
6372
6373 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006374 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006375
6376 // Slow path: we need to compare widths.
6377 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006378 CanQualType LT = getArithmeticType(L),
6379 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006380 unsigned LW = S.Context.getIntWidth(LT),
6381 RW = S.Context.getIntWidth(RT);
6382
6383 // If they're different widths, use the signed type.
6384 if (LW > RW) return LT;
6385 else if (LW < RW) return RT;
6386
6387 // Otherwise, use the unsigned type of the signed type's rank.
6388 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6389 assert(L == SLL || R == SLL);
6390 return S.Context.UnsignedLongLongTy;
6391 }
6392
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006393 /// \brief Helper method to factor out the common pattern of adding overloads
6394 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006395 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6396 bool HasVolatile) {
6397 QualType ParamTypes[2] = {
6398 S.Context.getLValueReferenceType(CandidateTy),
6399 S.Context.IntTy
6400 };
6401
6402 // Non-volatile version.
6403 if (NumArgs == 1)
6404 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6405 else
6406 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6407
6408 // Use a heuristic to reduce number of builtin candidates in the set:
6409 // add volatile version only if there are conversions to a volatile type.
6410 if (HasVolatile) {
6411 ParamTypes[0] =
6412 S.Context.getLValueReferenceType(
6413 S.Context.getVolatileType(CandidateTy));
6414 if (NumArgs == 1)
6415 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6416 else
6417 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6418 }
6419 }
6420
6421public:
6422 BuiltinOperatorOverloadBuilder(
6423 Sema &S, Expr **Args, unsigned NumArgs,
6424 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006425 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006426 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006427 OverloadCandidateSet &CandidateSet)
6428 : S(S), Args(Args), NumArgs(NumArgs),
6429 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006430 HasArithmeticOrEnumeralCandidateType(
6431 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006432 CandidateTypes(CandidateTypes),
6433 CandidateSet(CandidateSet) {
6434 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006435 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006436 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006437 assert(getArithmeticType(LastPromotedIntegralType - 1)
6438 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006439 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006440 assert(getArithmeticType(FirstPromotedArithmeticType)
6441 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006442 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006443 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6444 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006445 "Invalid last promoted arithmetic type");
6446 }
6447
6448 // C++ [over.built]p3:
6449 //
6450 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6451 // is either volatile or empty, there exist candidate operator
6452 // functions of the form
6453 //
6454 // VQ T& operator++(VQ T&);
6455 // T operator++(VQ T&, int);
6456 //
6457 // C++ [over.built]p4:
6458 //
6459 // For every pair (T, VQ), where T is an arithmetic type other
6460 // than bool, and VQ is either volatile or empty, there exist
6461 // candidate operator functions of the form
6462 //
6463 // VQ T& operator--(VQ T&);
6464 // T operator--(VQ T&, int);
6465 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006466 if (!HasArithmeticOrEnumeralCandidateType)
6467 return;
6468
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006469 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6470 Arith < NumArithmeticTypes; ++Arith) {
6471 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006472 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006473 VisibleTypeConversionsQuals.hasVolatile());
6474 }
6475 }
6476
6477 // C++ [over.built]p5:
6478 //
6479 // For every pair (T, VQ), where T is a cv-qualified or
6480 // cv-unqualified object type, and VQ is either volatile or
6481 // empty, there exist candidate operator functions of the form
6482 //
6483 // T*VQ& operator++(T*VQ&);
6484 // T*VQ& operator--(T*VQ&);
6485 // T* operator++(T*VQ&, int);
6486 // T* operator--(T*VQ&, int);
6487 void addPlusPlusMinusMinusPointerOverloads() {
6488 for (BuiltinCandidateTypeSet::iterator
6489 Ptr = CandidateTypes[0].pointer_begin(),
6490 PtrEnd = CandidateTypes[0].pointer_end();
6491 Ptr != PtrEnd; ++Ptr) {
6492 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006493 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006494 continue;
6495
6496 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6497 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6498 VisibleTypeConversionsQuals.hasVolatile()));
6499 }
6500 }
6501
6502 // C++ [over.built]p6:
6503 // For every cv-qualified or cv-unqualified object type T, there
6504 // exist candidate operator functions of the form
6505 //
6506 // T& operator*(T*);
6507 //
6508 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006510 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006511 // T& operator*(T*);
6512 void addUnaryStarPointerOverloads() {
6513 for (BuiltinCandidateTypeSet::iterator
6514 Ptr = CandidateTypes[0].pointer_begin(),
6515 PtrEnd = CandidateTypes[0].pointer_end();
6516 Ptr != PtrEnd; ++Ptr) {
6517 QualType ParamTy = *Ptr;
6518 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006519 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6520 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521
Douglas Gregor02824322011-01-26 19:30:28 +00006522 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6523 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6524 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006525
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006526 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6527 &ParamTy, Args, 1, CandidateSet);
6528 }
6529 }
6530
6531 // C++ [over.built]p9:
6532 // For every promoted arithmetic type T, there exist candidate
6533 // operator functions of the form
6534 //
6535 // T operator+(T);
6536 // T operator-(T);
6537 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006538 if (!HasArithmeticOrEnumeralCandidateType)
6539 return;
6540
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006541 for (unsigned Arith = FirstPromotedArithmeticType;
6542 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006543 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006544 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6545 }
6546
6547 // Extension: We also add these operators for vector types.
6548 for (BuiltinCandidateTypeSet::iterator
6549 Vec = CandidateTypes[0].vector_begin(),
6550 VecEnd = CandidateTypes[0].vector_end();
6551 Vec != VecEnd; ++Vec) {
6552 QualType VecTy = *Vec;
6553 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6554 }
6555 }
6556
6557 // C++ [over.built]p8:
6558 // For every type T, there exist candidate operator functions of
6559 // the form
6560 //
6561 // T* operator+(T*);
6562 void addUnaryPlusPointerOverloads() {
6563 for (BuiltinCandidateTypeSet::iterator
6564 Ptr = CandidateTypes[0].pointer_begin(),
6565 PtrEnd = CandidateTypes[0].pointer_end();
6566 Ptr != PtrEnd; ++Ptr) {
6567 QualType ParamTy = *Ptr;
6568 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6569 }
6570 }
6571
6572 // C++ [over.built]p10:
6573 // For every promoted integral type T, there exist candidate
6574 // operator functions of the form
6575 //
6576 // T operator~(T);
6577 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006578 if (!HasArithmeticOrEnumeralCandidateType)
6579 return;
6580
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006581 for (unsigned Int = FirstPromotedIntegralType;
6582 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006583 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006584 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6585 }
6586
6587 // Extension: We also add this operator for vector types.
6588 for (BuiltinCandidateTypeSet::iterator
6589 Vec = CandidateTypes[0].vector_begin(),
6590 VecEnd = CandidateTypes[0].vector_end();
6591 Vec != VecEnd; ++Vec) {
6592 QualType VecTy = *Vec;
6593 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6594 }
6595 }
6596
6597 // C++ [over.match.oper]p16:
6598 // For every pointer to member type T, there exist candidate operator
6599 // functions of the form
6600 //
6601 // bool operator==(T,T);
6602 // bool operator!=(T,T);
6603 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6604 /// Set of (canonical) types that we've already handled.
6605 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6606
6607 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6608 for (BuiltinCandidateTypeSet::iterator
6609 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6610 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6611 MemPtr != MemPtrEnd;
6612 ++MemPtr) {
6613 // Don't add the same builtin candidate twice.
6614 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6615 continue;
6616
6617 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6618 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6619 CandidateSet);
6620 }
6621 }
6622 }
6623
6624 // C++ [over.built]p15:
6625 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006626 // For every T, where T is an enumeration type, a pointer type, or
6627 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006628 //
6629 // bool operator<(T, T);
6630 // bool operator>(T, T);
6631 // bool operator<=(T, T);
6632 // bool operator>=(T, T);
6633 // bool operator==(T, T);
6634 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006635 void addRelationalPointerOrEnumeralOverloads() {
6636 // C++ [over.built]p1:
6637 // If there is a user-written candidate with the same name and parameter
6638 // types as a built-in candidate operator function, the built-in operator
6639 // function is hidden and is not included in the set of candidate
6640 // functions.
6641 //
6642 // The text is actually in a note, but if we don't implement it then we end
6643 // up with ambiguities when the user provides an overloaded operator for
6644 // an enumeration type. Note that only enumeration types have this problem,
6645 // so we track which enumeration types we've seen operators for. Also, the
6646 // only other overloaded operator with enumeration argumenst, operator=,
6647 // cannot be overloaded for enumeration types, so this is the only place
6648 // where we must suppress candidates like this.
6649 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6650 UserDefinedBinaryOperators;
6651
6652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6653 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6654 CandidateTypes[ArgIdx].enumeration_end()) {
6655 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6656 CEnd = CandidateSet.end();
6657 C != CEnd; ++C) {
6658 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6659 continue;
6660
6661 QualType FirstParamType =
6662 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6663 QualType SecondParamType =
6664 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6665
6666 // Skip if either parameter isn't of enumeral type.
6667 if (!FirstParamType->isEnumeralType() ||
6668 !SecondParamType->isEnumeralType())
6669 continue;
6670
6671 // Add this operator to the set of known user-defined operators.
6672 UserDefinedBinaryOperators.insert(
6673 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6674 S.Context.getCanonicalType(SecondParamType)));
6675 }
6676 }
6677 }
6678
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006679 /// Set of (canonical) types that we've already handled.
6680 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6681
6682 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6683 for (BuiltinCandidateTypeSet::iterator
6684 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6685 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6686 Ptr != PtrEnd; ++Ptr) {
6687 // Don't add the same builtin candidate twice.
6688 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6689 continue;
6690
6691 QualType ParamTypes[2] = { *Ptr, *Ptr };
6692 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6693 CandidateSet);
6694 }
6695 for (BuiltinCandidateTypeSet::iterator
6696 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6697 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6698 Enum != EnumEnd; ++Enum) {
6699 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6700
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006701 // Don't add the same builtin candidate twice, or if a user defined
6702 // candidate exists.
6703 if (!AddedTypes.insert(CanonType) ||
6704 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6705 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006706 continue;
6707
6708 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006709 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6710 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006711 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006712
6713 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6714 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6715 if (AddedTypes.insert(NullPtrTy) &&
6716 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6717 NullPtrTy))) {
6718 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6719 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6720 CandidateSet);
6721 }
6722 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006723 }
6724 }
6725
6726 // C++ [over.built]p13:
6727 //
6728 // For every cv-qualified or cv-unqualified object type T
6729 // there exist candidate operator functions of the form
6730 //
6731 // T* operator+(T*, ptrdiff_t);
6732 // T& operator[](T*, ptrdiff_t); [BELOW]
6733 // T* operator-(T*, ptrdiff_t);
6734 // T* operator+(ptrdiff_t, T*);
6735 // T& operator[](ptrdiff_t, T*); [BELOW]
6736 //
6737 // C++ [over.built]p14:
6738 //
6739 // For every T, where T is a pointer to object type, there
6740 // exist candidate operator functions of the form
6741 //
6742 // ptrdiff_t operator-(T, T);
6743 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6744 /// Set of (canonical) types that we've already handled.
6745 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6746
6747 for (int Arg = 0; Arg < 2; ++Arg) {
6748 QualType AsymetricParamTypes[2] = {
6749 S.Context.getPointerDiffType(),
6750 S.Context.getPointerDiffType(),
6751 };
6752 for (BuiltinCandidateTypeSet::iterator
6753 Ptr = CandidateTypes[Arg].pointer_begin(),
6754 PtrEnd = CandidateTypes[Arg].pointer_end();
6755 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006756 QualType PointeeTy = (*Ptr)->getPointeeType();
6757 if (!PointeeTy->isObjectType())
6758 continue;
6759
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006760 AsymetricParamTypes[Arg] = *Ptr;
6761 if (Arg == 0 || Op == OO_Plus) {
6762 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6763 // T* operator+(ptrdiff_t, T*);
6764 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6765 CandidateSet);
6766 }
6767 if (Op == OO_Minus) {
6768 // ptrdiff_t operator-(T, T);
6769 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6770 continue;
6771
6772 QualType ParamTypes[2] = { *Ptr, *Ptr };
6773 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6774 Args, 2, CandidateSet);
6775 }
6776 }
6777 }
6778 }
6779
6780 // C++ [over.built]p12:
6781 //
6782 // For every pair of promoted arithmetic types L and R, there
6783 // exist candidate operator functions of the form
6784 //
6785 // LR operator*(L, R);
6786 // LR operator/(L, R);
6787 // LR operator+(L, R);
6788 // LR operator-(L, R);
6789 // bool operator<(L, R);
6790 // bool operator>(L, R);
6791 // bool operator<=(L, R);
6792 // bool operator>=(L, R);
6793 // bool operator==(L, R);
6794 // bool operator!=(L, R);
6795 //
6796 // where LR is the result of the usual arithmetic conversions
6797 // between types L and R.
6798 //
6799 // C++ [over.built]p24:
6800 //
6801 // For every pair of promoted arithmetic types L and R, there exist
6802 // candidate operator functions of the form
6803 //
6804 // LR operator?(bool, L, R);
6805 //
6806 // where LR is the result of the usual arithmetic conversions
6807 // between types L and R.
6808 // Our candidates ignore the first parameter.
6809 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006810 if (!HasArithmeticOrEnumeralCandidateType)
6811 return;
6812
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006813 for (unsigned Left = FirstPromotedArithmeticType;
6814 Left < LastPromotedArithmeticType; ++Left) {
6815 for (unsigned Right = FirstPromotedArithmeticType;
6816 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006817 QualType LandR[2] = { getArithmeticType(Left),
6818 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006819 QualType Result =
6820 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006821 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006822 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6823 }
6824 }
6825
6826 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6827 // conditional operator for vector types.
6828 for (BuiltinCandidateTypeSet::iterator
6829 Vec1 = CandidateTypes[0].vector_begin(),
6830 Vec1End = CandidateTypes[0].vector_end();
6831 Vec1 != Vec1End; ++Vec1) {
6832 for (BuiltinCandidateTypeSet::iterator
6833 Vec2 = CandidateTypes[1].vector_begin(),
6834 Vec2End = CandidateTypes[1].vector_end();
6835 Vec2 != Vec2End; ++Vec2) {
6836 QualType LandR[2] = { *Vec1, *Vec2 };
6837 QualType Result = S.Context.BoolTy;
6838 if (!isComparison) {
6839 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6840 Result = *Vec1;
6841 else
6842 Result = *Vec2;
6843 }
6844
6845 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6846 }
6847 }
6848 }
6849
6850 // C++ [over.built]p17:
6851 //
6852 // For every pair of promoted integral types L and R, there
6853 // exist candidate operator functions of the form
6854 //
6855 // LR operator%(L, R);
6856 // LR operator&(L, R);
6857 // LR operator^(L, R);
6858 // LR operator|(L, R);
6859 // L operator<<(L, R);
6860 // L operator>>(L, R);
6861 //
6862 // where LR is the result of the usual arithmetic conversions
6863 // between types L and R.
6864 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006865 if (!HasArithmeticOrEnumeralCandidateType)
6866 return;
6867
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006868 for (unsigned Left = FirstPromotedIntegralType;
6869 Left < LastPromotedIntegralType; ++Left) {
6870 for (unsigned Right = FirstPromotedIntegralType;
6871 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006872 QualType LandR[2] = { getArithmeticType(Left),
6873 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006874 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6875 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006876 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006877 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6878 }
6879 }
6880 }
6881
6882 // C++ [over.built]p20:
6883 //
6884 // For every pair (T, VQ), where T is an enumeration or
6885 // pointer to member type and VQ is either volatile or
6886 // empty, there exist candidate operator functions of the form
6887 //
6888 // VQ T& operator=(VQ T&, T);
6889 void addAssignmentMemberPointerOrEnumeralOverloads() {
6890 /// Set of (canonical) types that we've already handled.
6891 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6892
6893 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6894 for (BuiltinCandidateTypeSet::iterator
6895 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6896 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6897 Enum != EnumEnd; ++Enum) {
6898 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6899 continue;
6900
6901 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6902 CandidateSet);
6903 }
6904
6905 for (BuiltinCandidateTypeSet::iterator
6906 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6907 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6908 MemPtr != MemPtrEnd; ++MemPtr) {
6909 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6910 continue;
6911
6912 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6913 CandidateSet);
6914 }
6915 }
6916 }
6917
6918 // C++ [over.built]p19:
6919 //
6920 // For every pair (T, VQ), where T is any type and VQ is either
6921 // volatile or empty, there exist candidate operator functions
6922 // of the form
6923 //
6924 // T*VQ& operator=(T*VQ&, T*);
6925 //
6926 // C++ [over.built]p21:
6927 //
6928 // For every pair (T, VQ), where T is a cv-qualified or
6929 // cv-unqualified object type and VQ is either volatile or
6930 // empty, there exist candidate operator functions of the form
6931 //
6932 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6933 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6934 void addAssignmentPointerOverloads(bool isEqualOp) {
6935 /// Set of (canonical) types that we've already handled.
6936 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6937
6938 for (BuiltinCandidateTypeSet::iterator
6939 Ptr = CandidateTypes[0].pointer_begin(),
6940 PtrEnd = CandidateTypes[0].pointer_end();
6941 Ptr != PtrEnd; ++Ptr) {
6942 // If this is operator=, keep track of the builtin candidates we added.
6943 if (isEqualOp)
6944 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006945 else if (!(*Ptr)->getPointeeType()->isObjectType())
6946 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006947
6948 // non-volatile version
6949 QualType ParamTypes[2] = {
6950 S.Context.getLValueReferenceType(*Ptr),
6951 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6952 };
6953 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6954 /*IsAssigmentOperator=*/ isEqualOp);
6955
6956 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6957 VisibleTypeConversionsQuals.hasVolatile()) {
6958 // volatile version
6959 ParamTypes[0] =
6960 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6962 /*IsAssigmentOperator=*/isEqualOp);
6963 }
6964 }
6965
6966 if (isEqualOp) {
6967 for (BuiltinCandidateTypeSet::iterator
6968 Ptr = CandidateTypes[1].pointer_begin(),
6969 PtrEnd = CandidateTypes[1].pointer_end();
6970 Ptr != PtrEnd; ++Ptr) {
6971 // Make sure we don't add the same candidate twice.
6972 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6973 continue;
6974
Chandler Carruth8e543b32010-12-12 08:17:55 +00006975 QualType ParamTypes[2] = {
6976 S.Context.getLValueReferenceType(*Ptr),
6977 *Ptr,
6978 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006979
6980 // non-volatile version
6981 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6982 /*IsAssigmentOperator=*/true);
6983
6984 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6985 VisibleTypeConversionsQuals.hasVolatile()) {
6986 // volatile version
6987 ParamTypes[0] =
6988 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6990 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006991 }
6992 }
6993 }
6994 }
6995
6996 // C++ [over.built]p18:
6997 //
6998 // For every triple (L, VQ, R), where L is an arithmetic type,
6999 // VQ is either volatile or empty, and R is a promoted
7000 // arithmetic type, there exist candidate operator functions of
7001 // the form
7002 //
7003 // VQ L& operator=(VQ L&, R);
7004 // VQ L& operator*=(VQ L&, R);
7005 // VQ L& operator/=(VQ L&, R);
7006 // VQ L& operator+=(VQ L&, R);
7007 // VQ L& operator-=(VQ L&, R);
7008 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007009 if (!HasArithmeticOrEnumeralCandidateType)
7010 return;
7011
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7013 for (unsigned Right = FirstPromotedArithmeticType;
7014 Right < LastPromotedArithmeticType; ++Right) {
7015 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007016 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007017
7018 // Add this built-in operator as a candidate (VQ is empty).
7019 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007020 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007021 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7022 /*IsAssigmentOperator=*/isEqualOp);
7023
7024 // Add this built-in operator as a candidate (VQ is 'volatile').
7025 if (VisibleTypeConversionsQuals.hasVolatile()) {
7026 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007027 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007028 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7030 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007031 /*IsAssigmentOperator=*/isEqualOp);
7032 }
7033 }
7034 }
7035
7036 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7037 for (BuiltinCandidateTypeSet::iterator
7038 Vec1 = CandidateTypes[0].vector_begin(),
7039 Vec1End = CandidateTypes[0].vector_end();
7040 Vec1 != Vec1End; ++Vec1) {
7041 for (BuiltinCandidateTypeSet::iterator
7042 Vec2 = CandidateTypes[1].vector_begin(),
7043 Vec2End = CandidateTypes[1].vector_end();
7044 Vec2 != Vec2End; ++Vec2) {
7045 QualType ParamTypes[2];
7046 ParamTypes[1] = *Vec2;
7047 // Add this built-in operator as a candidate (VQ is empty).
7048 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7049 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7050 /*IsAssigmentOperator=*/isEqualOp);
7051
7052 // Add this built-in operator as a candidate (VQ is 'volatile').
7053 if (VisibleTypeConversionsQuals.hasVolatile()) {
7054 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7055 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7057 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007058 /*IsAssigmentOperator=*/isEqualOp);
7059 }
7060 }
7061 }
7062 }
7063
7064 // C++ [over.built]p22:
7065 //
7066 // For every triple (L, VQ, R), where L is an integral type, VQ
7067 // is either volatile or empty, and R is a promoted integral
7068 // type, there exist candidate operator functions of the form
7069 //
7070 // VQ L& operator%=(VQ L&, R);
7071 // VQ L& operator<<=(VQ L&, R);
7072 // VQ L& operator>>=(VQ L&, R);
7073 // VQ L& operator&=(VQ L&, R);
7074 // VQ L& operator^=(VQ L&, R);
7075 // VQ L& operator|=(VQ L&, R);
7076 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007077 if (!HasArithmeticOrEnumeralCandidateType)
7078 return;
7079
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007080 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7081 for (unsigned Right = FirstPromotedIntegralType;
7082 Right < LastPromotedIntegralType; ++Right) {
7083 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007084 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007085
7086 // Add this built-in operator as a candidate (VQ is empty).
7087 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007088 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007089 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7090 if (VisibleTypeConversionsQuals.hasVolatile()) {
7091 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007092 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007093 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7094 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7096 CandidateSet);
7097 }
7098 }
7099 }
7100 }
7101
7102 // C++ [over.operator]p23:
7103 //
7104 // There also exist candidate operator functions of the form
7105 //
7106 // bool operator!(bool);
7107 // bool operator&&(bool, bool);
7108 // bool operator||(bool, bool);
7109 void addExclaimOverload() {
7110 QualType ParamTy = S.Context.BoolTy;
7111 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7112 /*IsAssignmentOperator=*/false,
7113 /*NumContextualBoolArguments=*/1);
7114 }
7115 void addAmpAmpOrPipePipeOverload() {
7116 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7117 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7118 /*IsAssignmentOperator=*/false,
7119 /*NumContextualBoolArguments=*/2);
7120 }
7121
7122 // C++ [over.built]p13:
7123 //
7124 // For every cv-qualified or cv-unqualified object type T there
7125 // exist candidate operator functions of the form
7126 //
7127 // T* operator+(T*, ptrdiff_t); [ABOVE]
7128 // T& operator[](T*, ptrdiff_t);
7129 // T* operator-(T*, ptrdiff_t); [ABOVE]
7130 // T* operator+(ptrdiff_t, T*); [ABOVE]
7131 // T& operator[](ptrdiff_t, T*);
7132 void addSubscriptOverloads() {
7133 for (BuiltinCandidateTypeSet::iterator
7134 Ptr = CandidateTypes[0].pointer_begin(),
7135 PtrEnd = CandidateTypes[0].pointer_end();
7136 Ptr != PtrEnd; ++Ptr) {
7137 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7138 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007139 if (!PointeeType->isObjectType())
7140 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007141
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007142 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7143
7144 // T& operator[](T*, ptrdiff_t)
7145 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7146 }
7147
7148 for (BuiltinCandidateTypeSet::iterator
7149 Ptr = CandidateTypes[1].pointer_begin(),
7150 PtrEnd = CandidateTypes[1].pointer_end();
7151 Ptr != PtrEnd; ++Ptr) {
7152 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7153 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007154 if (!PointeeType->isObjectType())
7155 continue;
7156
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007157 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7158
7159 // T& operator[](ptrdiff_t, T*)
7160 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7161 }
7162 }
7163
7164 // C++ [over.built]p11:
7165 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7166 // C1 is the same type as C2 or is a derived class of C2, T is an object
7167 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7168 // there exist candidate operator functions of the form
7169 //
7170 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7171 //
7172 // where CV12 is the union of CV1 and CV2.
7173 void addArrowStarOverloads() {
7174 for (BuiltinCandidateTypeSet::iterator
7175 Ptr = CandidateTypes[0].pointer_begin(),
7176 PtrEnd = CandidateTypes[0].pointer_end();
7177 Ptr != PtrEnd; ++Ptr) {
7178 QualType C1Ty = (*Ptr);
7179 QualType C1;
7180 QualifierCollector Q1;
7181 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7182 if (!isa<RecordType>(C1))
7183 continue;
7184 // heuristic to reduce number of builtin candidates in the set.
7185 // Add volatile/restrict version only if there are conversions to a
7186 // volatile/restrict type.
7187 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7188 continue;
7189 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7190 continue;
7191 for (BuiltinCandidateTypeSet::iterator
7192 MemPtr = CandidateTypes[1].member_pointer_begin(),
7193 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7194 MemPtr != MemPtrEnd; ++MemPtr) {
7195 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7196 QualType C2 = QualType(mptr->getClass(), 0);
7197 C2 = C2.getUnqualifiedType();
7198 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7199 break;
7200 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7201 // build CV12 T&
7202 QualType T = mptr->getPointeeType();
7203 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7204 T.isVolatileQualified())
7205 continue;
7206 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7207 T.isRestrictQualified())
7208 continue;
7209 T = Q1.apply(S.Context, T);
7210 QualType ResultTy = S.Context.getLValueReferenceType(T);
7211 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7212 }
7213 }
7214 }
7215
7216 // Note that we don't consider the first argument, since it has been
7217 // contextually converted to bool long ago. The candidates below are
7218 // therefore added as binary.
7219 //
7220 // C++ [over.built]p25:
7221 // For every type T, where T is a pointer, pointer-to-member, or scoped
7222 // enumeration type, there exist candidate operator functions of the form
7223 //
7224 // T operator?(bool, T, T);
7225 //
7226 void addConditionalOperatorOverloads() {
7227 /// Set of (canonical) types that we've already handled.
7228 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7229
7230 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7231 for (BuiltinCandidateTypeSet::iterator
7232 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7233 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7234 Ptr != PtrEnd; ++Ptr) {
7235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7236 continue;
7237
7238 QualType ParamTypes[2] = { *Ptr, *Ptr };
7239 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7240 }
7241
7242 for (BuiltinCandidateTypeSet::iterator
7243 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7244 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7245 MemPtr != MemPtrEnd; ++MemPtr) {
7246 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7247 continue;
7248
7249 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7250 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7251 }
7252
David Blaikiebbafb8a2012-03-11 07:00:24 +00007253 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007254 for (BuiltinCandidateTypeSet::iterator
7255 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7256 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7257 Enum != EnumEnd; ++Enum) {
7258 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7259 continue;
7260
7261 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7262 continue;
7263
7264 QualType ParamTypes[2] = { *Enum, *Enum };
7265 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7266 }
7267 }
7268 }
7269 }
7270};
7271
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007272} // end anonymous namespace
7273
7274/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7275/// operator overloads to the candidate set (C++ [over.built]), based
7276/// on the operator @p Op and the arguments given. For example, if the
7277/// operator is a binary '+', this routine might add "int
7278/// operator+(int, int)" to cover integer addition.
7279void
7280Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7281 SourceLocation OpLoc,
7282 Expr **Args, unsigned NumArgs,
7283 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007284 // Find all of the types that the arguments can convert to, but only
7285 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007286 // that make use of these types. Also record whether we encounter non-record
7287 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007288 Qualifiers VisibleTypeConversionsQuals;
7289 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007290 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7291 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007292
7293 bool HasNonRecordCandidateType = false;
7294 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007295 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007296 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7297 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7298 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7299 OpLoc,
7300 true,
7301 (Op == OO_Exclaim ||
7302 Op == OO_AmpAmp ||
7303 Op == OO_PipePipe),
7304 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007305 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7306 CandidateTypes[ArgIdx].hasNonRecordTypes();
7307 HasArithmeticOrEnumeralCandidateType =
7308 HasArithmeticOrEnumeralCandidateType ||
7309 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007310 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007311
Chandler Carruth00a38332010-12-13 01:44:01 +00007312 // Exit early when no non-record types have been added to the candidate set
7313 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007314 //
7315 // We can't exit early for !, ||, or &&, since there we have always have
7316 // 'bool' overloads.
7317 if (!HasNonRecordCandidateType &&
7318 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007319 return;
7320
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007321 // Setup an object to manage the common state for building overloads.
7322 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7323 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007324 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007325 CandidateTypes, CandidateSet);
7326
7327 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007328 switch (Op) {
7329 case OO_None:
7330 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007331 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007332
Chandler Carruth5184de02010-12-12 08:51:33 +00007333 case OO_New:
7334 case OO_Delete:
7335 case OO_Array_New:
7336 case OO_Array_Delete:
7337 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007338 llvm_unreachable(
7339 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007340
7341 case OO_Comma:
7342 case OO_Arrow:
7343 // C++ [over.match.oper]p3:
7344 // -- For the operator ',', the unary operator '&', or the
7345 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007346 break;
7347
7348 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007349 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007351 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007352
7353 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007354 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007356 } else {
7357 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7358 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7359 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007360 break;
7361
Chandler Carruth5184de02010-12-12 08:51:33 +00007362 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007363 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007364 OpBuilder.addUnaryStarPointerOverloads();
7365 else
7366 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7367 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007368
Chandler Carruth5184de02010-12-12 08:51:33 +00007369 case OO_Slash:
7370 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007371 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007372
7373 case OO_PlusPlus:
7374 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007375 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7376 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007377 break;
7378
Douglas Gregor84605ae2009-08-24 13:43:27 +00007379 case OO_EqualEqual:
7380 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007381 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007382 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007383
Douglas Gregora11693b2008-11-12 17:17:38 +00007384 case OO_Less:
7385 case OO_Greater:
7386 case OO_LessEqual:
7387 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007388 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007389 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7390 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007391
Douglas Gregora11693b2008-11-12 17:17:38 +00007392 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007393 case OO_Caret:
7394 case OO_Pipe:
7395 case OO_LessLess:
7396 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007397 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007398 break;
7399
Chandler Carruth5184de02010-12-12 08:51:33 +00007400 case OO_Amp: // '&' is either unary or binary
7401 if (NumArgs == 1)
7402 // C++ [over.match.oper]p3:
7403 // -- For the operator ',', the unary operator '&', or the
7404 // operator '->', the built-in candidates set is empty.
7405 break;
7406
7407 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7408 break;
7409
7410 case OO_Tilde:
7411 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7412 break;
7413
Douglas Gregora11693b2008-11-12 17:17:38 +00007414 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007415 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007416 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007417
7418 case OO_PlusEqual:
7419 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007420 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007421 // Fall through.
7422
7423 case OO_StarEqual:
7424 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007426 break;
7427
7428 case OO_PercentEqual:
7429 case OO_LessLessEqual:
7430 case OO_GreaterGreaterEqual:
7431 case OO_AmpEqual:
7432 case OO_CaretEqual:
7433 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007434 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007435 break;
7436
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007437 case OO_Exclaim:
7438 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007439 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007440
Douglas Gregora11693b2008-11-12 17:17:38 +00007441 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007442 case OO_PipePipe:
7443 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007444 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007445
7446 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007447 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007448 break;
7449
7450 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007452 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007453
7454 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007455 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007456 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7457 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007458 }
7459}
7460
Douglas Gregore254f902009-02-04 00:32:51 +00007461/// \brief Add function candidates found via argument-dependent lookup
7462/// to the set of overloading candidates.
7463///
7464/// This routine performs argument-dependent name lookup based on the
7465/// given function name (which may also be an operator name) and adds
7466/// all of the overload candidates found by ADL to the overload
7467/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007468void
Douglas Gregore254f902009-02-04 00:32:51 +00007469Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007470 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007471 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007472 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007473 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007474 bool PartialOverloading,
7475 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007476 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007477
John McCall91f61fc2010-01-26 06:04:06 +00007478 // FIXME: This approach for uniquing ADL results (and removing
7479 // redundant candidates from the set) relies on pointer-equality,
7480 // which means we need to key off the canonical decl. However,
7481 // always going back to the canonical decl might not get us the
7482 // right set of default arguments. What default arguments are
7483 // we supposed to consider on ADL candidates, anyway?
7484
Douglas Gregorcabea402009-09-22 15:41:20 +00007485 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007486 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007487 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007488
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007489 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007490 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7491 CandEnd = CandidateSet.end();
7492 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007493 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007494 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007495 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007496 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007497 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007498
7499 // For each of the ADL candidates we found, add it to the overload
7500 // set.
John McCall8fe68082010-01-26 07:16:45 +00007501 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007502 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007503 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007504 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007505 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007507 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7508 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007509 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007510 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007511 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007512 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007513 }
Douglas Gregore254f902009-02-04 00:32:51 +00007514}
7515
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007516/// isBetterOverloadCandidate - Determines whether the first overload
7517/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007518bool
John McCall5c32be02010-08-24 20:38:10 +00007519isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007520 const OverloadCandidate &Cand1,
7521 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007522 SourceLocation Loc,
7523 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007524 // Define viable functions to be better candidates than non-viable
7525 // functions.
7526 if (!Cand2.Viable)
7527 return Cand1.Viable;
7528 else if (!Cand1.Viable)
7529 return false;
7530
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007531 // C++ [over.match.best]p1:
7532 //
7533 // -- if F is a static member function, ICS1(F) is defined such
7534 // that ICS1(F) is neither better nor worse than ICS1(G) for
7535 // any function G, and, symmetrically, ICS1(G) is neither
7536 // better nor worse than ICS1(F).
7537 unsigned StartArg = 0;
7538 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7539 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007540
Douglas Gregord3cb3562009-07-07 23:38:56 +00007541 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007542 // A viable function F1 is defined to be a better function than another
7543 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007544 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007545 unsigned NumArgs = Cand1.NumConversions;
7546 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007547 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007548 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007549 switch (CompareImplicitConversionSequences(S,
7550 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007551 Cand2.Conversions[ArgIdx])) {
7552 case ImplicitConversionSequence::Better:
7553 // Cand1 has a better conversion sequence.
7554 HasBetterConversion = true;
7555 break;
7556
7557 case ImplicitConversionSequence::Worse:
7558 // Cand1 can't be better than Cand2.
7559 return false;
7560
7561 case ImplicitConversionSequence::Indistinguishable:
7562 // Do nothing.
7563 break;
7564 }
7565 }
7566
Mike Stump11289f42009-09-09 15:08:12 +00007567 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007568 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007569 if (HasBetterConversion)
7570 return true;
7571
Mike Stump11289f42009-09-09 15:08:12 +00007572 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007573 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007574 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007575 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7576 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007577
7578 // -- F1 and F2 are function template specializations, and the function
7579 // template for F1 is more specialized than the template for F2
7580 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007581 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007582 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007583 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007584 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007585 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7586 Cand2.Function->getPrimaryTemplate(),
7587 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007588 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007589 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007590 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007591 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007593
Douglas Gregora1f013e2008-11-07 22:36:19 +00007594 // -- the context is an initialization by user-defined conversion
7595 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7596 // from the return type of F1 to the destination type (i.e.,
7597 // the type of the entity being initialized) is a better
7598 // conversion sequence than the standard conversion sequence
7599 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007600 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007601 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007602 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007603 // First check whether we prefer one of the conversion functions over the
7604 // other. This only distinguishes the results in non-standard, extension
7605 // cases such as the conversion from a lambda closure type to a function
7606 // pointer or block.
7607 ImplicitConversionSequence::CompareKind FuncResult
7608 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7609 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7610 return FuncResult;
7611
John McCall5c32be02010-08-24 20:38:10 +00007612 switch (CompareStandardConversionSequences(S,
7613 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007614 Cand2.FinalConversion)) {
7615 case ImplicitConversionSequence::Better:
7616 // Cand1 has a better conversion sequence.
7617 return true;
7618
7619 case ImplicitConversionSequence::Worse:
7620 // Cand1 can't be better than Cand2.
7621 return false;
7622
7623 case ImplicitConversionSequence::Indistinguishable:
7624 // Do nothing
7625 break;
7626 }
7627 }
7628
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007629 return false;
7630}
7631
Mike Stump11289f42009-09-09 15:08:12 +00007632/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007633/// within an overload candidate set.
7634///
7635/// \param CandidateSet the set of candidate functions.
7636///
7637/// \param Loc the location of the function name (or operator symbol) for
7638/// which overload resolution occurs.
7639///
Mike Stump11289f42009-09-09 15:08:12 +00007640/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007641/// function, Best points to the candidate function found.
7642///
7643/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007644OverloadingResult
7645OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007646 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007647 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007648 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007649 Best = end();
7650 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7651 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007652 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007653 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007654 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007655 }
7656
7657 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007658 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007659 return OR_No_Viable_Function;
7660
7661 // Make sure that this function is better than every other viable
7662 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007663 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007664 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007665 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007666 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007667 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007668 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007669 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007670 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007671 }
Mike Stump11289f42009-09-09 15:08:12 +00007672
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007673 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007674 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007675 (Best->Function->isDeleted() ||
7676 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007677 return OR_Deleted;
7678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007679 return OR_Success;
7680}
7681
John McCall53262c92010-01-12 02:15:36 +00007682namespace {
7683
7684enum OverloadCandidateKind {
7685 oc_function,
7686 oc_method,
7687 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007688 oc_function_template,
7689 oc_method_template,
7690 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007691 oc_implicit_default_constructor,
7692 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007693 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007694 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007695 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007696 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007697};
7698
John McCalle1ac8d12010-01-13 00:25:19 +00007699OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7700 FunctionDecl *Fn,
7701 std::string &Description) {
7702 bool isTemplate = false;
7703
7704 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7705 isTemplate = true;
7706 Description = S.getTemplateArgumentBindingsText(
7707 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7708 }
John McCallfd0b2f82010-01-06 09:43:14 +00007709
7710 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007711 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007712 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007713
Sebastian Redl08905022011-02-05 19:23:19 +00007714 if (Ctor->getInheritedConstructor())
7715 return oc_implicit_inherited_constructor;
7716
Alexis Hunt119c10e2011-05-25 23:16:36 +00007717 if (Ctor->isDefaultConstructor())
7718 return oc_implicit_default_constructor;
7719
7720 if (Ctor->isMoveConstructor())
7721 return oc_implicit_move_constructor;
7722
7723 assert(Ctor->isCopyConstructor() &&
7724 "unexpected sort of implicit constructor");
7725 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007726 }
7727
7728 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7729 // This actually gets spelled 'candidate function' for now, but
7730 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007731 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007732 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007733
Alexis Hunt119c10e2011-05-25 23:16:36 +00007734 if (Meth->isMoveAssignmentOperator())
7735 return oc_implicit_move_assignment;
7736
Douglas Gregor12695102012-02-10 08:36:38 +00007737 if (Meth->isCopyAssignmentOperator())
7738 return oc_implicit_copy_assignment;
7739
7740 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7741 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007742 }
7743
John McCalle1ac8d12010-01-13 00:25:19 +00007744 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007745}
7746
Sebastian Redl08905022011-02-05 19:23:19 +00007747void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7748 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7749 if (!Ctor) return;
7750
7751 Ctor = Ctor->getInheritedConstructor();
7752 if (!Ctor) return;
7753
7754 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7755}
7756
John McCall53262c92010-01-12 02:15:36 +00007757} // end anonymous namespace
7758
7759// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007760void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007761 std::string FnDesc;
7762 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007763 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7764 << (unsigned) K << FnDesc;
7765 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7766 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007767 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007768}
7769
Douglas Gregorb491ed32011-02-19 21:32:49 +00007770//Notes the location of all overload candidates designated through
7771// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007772void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007773 assert(OverloadedExpr->getType() == Context.OverloadTy);
7774
7775 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7776 OverloadExpr *OvlExpr = Ovl.Expression;
7777
7778 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7779 IEnd = OvlExpr->decls_end();
7780 I != IEnd; ++I) {
7781 if (FunctionTemplateDecl *FunTmpl =
7782 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007783 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007784 } else if (FunctionDecl *Fun
7785 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007786 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007787 }
7788 }
7789}
7790
John McCall0d1da222010-01-12 00:44:57 +00007791/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7792/// "lead" diagnostic; it will be given two arguments, the source and
7793/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007794void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7795 Sema &S,
7796 SourceLocation CaretLoc,
7797 const PartialDiagnostic &PDiag) const {
7798 S.Diag(CaretLoc, PDiag)
7799 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007800 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007801 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7802 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007803 }
John McCall12f97bc2010-01-08 04:41:39 +00007804}
7805
John McCall0d1da222010-01-12 00:44:57 +00007806namespace {
7807
John McCall6a61b522010-01-13 09:16:55 +00007808void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7809 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7810 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007811 assert(Cand->Function && "for now, candidate must be a function");
7812 FunctionDecl *Fn = Cand->Function;
7813
7814 // There's a conversion slot for the object argument if this is a
7815 // non-constructor method. Note that 'I' corresponds the
7816 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007817 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007818 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007819 if (I == 0)
7820 isObjectArgument = true;
7821 else
7822 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007823 }
7824
John McCalle1ac8d12010-01-13 00:25:19 +00007825 std::string FnDesc;
7826 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7827
John McCall6a61b522010-01-13 09:16:55 +00007828 Expr *FromExpr = Conv.Bad.FromExpr;
7829 QualType FromTy = Conv.Bad.getFromType();
7830 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007831
John McCallfb7ad0f2010-02-02 02:42:52 +00007832 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007833 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007834 Expr *E = FromExpr->IgnoreParens();
7835 if (isa<UnaryOperator>(E))
7836 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007837 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007838
7839 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7840 << (unsigned) FnKind << FnDesc
7841 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7842 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007843 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007844 return;
7845 }
7846
John McCall6d174642010-01-23 08:10:49 +00007847 // Do some hand-waving analysis to see if the non-viability is due
7848 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007849 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7850 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7851 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7852 CToTy = RT->getPointeeType();
7853 else {
7854 // TODO: detect and diagnose the full richness of const mismatches.
7855 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7856 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7857 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7858 }
7859
7860 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7861 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007862 Qualifiers FromQs = CFromTy.getQualifiers();
7863 Qualifiers ToQs = CToTy.getQualifiers();
7864
7865 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7866 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7867 << (unsigned) FnKind << FnDesc
7868 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7869 << FromTy
7870 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7871 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007872 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007873 return;
7874 }
7875
John McCall31168b02011-06-15 23:02:42 +00007876 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007877 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007878 << (unsigned) FnKind << FnDesc
7879 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7880 << FromTy
7881 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7882 << (unsigned) isObjectArgument << I+1;
7883 MaybeEmitInheritedConstructorNote(S, Fn);
7884 return;
7885 }
7886
Douglas Gregoraec25842011-04-26 23:16:46 +00007887 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7888 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7889 << (unsigned) FnKind << FnDesc
7890 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7891 << FromTy
7892 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7893 << (unsigned) isObjectArgument << I+1;
7894 MaybeEmitInheritedConstructorNote(S, Fn);
7895 return;
7896 }
7897
John McCall47000992010-01-14 03:28:57 +00007898 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7899 assert(CVR && "unexpected qualifiers mismatch");
7900
7901 if (isObjectArgument) {
7902 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7903 << (unsigned) FnKind << FnDesc
7904 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7905 << FromTy << (CVR - 1);
7906 } else {
7907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7908 << (unsigned) FnKind << FnDesc
7909 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7910 << FromTy << (CVR - 1) << I+1;
7911 }
Sebastian Redl08905022011-02-05 19:23:19 +00007912 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007913 return;
7914 }
7915
Sebastian Redla72462c2011-09-24 17:48:32 +00007916 // Special diagnostic for failure to convert an initializer list, since
7917 // telling the user that it has type void is not useful.
7918 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7920 << (unsigned) FnKind << FnDesc
7921 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7922 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7923 MaybeEmitInheritedConstructorNote(S, Fn);
7924 return;
7925 }
7926
John McCall6d174642010-01-23 08:10:49 +00007927 // Diagnose references or pointers to incomplete types differently,
7928 // since it's far from impossible that the incompleteness triggered
7929 // the failure.
7930 QualType TempFromTy = FromTy.getNonReferenceType();
7931 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7932 TempFromTy = PTy->getPointeeType();
7933 if (TempFromTy->isIncompleteType()) {
7934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7935 << (unsigned) FnKind << FnDesc
7936 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7937 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007938 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007939 return;
7940 }
7941
Douglas Gregor56f2e342010-06-30 23:01:39 +00007942 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007943 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007944 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7945 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7946 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7947 FromPtrTy->getPointeeType()) &&
7948 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7949 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007950 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007951 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007952 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007953 }
7954 } else if (const ObjCObjectPointerType *FromPtrTy
7955 = FromTy->getAs<ObjCObjectPointerType>()) {
7956 if (const ObjCObjectPointerType *ToPtrTy
7957 = ToTy->getAs<ObjCObjectPointerType>())
7958 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7959 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7960 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7961 FromPtrTy->getPointeeType()) &&
7962 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007963 BaseToDerivedConversion = 2;
7964 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7965 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7966 !FromTy->isIncompleteType() &&
7967 !ToRefTy->getPointeeType()->isIncompleteType() &&
7968 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7969 BaseToDerivedConversion = 3;
7970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007972 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007973 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007974 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007975 << (unsigned) FnKind << FnDesc
7976 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007977 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007978 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007979 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007980 return;
7981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007983 if (isa<ObjCObjectPointerType>(CFromTy) &&
7984 isa<PointerType>(CToTy)) {
7985 Qualifiers FromQs = CFromTy.getQualifiers();
7986 Qualifiers ToQs = CToTy.getQualifiers();
7987 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7988 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7989 << (unsigned) FnKind << FnDesc
7990 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7991 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7992 MaybeEmitInheritedConstructorNote(S, Fn);
7993 return;
7994 }
7995 }
7996
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007997 // Emit the generic diagnostic and, optionally, add the hints to it.
7998 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7999 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008000 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008001 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8002 << (unsigned) (Cand->Fix.Kind);
8003
8004 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008005 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8006 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008007 FDiag << *HI;
8008 S.Diag(Fn->getLocation(), FDiag);
8009
Sebastian Redl08905022011-02-05 19:23:19 +00008010 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008011}
8012
8013void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8014 unsigned NumFormalArgs) {
8015 // TODO: treat calls to a missing default constructor as a special case
8016
8017 FunctionDecl *Fn = Cand->Function;
8018 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8019
8020 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008022 // With invalid overloaded operators, it's possible that we think we
8023 // have an arity mismatch when it fact it looks like we have the
8024 // right number of arguments, because only overloaded operators have
8025 // the weird behavior of overloading member and non-member functions.
8026 // Just don't report anything.
8027 if (Fn->isInvalidDecl() &&
8028 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8029 return;
8030
John McCall6a61b522010-01-13 09:16:55 +00008031 // at least / at most / exactly
8032 unsigned mode, modeCount;
8033 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008034 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8035 (Cand->FailureKind == ovl_fail_bad_deduction &&
8036 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008038 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008039 mode = 0; // "at least"
8040 else
8041 mode = 2; // "exactly"
8042 modeCount = MinParams;
8043 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008044 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8045 (Cand->FailureKind == ovl_fail_bad_deduction &&
8046 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008047 if (MinParams != FnTy->getNumArgs())
8048 mode = 1; // "at most"
8049 else
8050 mode = 2; // "exactly"
8051 modeCount = FnTy->getNumArgs();
8052 }
8053
8054 std::string Description;
8055 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8056
8057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008058 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008059 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008060 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008061}
8062
John McCall8b9ed552010-02-01 18:53:26 +00008063/// Diagnose a failed template-argument deduction.
8064void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008065 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008066 FunctionDecl *Fn = Cand->Function; // pattern
8067
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008068 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008069 NamedDecl *ParamD;
8070 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8071 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8072 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008073 switch (Cand->DeductionFailure.Result) {
8074 case Sema::TDK_Success:
8075 llvm_unreachable("TDK_success while diagnosing bad deduction");
8076
8077 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008078 assert(ParamD && "no parameter found for incomplete deduction result");
8079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8080 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008081 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008082 return;
8083 }
8084
John McCall42d7d192010-08-05 09:05:08 +00008085 case Sema::TDK_Underqualified: {
8086 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8087 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8088
8089 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8090
8091 // Param will have been canonicalized, but it should just be a
8092 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008093 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008094 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008095 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008096 assert(S.Context.hasSameType(Param, NonCanonParam));
8097
8098 // Arg has also been canonicalized, but there's nothing we can do
8099 // about that. It also doesn't matter as much, because it won't
8100 // have any template parameters in it (because deduction isn't
8101 // done on dependent types).
8102 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8103
8104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8105 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008106 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008107 return;
8108 }
8109
8110 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008111 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008112 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008113 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008114 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008115 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008116 which = 1;
8117 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008118 which = 2;
8119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008121 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008123 << *Cand->DeductionFailure.getFirstArg()
8124 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008125 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008126 return;
8127 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008128
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008129 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008130 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008131 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008133 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8134 << ParamD->getDeclName();
8135 else {
8136 int index = 0;
8137 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8138 index = TTP->getIndex();
8139 else if (NonTypeTemplateParmDecl *NTTP
8140 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8141 index = NTTP->getIndex();
8142 else
8143 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008144 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008145 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8146 << (index + 1);
8147 }
Sebastian Redl08905022011-02-05 19:23:19 +00008148 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008149 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150
Douglas Gregor02eb4832010-05-08 18:13:28 +00008151 case Sema::TDK_TooManyArguments:
8152 case Sema::TDK_TooFewArguments:
8153 DiagnoseArityMismatch(S, Cand, NumArgs);
8154 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008155
8156 case Sema::TDK_InstantiationDepth:
8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008158 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008159 return;
8160
8161 case Sema::TDK_SubstitutionFailure: {
8162 std::string ArgString;
8163 if (TemplateArgumentList *Args
8164 = Cand->DeductionFailure.getTemplateArgumentList())
8165 ArgString = S.getTemplateArgumentBindingsText(
8166 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8167 *Args);
8168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8169 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00008170 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008171 return;
8172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008173
John McCall8b9ed552010-02-01 18:53:26 +00008174 // TODO: diagnose these individually, then kill off
8175 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008176 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008177 case Sema::TDK_FailedOverloadResolution:
8178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008179 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008180 return;
8181 }
8182}
8183
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008184/// CUDA: diagnose an invalid call across targets.
8185void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8186 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8187 FunctionDecl *Callee = Cand->Function;
8188
8189 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8190 CalleeTarget = S.IdentifyCUDATarget(Callee);
8191
8192 std::string FnDesc;
8193 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8194
8195 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8196 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8197}
8198
John McCall8b9ed552010-02-01 18:53:26 +00008199/// Generates a 'note' diagnostic for an overload candidate. We've
8200/// already generated a primary error at the call site.
8201///
8202/// It really does need to be a single diagnostic with its caret
8203/// pointed at the candidate declaration. Yes, this creates some
8204/// major challenges of technical writing. Yes, this makes pointing
8205/// out problems with specific arguments quite awkward. It's still
8206/// better than generating twenty screens of text for every failed
8207/// overload.
8208///
8209/// It would be great to be able to express per-candidate problems
8210/// more richly for those diagnostic clients that cared, but we'd
8211/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008212void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008213 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008214 FunctionDecl *Fn = Cand->Function;
8215
John McCall12f97bc2010-01-08 04:41:39 +00008216 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008217 if (Cand->Viable && (Fn->isDeleted() ||
8218 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008219 std::string FnDesc;
8220 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008221
8222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00008223 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00008224 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008225 return;
John McCall12f97bc2010-01-08 04:41:39 +00008226 }
8227
John McCalle1ac8d12010-01-13 00:25:19 +00008228 // We don't really have anything else to say about viable candidates.
8229 if (Cand->Viable) {
8230 S.NoteOverloadCandidate(Fn);
8231 return;
8232 }
John McCall0d1da222010-01-12 00:44:57 +00008233
John McCall6a61b522010-01-13 09:16:55 +00008234 switch (Cand->FailureKind) {
8235 case ovl_fail_too_many_arguments:
8236 case ovl_fail_too_few_arguments:
8237 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008238
John McCall6a61b522010-01-13 09:16:55 +00008239 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008240 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008241
John McCallfe796dd2010-01-23 05:17:32 +00008242 case ovl_fail_trivial_conversion:
8243 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008244 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008245 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008246
John McCall65eb8792010-02-25 01:37:24 +00008247 case ovl_fail_bad_conversion: {
8248 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008249 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008250 if (Cand->Conversions[I].isBad())
8251 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008252
John McCall6a61b522010-01-13 09:16:55 +00008253 // FIXME: this currently happens when we're called from SemaInit
8254 // when user-conversion overload fails. Figure out how to handle
8255 // those conditions and diagnose them well.
8256 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008257 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008258
8259 case ovl_fail_bad_target:
8260 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008261 }
John McCalld3224162010-01-08 00:58:21 +00008262}
8263
8264void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8265 // Desugar the type of the surrogate down to a function type,
8266 // retaining as many typedefs as possible while still showing
8267 // the function type (and, therefore, its parameter types).
8268 QualType FnType = Cand->Surrogate->getConversionType();
8269 bool isLValueReference = false;
8270 bool isRValueReference = false;
8271 bool isPointer = false;
8272 if (const LValueReferenceType *FnTypeRef =
8273 FnType->getAs<LValueReferenceType>()) {
8274 FnType = FnTypeRef->getPointeeType();
8275 isLValueReference = true;
8276 } else if (const RValueReferenceType *FnTypeRef =
8277 FnType->getAs<RValueReferenceType>()) {
8278 FnType = FnTypeRef->getPointeeType();
8279 isRValueReference = true;
8280 }
8281 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8282 FnType = FnTypePtr->getPointeeType();
8283 isPointer = true;
8284 }
8285 // Desugar down to a function type.
8286 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8287 // Reconstruct the pointer/reference as appropriate.
8288 if (isPointer) FnType = S.Context.getPointerType(FnType);
8289 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8290 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8291
8292 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8293 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008294 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008295}
8296
8297void NoteBuiltinOperatorCandidate(Sema &S,
8298 const char *Opc,
8299 SourceLocation OpLoc,
8300 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008301 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008302 std::string TypeStr("operator");
8303 TypeStr += Opc;
8304 TypeStr += "(";
8305 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008306 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008307 TypeStr += ")";
8308 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8309 } else {
8310 TypeStr += ", ";
8311 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8312 TypeStr += ")";
8313 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8314 }
8315}
8316
8317void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8318 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008319 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008320 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8321 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008322 if (ICS.isBad()) break; // all meaningless after first invalid
8323 if (!ICS.isAmbiguous()) continue;
8324
John McCall5c32be02010-08-24 20:38:10 +00008325 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008326 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008327 }
8328}
8329
John McCall3712d9e2010-01-15 23:32:50 +00008330SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8331 if (Cand->Function)
8332 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008333 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008334 return Cand->Surrogate->getLocation();
8335 return SourceLocation();
8336}
8337
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008338static unsigned
8339RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008340 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008341 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008342 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008343
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008344 case Sema::TDK_Incomplete:
8345 return 1;
8346
8347 case Sema::TDK_Underqualified:
8348 case Sema::TDK_Inconsistent:
8349 return 2;
8350
8351 case Sema::TDK_SubstitutionFailure:
8352 case Sema::TDK_NonDeducedMismatch:
8353 return 3;
8354
8355 case Sema::TDK_InstantiationDepth:
8356 case Sema::TDK_FailedOverloadResolution:
8357 return 4;
8358
8359 case Sema::TDK_InvalidExplicitArguments:
8360 return 5;
8361
8362 case Sema::TDK_TooManyArguments:
8363 case Sema::TDK_TooFewArguments:
8364 return 6;
8365 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008366 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008367}
8368
John McCallad2587a2010-01-12 00:48:53 +00008369struct CompareOverloadCandidatesForDisplay {
8370 Sema &S;
8371 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008372
8373 bool operator()(const OverloadCandidate *L,
8374 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008375 // Fast-path this check.
8376 if (L == R) return false;
8377
John McCall12f97bc2010-01-08 04:41:39 +00008378 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008379 if (L->Viable) {
8380 if (!R->Viable) return true;
8381
8382 // TODO: introduce a tri-valued comparison for overload
8383 // candidates. Would be more worthwhile if we had a sort
8384 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008385 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8386 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008387 } else if (R->Viable)
8388 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008389
John McCall3712d9e2010-01-15 23:32:50 +00008390 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008391
John McCall3712d9e2010-01-15 23:32:50 +00008392 // Criteria by which we can sort non-viable candidates:
8393 if (!L->Viable) {
8394 // 1. Arity mismatches come after other candidates.
8395 if (L->FailureKind == ovl_fail_too_many_arguments ||
8396 L->FailureKind == ovl_fail_too_few_arguments)
8397 return false;
8398 if (R->FailureKind == ovl_fail_too_many_arguments ||
8399 R->FailureKind == ovl_fail_too_few_arguments)
8400 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008401
John McCallfe796dd2010-01-23 05:17:32 +00008402 // 2. Bad conversions come first and are ordered by the number
8403 // of bad conversions and quality of good conversions.
8404 if (L->FailureKind == ovl_fail_bad_conversion) {
8405 if (R->FailureKind != ovl_fail_bad_conversion)
8406 return true;
8407
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008408 // The conversion that can be fixed with a smaller number of changes,
8409 // comes first.
8410 unsigned numLFixes = L->Fix.NumConversionsFixed;
8411 unsigned numRFixes = R->Fix.NumConversionsFixed;
8412 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8413 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008414 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008415 if (numLFixes < numRFixes)
8416 return true;
8417 else
8418 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008419 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008420
John McCallfe796dd2010-01-23 05:17:32 +00008421 // If there's any ordering between the defined conversions...
8422 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008423 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008424
8425 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008426 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008427 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008428 switch (CompareImplicitConversionSequences(S,
8429 L->Conversions[I],
8430 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008431 case ImplicitConversionSequence::Better:
8432 leftBetter++;
8433 break;
8434
8435 case ImplicitConversionSequence::Worse:
8436 leftBetter--;
8437 break;
8438
8439 case ImplicitConversionSequence::Indistinguishable:
8440 break;
8441 }
8442 }
8443 if (leftBetter > 0) return true;
8444 if (leftBetter < 0) return false;
8445
8446 } else if (R->FailureKind == ovl_fail_bad_conversion)
8447 return false;
8448
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008449 if (L->FailureKind == ovl_fail_bad_deduction) {
8450 if (R->FailureKind != ovl_fail_bad_deduction)
8451 return true;
8452
8453 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8454 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008455 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008456 } else if (R->FailureKind == ovl_fail_bad_deduction)
8457 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008458
John McCall3712d9e2010-01-15 23:32:50 +00008459 // TODO: others?
8460 }
8461
8462 // Sort everything else by location.
8463 SourceLocation LLoc = GetLocationForCandidate(L);
8464 SourceLocation RLoc = GetLocationForCandidate(R);
8465
8466 // Put candidates without locations (e.g. builtins) at the end.
8467 if (LLoc.isInvalid()) return false;
8468 if (RLoc.isInvalid()) return true;
8469
8470 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008471 }
8472};
8473
John McCallfe796dd2010-01-23 05:17:32 +00008474/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008475/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008476void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008477 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008478 assert(!Cand->Viable);
8479
8480 // Don't do anything on failures other than bad conversion.
8481 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8482
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008483 // We only want the FixIts if all the arguments can be corrected.
8484 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008485 // Use a implicit copy initialization to check conversion fixes.
8486 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008487
John McCallfe796dd2010-01-23 05:17:32 +00008488 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008489 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008490 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008491 while (true) {
8492 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8493 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008494 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008495 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008496 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008497 }
John McCallfe796dd2010-01-23 05:17:32 +00008498 }
8499
8500 if (ConvIdx == ConvCount)
8501 return;
8502
John McCall65eb8792010-02-25 01:37:24 +00008503 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8504 "remaining conversion is initialized?");
8505
Douglas Gregoradc7a702010-04-16 17:45:54 +00008506 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008507 // operation somehow.
8508 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008509
8510 const FunctionProtoType* Proto;
8511 unsigned ArgIdx = ConvIdx;
8512
8513 if (Cand->IsSurrogate) {
8514 QualType ConvType
8515 = Cand->Surrogate->getConversionType().getNonReferenceType();
8516 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8517 ConvType = ConvPtrType->getPointeeType();
8518 Proto = ConvType->getAs<FunctionProtoType>();
8519 ArgIdx--;
8520 } else if (Cand->Function) {
8521 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8522 if (isa<CXXMethodDecl>(Cand->Function) &&
8523 !isa<CXXConstructorDecl>(Cand->Function))
8524 ArgIdx--;
8525 } else {
8526 // Builtin binary operator with a bad first conversion.
8527 assert(ConvCount <= 3);
8528 for (; ConvIdx != ConvCount; ++ConvIdx)
8529 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008530 = TryCopyInitialization(S, Args[ConvIdx],
8531 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008532 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008533 /*InOverloadResolution*/ true,
8534 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008535 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008536 return;
8537 }
8538
8539 // Fill in the rest of the conversions.
8540 unsigned NumArgsInProto = Proto->getNumArgs();
8541 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008542 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008543 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008544 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008545 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008546 /*InOverloadResolution=*/true,
8547 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008548 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008549 // Store the FixIt in the candidate if it exists.
8550 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008551 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008552 }
John McCallfe796dd2010-01-23 05:17:32 +00008553 else
8554 Cand->Conversions[ConvIdx].setEllipsis();
8555 }
8556}
8557
John McCalld3224162010-01-08 00:58:21 +00008558} // end anonymous namespace
8559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008560/// PrintOverloadCandidates - When overload resolution fails, prints
8561/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008562/// set.
John McCall5c32be02010-08-24 20:38:10 +00008563void OverloadCandidateSet::NoteCandidates(Sema &S,
8564 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008565 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008566 const char *Opc,
8567 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008568 // Sort the candidates by viability and position. Sorting directly would
8569 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008570 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008571 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8572 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008573 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008574 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008575 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008576 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008577 if (Cand->Function || Cand->IsSurrogate)
8578 Cands.push_back(Cand);
8579 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8580 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008581 }
8582 }
8583
John McCallad2587a2010-01-12 00:48:53 +00008584 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008585 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008586
John McCall0d1da222010-01-12 00:44:57 +00008587 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008588
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008589 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008590 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8591 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008592 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008593 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8594 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008595
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008596 // Set an arbitrary limit on the number of candidate functions we'll spam
8597 // the user with. FIXME: This limit should depend on details of the
8598 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008599 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008600 break;
8601 }
8602 ++CandsShown;
8603
John McCalld3224162010-01-08 00:58:21 +00008604 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008605 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008606 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008607 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008608 else {
8609 assert(Cand->Viable &&
8610 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008611 // Generally we only see ambiguities including viable builtin
8612 // operators if overload resolution got screwed up by an
8613 // ambiguous user-defined conversion.
8614 //
8615 // FIXME: It's quite possible for different conversions to see
8616 // different ambiguities, though.
8617 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008618 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008619 ReportedAmbiguousConversions = true;
8620 }
John McCalld3224162010-01-08 00:58:21 +00008621
John McCall0d1da222010-01-12 00:44:57 +00008622 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008623 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008624 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008625 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008626
8627 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008628 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008629}
8630
Douglas Gregorb491ed32011-02-19 21:32:49 +00008631// [PossiblyAFunctionType] --> [Return]
8632// NonFunctionType --> NonFunctionType
8633// R (A) --> R(A)
8634// R (*)(A) --> R (A)
8635// R (&)(A) --> R (A)
8636// R (S::*)(A) --> R (A)
8637QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8638 QualType Ret = PossiblyAFunctionType;
8639 if (const PointerType *ToTypePtr =
8640 PossiblyAFunctionType->getAs<PointerType>())
8641 Ret = ToTypePtr->getPointeeType();
8642 else if (const ReferenceType *ToTypeRef =
8643 PossiblyAFunctionType->getAs<ReferenceType>())
8644 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008645 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008646 PossiblyAFunctionType->getAs<MemberPointerType>())
8647 Ret = MemTypePtr->getPointeeType();
8648 Ret =
8649 Context.getCanonicalType(Ret).getUnqualifiedType();
8650 return Ret;
8651}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008652
Douglas Gregorb491ed32011-02-19 21:32:49 +00008653// A helper class to help with address of function resolution
8654// - allows us to avoid passing around all those ugly parameters
8655class AddressOfFunctionResolver
8656{
8657 Sema& S;
8658 Expr* SourceExpr;
8659 const QualType& TargetType;
8660 QualType TargetFunctionType; // Extracted function type from target type
8661
8662 bool Complain;
8663 //DeclAccessPair& ResultFunctionAccessPair;
8664 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008665
Douglas Gregorb491ed32011-02-19 21:32:49 +00008666 bool TargetTypeIsNonStaticMemberFunction;
8667 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008668
Douglas Gregorb491ed32011-02-19 21:32:49 +00008669 OverloadExpr::FindResult OvlExprInfo;
8670 OverloadExpr *OvlExpr;
8671 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008672 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673
Douglas Gregorb491ed32011-02-19 21:32:49 +00008674public:
8675 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8676 const QualType& TargetType, bool Complain)
8677 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8678 Complain(Complain), Context(S.getASTContext()),
8679 TargetTypeIsNonStaticMemberFunction(
8680 !!TargetType->getAs<MemberPointerType>()),
8681 FoundNonTemplateFunction(false),
8682 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8683 OvlExpr(OvlExprInfo.Expression)
8684 {
8685 ExtractUnqualifiedFunctionTypeFromTargetType();
8686
8687 if (!TargetFunctionType->isFunctionType()) {
8688 if (OvlExpr->hasExplicitTemplateArgs()) {
8689 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008690 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008691 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008692
8693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8694 if (!Method->isStatic()) {
8695 // If the target type is a non-function type and the function
8696 // found is a non-static member function, pretend as if that was
8697 // the target, it's the only possible type to end up with.
8698 TargetTypeIsNonStaticMemberFunction = true;
8699
8700 // And skip adding the function if its not in the proper form.
8701 // We'll diagnose this due to an empty set of functions.
8702 if (!OvlExprInfo.HasFormOfMemberPointer)
8703 return;
8704 }
8705 }
8706
Douglas Gregorb491ed32011-02-19 21:32:49 +00008707 Matches.push_back(std::make_pair(dap,Fn));
8708 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008709 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008710 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008711 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008712
8713 if (OvlExpr->hasExplicitTemplateArgs())
8714 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008715
Douglas Gregorb491ed32011-02-19 21:32:49 +00008716 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8717 // C++ [over.over]p4:
8718 // If more than one function is selected, [...]
8719 if (Matches.size() > 1) {
8720 if (FoundNonTemplateFunction)
8721 EliminateAllTemplateMatches();
8722 else
8723 EliminateAllExceptMostSpecializedTemplate();
8724 }
8725 }
8726 }
8727
8728private:
8729 bool isTargetTypeAFunction() const {
8730 return TargetFunctionType->isFunctionType();
8731 }
8732
8733 // [ToType] [Return]
8734
8735 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8736 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8737 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8738 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8739 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8740 }
8741
8742 // return true if any matching specializations were found
8743 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8744 const DeclAccessPair& CurAccessFunPair) {
8745 if (CXXMethodDecl *Method
8746 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8747 // Skip non-static function templates when converting to pointer, and
8748 // static when converting to member pointer.
8749 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8750 return false;
8751 }
8752 else if (TargetTypeIsNonStaticMemberFunction)
8753 return false;
8754
8755 // C++ [over.over]p2:
8756 // If the name is a function template, template argument deduction is
8757 // done (14.8.2.2), and if the argument deduction succeeds, the
8758 // resulting template argument list is used to generate a single
8759 // function template specialization, which is added to the set of
8760 // overloaded functions considered.
8761 FunctionDecl *Specialization = 0;
8762 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8763 if (Sema::TemplateDeductionResult Result
8764 = S.DeduceTemplateArguments(FunctionTemplate,
8765 &OvlExplicitTemplateArgs,
8766 TargetFunctionType, Specialization,
8767 Info)) {
8768 // FIXME: make a note of the failed deduction for diagnostics.
8769 (void)Result;
8770 return false;
8771 }
8772
8773 // Template argument deduction ensures that we have an exact match.
8774 // This function template specicalization works.
8775 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8776 assert(TargetFunctionType
8777 == Context.getCanonicalType(Specialization->getType()));
8778 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8779 return true;
8780 }
8781
8782 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8783 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008784 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008785 // Skip non-static functions when converting to pointer, and static
8786 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008787 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8788 return false;
8789 }
8790 else if (TargetTypeIsNonStaticMemberFunction)
8791 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008792
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008793 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008794 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008795 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8796 if (S.CheckCUDATarget(Caller, FunDecl))
8797 return false;
8798
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008799 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008800 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8801 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008802 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8803 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008804 Matches.push_back(std::make_pair(CurAccessFunPair,
8805 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008806 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008807 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008808 }
Mike Stump11289f42009-09-09 15:08:12 +00008809 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008810
8811 return false;
8812 }
8813
8814 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8815 bool Ret = false;
8816
8817 // If the overload expression doesn't have the form of a pointer to
8818 // member, don't try to convert it to a pointer-to-member type.
8819 if (IsInvalidFormOfPointerToMemberFunction())
8820 return false;
8821
8822 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8823 E = OvlExpr->decls_end();
8824 I != E; ++I) {
8825 // Look through any using declarations to find the underlying function.
8826 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8827
8828 // C++ [over.over]p3:
8829 // Non-member functions and static member functions match
8830 // targets of type "pointer-to-function" or "reference-to-function."
8831 // Nonstatic member functions match targets of
8832 // type "pointer-to-member-function."
8833 // Note that according to DR 247, the containing class does not matter.
8834 if (FunctionTemplateDecl *FunctionTemplate
8835 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8836 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8837 Ret = true;
8838 }
8839 // If we have explicit template arguments supplied, skip non-templates.
8840 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8841 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8842 Ret = true;
8843 }
8844 assert(Ret || Matches.empty());
8845 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008846 }
8847
Douglas Gregorb491ed32011-02-19 21:32:49 +00008848 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008849 // [...] and any given function template specialization F1 is
8850 // eliminated if the set contains a second function template
8851 // specialization whose function template is more specialized
8852 // than the function template of F1 according to the partial
8853 // ordering rules of 14.5.5.2.
8854
8855 // The algorithm specified above is quadratic. We instead use a
8856 // two-pass algorithm (similar to the one used to identify the
8857 // best viable function in an overload set) that identifies the
8858 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008859
8860 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8861 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8862 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008863
John McCall58cc69d2010-01-27 01:50:18 +00008864 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008865 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8866 TPOC_Other, 0, SourceExpr->getLocStart(),
8867 S.PDiag(),
8868 S.PDiag(diag::err_addr_ovl_ambiguous)
8869 << Matches[0].second->getDeclName(),
8870 S.PDiag(diag::note_ovl_candidate)
8871 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008872 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008873
Douglas Gregorb491ed32011-02-19 21:32:49 +00008874 if (Result != MatchesCopy.end()) {
8875 // Make it the first and only element
8876 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8877 Matches[0].second = cast<FunctionDecl>(*Result);
8878 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008879 }
8880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008881
Douglas Gregorb491ed32011-02-19 21:32:49 +00008882 void EliminateAllTemplateMatches() {
8883 // [...] any function template specializations in the set are
8884 // eliminated if the set also contains a non-template function, [...]
8885 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8886 if (Matches[I].second->getPrimaryTemplate() == 0)
8887 ++I;
8888 else {
8889 Matches[I] = Matches[--N];
8890 Matches.set_size(N);
8891 }
8892 }
8893 }
8894
8895public:
8896 void ComplainNoMatchesFound() const {
8897 assert(Matches.empty());
8898 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8899 << OvlExpr->getName() << TargetFunctionType
8900 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008901 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008902 }
8903
8904 bool IsInvalidFormOfPointerToMemberFunction() const {
8905 return TargetTypeIsNonStaticMemberFunction &&
8906 !OvlExprInfo.HasFormOfMemberPointer;
8907 }
8908
8909 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8910 // TODO: Should we condition this on whether any functions might
8911 // have matched, or is it more appropriate to do that in callers?
8912 // TODO: a fixit wouldn't hurt.
8913 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8914 << TargetType << OvlExpr->getSourceRange();
8915 }
8916
8917 void ComplainOfInvalidConversion() const {
8918 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8919 << OvlExpr->getName() << TargetType;
8920 }
8921
8922 void ComplainMultipleMatchesFound() const {
8923 assert(Matches.size() > 1);
8924 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8925 << OvlExpr->getName()
8926 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008927 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008928 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008929
8930 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8931
Douglas Gregorb491ed32011-02-19 21:32:49 +00008932 int getNumMatches() const { return Matches.size(); }
8933
8934 FunctionDecl* getMatchingFunctionDecl() const {
8935 if (Matches.size() != 1) return 0;
8936 return Matches[0].second;
8937 }
8938
8939 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8940 if (Matches.size() != 1) return 0;
8941 return &Matches[0].first;
8942 }
8943};
8944
8945/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8946/// an overloaded function (C++ [over.over]), where @p From is an
8947/// expression with overloaded function type and @p ToType is the type
8948/// we're trying to resolve to. For example:
8949///
8950/// @code
8951/// int f(double);
8952/// int f(int);
8953///
8954/// int (*pfd)(double) = f; // selects f(double)
8955/// @endcode
8956///
8957/// This routine returns the resulting FunctionDecl if it could be
8958/// resolved, and NULL otherwise. When @p Complain is true, this
8959/// routine will emit diagnostics if there is an error.
8960FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008961Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8962 QualType TargetType,
8963 bool Complain,
8964 DeclAccessPair &FoundResult,
8965 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008966 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008967
8968 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8969 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008970 int NumMatches = Resolver.getNumMatches();
8971 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008972 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008973 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8974 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8975 else
8976 Resolver.ComplainNoMatchesFound();
8977 }
8978 else if (NumMatches > 1 && Complain)
8979 Resolver.ComplainMultipleMatchesFound();
8980 else if (NumMatches == 1) {
8981 Fn = Resolver.getMatchingFunctionDecl();
8982 assert(Fn);
8983 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00008984 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008985 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008986 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008987 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008988
8989 if (pHadMultipleCandidates)
8990 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008991 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008992}
8993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008994/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008995/// resolve that overloaded function expression down to a single function.
8996///
8997/// This routine can only resolve template-ids that refer to a single function
8998/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008999/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009000/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009001FunctionDecl *
9002Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9003 bool Complain,
9004 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009005 // C++ [over.over]p1:
9006 // [...] [Note: any redundant set of parentheses surrounding the
9007 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009008 // C++ [over.over]p1:
9009 // [...] The overloaded function name can be preceded by the &
9010 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009011
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009012 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009013 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009014 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009015
9016 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009017 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009018
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009019 // Look through all of the overloaded functions, searching for one
9020 // whose type matches exactly.
9021 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009022 for (UnresolvedSetIterator I = ovl->decls_begin(),
9023 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009024 // C++0x [temp.arg.explicit]p3:
9025 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009026 // where deduction is not done, if a template argument list is
9027 // specified and it, along with any default template arguments,
9028 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009029 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009030 FunctionTemplateDecl *FunctionTemplate
9031 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009032
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009033 // C++ [over.over]p2:
9034 // If the name is a function template, template argument deduction is
9035 // done (14.8.2.2), and if the argument deduction succeeds, the
9036 // resulting template argument list is used to generate a single
9037 // function template specialization, which is added to the set of
9038 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009039 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009040 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009041 if (TemplateDeductionResult Result
9042 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9043 Specialization, Info)) {
9044 // FIXME: make a note of the failed deduction for diagnostics.
9045 (void)Result;
9046 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009047 }
9048
John McCall0009fcc2011-04-26 20:42:42 +00009049 assert(Specialization && "no specialization and no error?");
9050
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009051 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009052 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009053 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009054 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9055 << ovl->getName();
9056 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009057 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009058 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009059 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009060
John McCall0009fcc2011-04-26 20:42:42 +00009061 Matched = Specialization;
9062 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009064
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009065 return Matched;
9066}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067
Douglas Gregor1beec452011-03-12 01:48:56 +00009068
9069
9070
John McCall50a2c2c2011-10-11 23:14:30 +00009071// Resolve and fix an overloaded expression that can be resolved
9072// because it identifies a single function template specialization.
9073//
Douglas Gregor1beec452011-03-12 01:48:56 +00009074// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009075//
9076// Return true if it was logically possible to so resolve the
9077// expression, regardless of whether or not it succeeded. Always
9078// returns true if 'complain' is set.
9079bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9080 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9081 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009082 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009083 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009084 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009085
John McCall50a2c2c2011-10-11 23:14:30 +00009086 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009087
John McCall0009fcc2011-04-26 20:42:42 +00009088 DeclAccessPair found;
9089 ExprResult SingleFunctionExpression;
9090 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9091 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009092 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009093 SrcExpr = ExprError();
9094 return true;
9095 }
John McCall0009fcc2011-04-26 20:42:42 +00009096
9097 // It is only correct to resolve to an instance method if we're
9098 // resolving a form that's permitted to be a pointer to member.
9099 // Otherwise we'll end up making a bound member expression, which
9100 // is illegal in all the contexts we resolve like this.
9101 if (!ovl.HasFormOfMemberPointer &&
9102 isa<CXXMethodDecl>(fn) &&
9103 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009104 if (!complain) return false;
9105
9106 Diag(ovl.Expression->getExprLoc(),
9107 diag::err_bound_member_function)
9108 << 0 << ovl.Expression->getSourceRange();
9109
9110 // TODO: I believe we only end up here if there's a mix of
9111 // static and non-static candidates (otherwise the expression
9112 // would have 'bound member' type, not 'overload' type).
9113 // Ideally we would note which candidate was chosen and why
9114 // the static candidates were rejected.
9115 SrcExpr = ExprError();
9116 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009117 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009118
John McCall0009fcc2011-04-26 20:42:42 +00009119 // Fix the expresion to refer to 'fn'.
9120 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009121 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009122
9123 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009124 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009125 SingleFunctionExpression =
9126 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009127 if (SingleFunctionExpression.isInvalid()) {
9128 SrcExpr = ExprError();
9129 return true;
9130 }
9131 }
John McCall0009fcc2011-04-26 20:42:42 +00009132 }
9133
9134 if (!SingleFunctionExpression.isUsable()) {
9135 if (complain) {
9136 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9137 << ovl.Expression->getName()
9138 << DestTypeForComplaining
9139 << OpRangeForComplaining
9140 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009141 NoteAllOverloadCandidates(SrcExpr.get());
9142
9143 SrcExpr = ExprError();
9144 return true;
9145 }
9146
9147 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009148 }
9149
John McCall50a2c2c2011-10-11 23:14:30 +00009150 SrcExpr = SingleFunctionExpression;
9151 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009152}
9153
Douglas Gregorcabea402009-09-22 15:41:20 +00009154/// \brief Add a single candidate to the overload set.
9155static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009156 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009157 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009158 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009159 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009160 bool PartialOverloading,
9161 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009162 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009163 if (isa<UsingShadowDecl>(Callee))
9164 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9165
Douglas Gregorcabea402009-09-22 15:41:20 +00009166 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009167 if (ExplicitTemplateArgs) {
9168 assert(!KnownValid && "Explicit template arguments?");
9169 return;
9170 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009171 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9172 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009173 return;
John McCalld14a8642009-11-21 08:51:07 +00009174 }
9175
9176 if (FunctionTemplateDecl *FuncTemplate
9177 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009178 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009179 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009180 return;
9181 }
9182
Richard Smith95ce4f62011-06-26 22:19:54 +00009183 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009184}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009185
Douglas Gregorcabea402009-09-22 15:41:20 +00009186/// \brief Add the overload candidates named by callee and/or found by argument
9187/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009188void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009189 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009190 OverloadCandidateSet &CandidateSet,
9191 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009192
9193#ifndef NDEBUG
9194 // Verify that ArgumentDependentLookup is consistent with the rules
9195 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009196 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009197 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9198 // and let Y be the lookup set produced by argument dependent
9199 // lookup (defined as follows). If X contains
9200 //
9201 // -- a declaration of a class member, or
9202 //
9203 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009204 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009205 //
9206 // -- a declaration that is neither a function or a function
9207 // template
9208 //
9209 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009210
John McCall57500772009-12-16 12:17:52 +00009211 if (ULE->requiresADL()) {
9212 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9213 E = ULE->decls_end(); I != E; ++I) {
9214 assert(!(*I)->getDeclContext()->isRecord());
9215 assert(isa<UsingShadowDecl>(*I) ||
9216 !(*I)->getDeclContext()->isFunctionOrMethod());
9217 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009218 }
9219 }
9220#endif
9221
John McCall57500772009-12-16 12:17:52 +00009222 // It would be nice to avoid this copy.
9223 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009224 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009225 if (ULE->hasExplicitTemplateArgs()) {
9226 ULE->copyTemplateArgumentsInto(TABuffer);
9227 ExplicitTemplateArgs = &TABuffer;
9228 }
9229
9230 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9231 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009232 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9233 CandidateSet, PartialOverloading,
9234 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009235
John McCall57500772009-12-16 12:17:52 +00009236 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009237 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009238 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009239 Args, ExplicitTemplateArgs,
9240 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009241 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009242}
John McCalld681c392009-12-16 08:11:27 +00009243
Richard Smith998a5912011-06-05 22:42:48 +00009244/// Attempt to recover from an ill-formed use of a non-dependent name in a
9245/// template, where the non-dependent name was declared after the template
9246/// was defined. This is common in code written for a compilers which do not
9247/// correctly implement two-stage name lookup.
9248///
9249/// Returns true if a viable candidate was found and a diagnostic was issued.
9250static bool
9251DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9252 const CXXScopeSpec &SS, LookupResult &R,
9253 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009254 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009255 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9256 return false;
9257
9258 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009259 if (DC->isTransparentContext())
9260 continue;
9261
Richard Smith998a5912011-06-05 22:42:48 +00009262 SemaRef.LookupQualifiedName(R, DC);
9263
9264 if (!R.empty()) {
9265 R.suppressDiagnostics();
9266
9267 if (isa<CXXRecordDecl>(DC)) {
9268 // Don't diagnose names we find in classes; we get much better
9269 // diagnostics for these from DiagnoseEmptyLookup.
9270 R.clear();
9271 return false;
9272 }
9273
9274 OverloadCandidateSet Candidates(FnLoc);
9275 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9276 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009277 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009278 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009279
9280 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009281 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009282 // No viable functions. Don't bother the user with notes for functions
9283 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009284 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009285 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009286 }
Richard Smith998a5912011-06-05 22:42:48 +00009287
9288 // Find the namespaces where ADL would have looked, and suggest
9289 // declaring the function there instead.
9290 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9291 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009292 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009293 AssociatedNamespaces,
9294 AssociatedClasses);
9295 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009296 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009297 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009298 for (Sema::AssociatedNamespaceSet::iterator
9299 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009300 end = AssociatedNamespaces.end(); it != end; ++it) {
9301 if (!Std->Encloses(*it))
9302 SuggestedNamespaces.insert(*it);
9303 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009304 } else {
9305 // Lacking the 'std::' namespace, use all of the associated namespaces.
9306 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009307 }
9308
9309 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9310 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009311 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009312 SemaRef.Diag(Best->Function->getLocation(),
9313 diag::note_not_found_by_two_phase_lookup)
9314 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009315 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009316 SemaRef.Diag(Best->Function->getLocation(),
9317 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009318 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009319 } else {
9320 // FIXME: It would be useful to list the associated namespaces here,
9321 // but the diagnostics infrastructure doesn't provide a way to produce
9322 // a localized representation of a list of items.
9323 SemaRef.Diag(Best->Function->getLocation(),
9324 diag::note_not_found_by_two_phase_lookup)
9325 << R.getLookupName() << 2;
9326 }
9327
9328 // Try to recover by calling this function.
9329 return true;
9330 }
9331
9332 R.clear();
9333 }
9334
9335 return false;
9336}
9337
9338/// Attempt to recover from ill-formed use of a non-dependent operator in a
9339/// template, where the non-dependent operator was declared after the template
9340/// was defined.
9341///
9342/// Returns true if a viable candidate was found and a diagnostic was issued.
9343static bool
9344DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9345 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009346 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009347 DeclarationName OpName =
9348 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9349 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9350 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009351 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009352}
9353
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009354namespace {
9355// Callback to limit the allowed keywords and to only accept typo corrections
9356// that are keywords or whose decls refer to functions (or template functions)
9357// that accept the given number of arguments.
9358class RecoveryCallCCC : public CorrectionCandidateCallback {
9359 public:
9360 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9361 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009362 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009363 WantRemainingKeywords = false;
9364 }
9365
9366 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9367 if (!candidate.getCorrectionDecl())
9368 return candidate.isKeyword();
9369
9370 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9371 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9372 FunctionDecl *FD = 0;
9373 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9374 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9375 FD = FTD->getTemplatedDecl();
9376 if (!HasExplicitTemplateArgs && !FD) {
9377 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9378 // If the Decl is neither a function nor a template function,
9379 // determine if it is a pointer or reference to a function. If so,
9380 // check against the number of arguments expected for the pointee.
9381 QualType ValType = cast<ValueDecl>(ND)->getType();
9382 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9383 ValType = ValType->getPointeeType();
9384 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9385 if (FPT->getNumArgs() == NumArgs)
9386 return true;
9387 }
9388 }
9389 if (FD && FD->getNumParams() >= NumArgs &&
9390 FD->getMinRequiredArguments() <= NumArgs)
9391 return true;
9392 }
9393 return false;
9394 }
9395
9396 private:
9397 unsigned NumArgs;
9398 bool HasExplicitTemplateArgs;
9399};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009400
9401// Callback that effectively disabled typo correction
9402class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9403 public:
9404 NoTypoCorrectionCCC() {
9405 WantTypeSpecifiers = false;
9406 WantExpressionKeywords = false;
9407 WantCXXNamedCasts = false;
9408 WantRemainingKeywords = false;
9409 }
9410
9411 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9412 return false;
9413 }
9414};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009415}
9416
John McCalld681c392009-12-16 08:11:27 +00009417/// Attempts to recover from a call where no functions were found.
9418///
9419/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009420static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009421BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009422 UnresolvedLookupExpr *ULE,
9423 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009424 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009425 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009426 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009427
9428 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009429 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009430 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009431
John McCall57500772009-12-16 12:17:52 +00009432 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009433 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009434 if (ULE->hasExplicitTemplateArgs()) {
9435 ULE->copyTemplateArgumentsInto(TABuffer);
9436 ExplicitTemplateArgs = &TABuffer;
9437 }
9438
John McCalld681c392009-12-16 08:11:27 +00009439 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9440 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009441 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009442 NoTypoCorrectionCCC RejectAll;
9443 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9444 (CorrectionCandidateCallback*)&Validator :
9445 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009446 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009447 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009448 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009449 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009450 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009451 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009452
John McCall57500772009-12-16 12:17:52 +00009453 assert(!R.empty() && "lookup results empty despite recovery");
9454
9455 // Build an implicit member call if appropriate. Just drop the
9456 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009457 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009458 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009459 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9460 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009461 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009462 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009463 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009464 else
9465 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9466
9467 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009468 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009469
9470 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009471 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009472 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009473 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009474 MultiExprArg(Args.data(), Args.size()),
9475 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009476}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009477
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009478/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009479/// (which eventually refers to the declaration Func) and the call
9480/// arguments Args/NumArgs, attempt to resolve the function call down
9481/// to a specific function. If overload resolution succeeds, returns
9482/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009483/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009484/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009485ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009486Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009487 SourceLocation LParenLoc,
9488 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009489 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009490 Expr *ExecConfig,
9491 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009492#ifndef NDEBUG
9493 if (ULE->requiresADL()) {
9494 // To do ADL, we must have found an unqualified name.
9495 assert(!ULE->getQualifier() && "qualified name with ADL");
9496
9497 // We don't perform ADL for implicit declarations of builtins.
9498 // Verify that this was correctly set up.
9499 FunctionDecl *F;
9500 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9501 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9502 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009503 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009504
John McCall57500772009-12-16 12:17:52 +00009505 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009506 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009507 } else
9508 assert(!ULE->isStdAssociatedNamespace() &&
9509 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009510#endif
9511
John McCall4124c492011-10-17 18:40:02 +00009512 UnbridgedCastsSet UnbridgedCasts;
9513 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9514 return ExprError();
9515
John McCallbc077cf2010-02-08 23:07:23 +00009516 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009517
John McCall57500772009-12-16 12:17:52 +00009518 // Add the functions denoted by the callee to the set of candidate
9519 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009520 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9521 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009522
9523 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009524 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9525 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009526 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009527 // In Microsoft mode, if we are inside a template class member function then
9528 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009529 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009530 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009531 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009532 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009533 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9534 Context.DependentTy, VK_RValue,
9535 RParenLoc);
9536 CE->setTypeDependent(true);
9537 return Owned(CE);
9538 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009539 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9540 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009541 RParenLoc, /*EmptyLookup=*/true,
9542 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009543 }
John McCalld681c392009-12-16 08:11:27 +00009544
John McCall4124c492011-10-17 18:40:02 +00009545 UnbridgedCasts.restore();
9546
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009547 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009548 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009549 case OR_Success: {
9550 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009551 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009552 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009553 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009554 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009555 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9556 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009557 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009558
Richard Smith998a5912011-06-05 22:42:48 +00009559 case OR_No_Viable_Function: {
9560 // Try to recover by looking for viable functions which the user might
9561 // have meant to call.
9562 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009563 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9564 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009565 /*EmptyLookup=*/false,
9566 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009567 if (!Recovery.isInvalid())
9568 return Recovery;
9569
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009570 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009571 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009572 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009573 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9574 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009575 break;
Richard Smith998a5912011-06-05 22:42:48 +00009576 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009577
9578 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009579 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009580 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009581 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9582 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009583 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009584
9585 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009586 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009587 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009588 << Best->Function->isDeleted()
9589 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009590 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009591 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009592 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9593 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009594
9595 // We emitted an error for the unvailable/deleted function call but keep
9596 // the call in the AST.
9597 FunctionDecl *FDecl = Best->Function;
9598 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9599 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9600 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009601 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009602 }
9603
Douglas Gregorb412e172010-07-25 18:17:45 +00009604 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009605 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009606}
9607
John McCall4c4c1df2010-01-26 03:27:55 +00009608static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009609 return Functions.size() > 1 ||
9610 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9611}
9612
Douglas Gregor084d8552009-03-13 23:49:33 +00009613/// \brief Create a unary operation that may resolve to an overloaded
9614/// operator.
9615///
9616/// \param OpLoc The location of the operator itself (e.g., '*').
9617///
9618/// \param OpcIn The UnaryOperator::Opcode that describes this
9619/// operator.
9620///
9621/// \param Functions The set of non-member functions that will be
9622/// considered by overload resolution. The caller needs to build this
9623/// set based on the context using, e.g.,
9624/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9625/// set should not contain any member functions; those will be added
9626/// by CreateOverloadedUnaryOp().
9627///
9628/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009629ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009630Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9631 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009632 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009633 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009634
9635 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9636 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9637 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009638 // TODO: provide better source location info.
9639 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009640
John McCall4124c492011-10-17 18:40:02 +00009641 if (checkPlaceholderForOverload(*this, Input))
9642 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009643
Douglas Gregor084d8552009-03-13 23:49:33 +00009644 Expr *Args[2] = { Input, 0 };
9645 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009646
Douglas Gregor084d8552009-03-13 23:49:33 +00009647 // For post-increment and post-decrement, add the implicit '0' as
9648 // the second argument, so that we know this is a post-increment or
9649 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009650 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009651 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009652 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9653 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009654 NumArgs = 2;
9655 }
9656
9657 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009658 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009659 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009660 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009661 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009662 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009663 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009664
John McCall58cc69d2010-01-27 01:50:18 +00009665 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009666 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009667 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009668 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009669 /*ADL*/ true, IsOverloaded(Fns),
9670 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009671 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009672 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009673 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009674 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009675 OpLoc));
9676 }
9677
9678 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009679 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009680
9681 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009682 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9683 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009684
9685 // Add operator candidates that are member functions.
9686 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9687
John McCall4c4c1df2010-01-26 03:27:55 +00009688 // Add candidates from ADL.
9689 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009690 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009691 /*ExplicitTemplateArgs*/ 0,
9692 CandidateSet);
9693
Douglas Gregor084d8552009-03-13 23:49:33 +00009694 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009695 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009696
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009697 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9698
Douglas Gregor084d8552009-03-13 23:49:33 +00009699 // Perform overload resolution.
9700 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009701 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009702 case OR_Success: {
9703 // We found a built-in operator or an overloaded operator.
9704 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009705
Douglas Gregor084d8552009-03-13 23:49:33 +00009706 if (FnDecl) {
9707 // We matched an overloaded operator. Build a call to that
9708 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009709
Eli Friedmanfa0df832012-02-02 03:46:19 +00009710 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009711
Douglas Gregor084d8552009-03-13 23:49:33 +00009712 // Convert the arguments.
9713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009714 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009715
John Wiegley01296292011-04-08 18:41:53 +00009716 ExprResult InputRes =
9717 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9718 Best->FoundDecl, Method);
9719 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009720 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009721 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009722 } else {
9723 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009724 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009725 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009726 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009727 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009728 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009729 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009730 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009731 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009732 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009733 }
9734
John McCall4fa0d5f2010-05-06 18:15:07 +00009735 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9736
John McCall7decc9e2010-11-18 06:31:45 +00009737 // Determine the result type.
9738 QualType ResultTy = FnDecl->getResultType();
9739 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9740 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009741
Douglas Gregor084d8552009-03-13 23:49:33 +00009742 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009743 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009744 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009745 if (FnExpr.isInvalid())
9746 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009747
Eli Friedman030eee42009-11-18 03:58:17 +00009748 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009749 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009750 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009751 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009753 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009754 FnDecl))
9755 return ExprError();
9756
John McCallb268a282010-08-23 23:25:46 +00009757 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009758 } else {
9759 // We matched a built-in operator. Convert the arguments, then
9760 // break out so that we will build the appropriate built-in
9761 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009762 ExprResult InputRes =
9763 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9764 Best->Conversions[0], AA_Passing);
9765 if (InputRes.isInvalid())
9766 return ExprError();
9767 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009768 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009769 }
John Wiegley01296292011-04-08 18:41:53 +00009770 }
9771
9772 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009773 // This is an erroneous use of an operator which can be overloaded by
9774 // a non-member function. Check for non-member operators which were
9775 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009776 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9777 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009778 // FIXME: Recover by calling the found function.
9779 return ExprError();
9780
John Wiegley01296292011-04-08 18:41:53 +00009781 // No viable function; fall through to handling this as a
9782 // built-in operator, which will produce an error message for us.
9783 break;
9784
9785 case OR_Ambiguous:
9786 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9787 << UnaryOperator::getOpcodeStr(Opc)
9788 << Input->getType()
9789 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009790 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9791 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009792 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9793 return ExprError();
9794
9795 case OR_Deleted:
9796 Diag(OpLoc, diag::err_ovl_deleted_oper)
9797 << Best->Function->isDeleted()
9798 << UnaryOperator::getOpcodeStr(Opc)
9799 << getDeletedOrUnavailableSuffix(Best->Function)
9800 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009801 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9802 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009803 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009804 return ExprError();
9805 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009806
9807 // Either we found no viable overloaded operator or we matched a
9808 // built-in operator. In either case, fall through to trying to
9809 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009810 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009811}
9812
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009813/// \brief Create a binary operation that may resolve to an overloaded
9814/// operator.
9815///
9816/// \param OpLoc The location of the operator itself (e.g., '+').
9817///
9818/// \param OpcIn The BinaryOperator::Opcode that describes this
9819/// operator.
9820///
9821/// \param Functions The set of non-member functions that will be
9822/// considered by overload resolution. The caller needs to build this
9823/// set based on the context using, e.g.,
9824/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9825/// set should not contain any member functions; those will be added
9826/// by CreateOverloadedBinOp().
9827///
9828/// \param LHS Left-hand argument.
9829/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009830ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009831Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009832 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009833 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009834 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009835 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009836 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009837
9838 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9839 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9840 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9841
9842 // If either side is type-dependent, create an appropriate dependent
9843 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009844 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009845 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009846 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009847 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009848 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009849 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009850 Context.DependentTy,
9851 VK_RValue, OK_Ordinary,
9852 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009853
Douglas Gregor5287f092009-11-05 00:51:44 +00009854 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9855 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009856 VK_LValue,
9857 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009858 Context.DependentTy,
9859 Context.DependentTy,
9860 OpLoc));
9861 }
John McCall4c4c1df2010-01-26 03:27:55 +00009862
9863 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009864 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009865 // TODO: provide better source location info in DNLoc component.
9866 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009867 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009868 = UnresolvedLookupExpr::Create(Context, NamingClass,
9869 NestedNameSpecifierLoc(), OpNameInfo,
9870 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009871 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009872 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009873 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009874 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009875 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009876 OpLoc));
9877 }
9878
John McCall4124c492011-10-17 18:40:02 +00009879 // Always do placeholder-like conversions on the RHS.
9880 if (checkPlaceholderForOverload(*this, Args[1]))
9881 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009882
John McCall526ab472011-10-25 17:37:35 +00009883 // Do placeholder-like conversion on the LHS; note that we should
9884 // not get here with a PseudoObject LHS.
9885 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009886 if (checkPlaceholderForOverload(*this, Args[0]))
9887 return ExprError();
9888
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009889 // If this is the assignment operator, we only perform overload resolution
9890 // if the left-hand side is a class or enumeration type. This is actually
9891 // a hack. The standard requires that we do overload resolution between the
9892 // various built-in candidates, but as DR507 points out, this can lead to
9893 // problems. So we do it this way, which pretty much follows what GCC does.
9894 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009895 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009896 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009897
John McCalle26a8722010-12-04 08:14:53 +00009898 // If this is the .* operator, which is not overloadable, just
9899 // create a built-in binary operator.
9900 if (Opc == BO_PtrMemD)
9901 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9902
Douglas Gregor084d8552009-03-13 23:49:33 +00009903 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009904 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009905
9906 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009907 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009908
9909 // Add operator candidates that are member functions.
9910 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9911
John McCall4c4c1df2010-01-26 03:27:55 +00009912 // Add candidates from ADL.
9913 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009914 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +00009915 /*ExplicitTemplateArgs*/ 0,
9916 CandidateSet);
9917
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009918 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009919 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009920
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009921 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9922
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009923 // Perform overload resolution.
9924 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009925 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009926 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009927 // We found a built-in operator or an overloaded operator.
9928 FunctionDecl *FnDecl = Best->Function;
9929
9930 if (FnDecl) {
9931 // We matched an overloaded operator. Build a call to that
9932 // operator.
9933
Eli Friedmanfa0df832012-02-02 03:46:19 +00009934 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009935
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009936 // Convert the arguments.
9937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009938 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009939 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009940
Chandler Carruth8e543b32010-12-12 08:17:55 +00009941 ExprResult Arg1 =
9942 PerformCopyInitialization(
9943 InitializedEntity::InitializeParameter(Context,
9944 FnDecl->getParamDecl(0)),
9945 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009946 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009947 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009948
John Wiegley01296292011-04-08 18:41:53 +00009949 ExprResult Arg0 =
9950 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9951 Best->FoundDecl, Method);
9952 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009953 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009954 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009955 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009956 } else {
9957 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009958 ExprResult Arg0 = PerformCopyInitialization(
9959 InitializedEntity::InitializeParameter(Context,
9960 FnDecl->getParamDecl(0)),
9961 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009962 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009963 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009964
Chandler Carruth8e543b32010-12-12 08:17:55 +00009965 ExprResult Arg1 =
9966 PerformCopyInitialization(
9967 InitializedEntity::InitializeParameter(Context,
9968 FnDecl->getParamDecl(1)),
9969 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009970 if (Arg1.isInvalid())
9971 return ExprError();
9972 Args[0] = LHS = Arg0.takeAs<Expr>();
9973 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009974 }
9975
John McCall4fa0d5f2010-05-06 18:15:07 +00009976 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9977
John McCall7decc9e2010-11-18 06:31:45 +00009978 // Determine the result type.
9979 QualType ResultTy = FnDecl->getResultType();
9980 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9981 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009982
9983 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009984 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9985 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009986 if (FnExpr.isInvalid())
9987 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009988
John McCallb268a282010-08-23 23:25:46 +00009989 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009990 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009991 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009992
9993 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009994 FnDecl))
9995 return ExprError();
9996
John McCallb268a282010-08-23 23:25:46 +00009997 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009998 } else {
9999 // We matched a built-in operator. Convert the arguments, then
10000 // break out so that we will build the appropriate built-in
10001 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010002 ExprResult ArgsRes0 =
10003 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10004 Best->Conversions[0], AA_Passing);
10005 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010006 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010007 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010008
John Wiegley01296292011-04-08 18:41:53 +000010009 ExprResult ArgsRes1 =
10010 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10011 Best->Conversions[1], AA_Passing);
10012 if (ArgsRes1.isInvalid())
10013 return ExprError();
10014 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010015 break;
10016 }
10017 }
10018
Douglas Gregor66950a32009-09-30 21:46:01 +000010019 case OR_No_Viable_Function: {
10020 // C++ [over.match.oper]p9:
10021 // If the operator is the operator , [...] and there are no
10022 // viable functions, then the operator is assumed to be the
10023 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010024 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010025 break;
10026
Chandler Carruth8e543b32010-12-12 08:17:55 +000010027 // For class as left operand for assignment or compound assigment
10028 // operator do not fall through to handling in built-in, but report that
10029 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010030 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010031 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010032 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010033 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10034 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010035 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010036 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010037 // This is an erroneous use of an operator which can be overloaded by
10038 // a non-member function. Check for non-member operators which were
10039 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010040 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010041 // FIXME: Recover by calling the found function.
10042 return ExprError();
10043
Douglas Gregor66950a32009-09-30 21:46:01 +000010044 // No viable function; try to create a built-in operation, which will
10045 // produce an error. Then, show the non-viable candidates.
10046 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010048 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010049 "C++ binary operator overloading is missing candidates!");
10050 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010051 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010052 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010053 return move(Result);
10054 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010055
10056 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010057 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010058 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010059 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010060 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010061 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010062 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010063 return ExprError();
10064
10065 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010066 if (isImplicitlyDeleted(Best->Function)) {
10067 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10068 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10069 << getSpecialMember(Method)
10070 << BinaryOperator::getOpcodeStr(Opc)
10071 << getDeletedOrUnavailableSuffix(Best->Function);
10072
10073 if (Method->getParent()->isLambda()) {
10074 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
10075 return ExprError();
10076 }
10077 } else {
10078 Diag(OpLoc, diag::err_ovl_deleted_oper)
10079 << Best->Function->isDeleted()
10080 << BinaryOperator::getOpcodeStr(Opc)
10081 << getDeletedOrUnavailableSuffix(Best->Function)
10082 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10083 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010084 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010085 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010086 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010087 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010088
Douglas Gregor66950a32009-09-30 21:46:01 +000010089 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010090 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010091}
10092
John McCalldadc5752010-08-24 06:29:42 +000010093ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010094Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10095 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010096 Expr *Base, Expr *Idx) {
10097 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010098 DeclarationName OpName =
10099 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10100
10101 // If either side is type-dependent, create an appropriate dependent
10102 // expression.
10103 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10104
John McCall58cc69d2010-01-27 01:50:18 +000010105 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010106 // CHECKME: no 'operator' keyword?
10107 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10108 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010109 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010110 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010111 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010112 /*ADL*/ true, /*Overloaded*/ false,
10113 UnresolvedSetIterator(),
10114 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010115 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010116
Sebastian Redladba46e2009-10-29 20:17:01 +000010117 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10118 Args, 2,
10119 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010120 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010121 RLoc));
10122 }
10123
John McCall4124c492011-10-17 18:40:02 +000010124 // Handle placeholders on both operands.
10125 if (checkPlaceholderForOverload(*this, Args[0]))
10126 return ExprError();
10127 if (checkPlaceholderForOverload(*this, Args[1]))
10128 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010129
Sebastian Redladba46e2009-10-29 20:17:01 +000010130 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010131 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010132
10133 // Subscript can only be overloaded as a member function.
10134
10135 // Add operator candidates that are member functions.
10136 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10137
10138 // Add builtin operator candidates.
10139 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10140
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010141 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10142
Sebastian Redladba46e2009-10-29 20:17:01 +000010143 // Perform overload resolution.
10144 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010145 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010146 case OR_Success: {
10147 // We found a built-in operator or an overloaded operator.
10148 FunctionDecl *FnDecl = Best->Function;
10149
10150 if (FnDecl) {
10151 // We matched an overloaded operator. Build a call to that
10152 // operator.
10153
Eli Friedmanfa0df832012-02-02 03:46:19 +000010154 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010155
John McCalla0296f72010-03-19 07:35:19 +000010156 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010157 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010158
Sebastian Redladba46e2009-10-29 20:17:01 +000010159 // Convert the arguments.
10160 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010161 ExprResult Arg0 =
10162 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10163 Best->FoundDecl, Method);
10164 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010165 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010166 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010167
Anders Carlssona68e51e2010-01-29 18:37:50 +000010168 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010169 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010170 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010171 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010172 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010173 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010174 Owned(Args[1]));
10175 if (InputInit.isInvalid())
10176 return ExprError();
10177
10178 Args[1] = InputInit.takeAs<Expr>();
10179
Sebastian Redladba46e2009-10-29 20:17:01 +000010180 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010181 QualType ResultTy = FnDecl->getResultType();
10182 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10183 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010184
10185 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010186 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10187 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010188 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10189 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010190 OpLocInfo.getLoc(),
10191 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010192 if (FnExpr.isInvalid())
10193 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010194
John McCallb268a282010-08-23 23:25:46 +000010195 CXXOperatorCallExpr *TheCall =
10196 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010197 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010198 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010199
John McCallb268a282010-08-23 23:25:46 +000010200 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010201 FnDecl))
10202 return ExprError();
10203
John McCallb268a282010-08-23 23:25:46 +000010204 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010205 } else {
10206 // We matched a built-in operator. Convert the arguments, then
10207 // break out so that we will build the appropriate built-in
10208 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010209 ExprResult ArgsRes0 =
10210 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10211 Best->Conversions[0], AA_Passing);
10212 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010213 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010214 Args[0] = ArgsRes0.take();
10215
10216 ExprResult ArgsRes1 =
10217 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10218 Best->Conversions[1], AA_Passing);
10219 if (ArgsRes1.isInvalid())
10220 return ExprError();
10221 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010222
10223 break;
10224 }
10225 }
10226
10227 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010228 if (CandidateSet.empty())
10229 Diag(LLoc, diag::err_ovl_no_oper)
10230 << Args[0]->getType() << /*subscript*/ 0
10231 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10232 else
10233 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10234 << Args[0]->getType()
10235 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010236 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010237 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010238 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010239 }
10240
10241 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010242 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010243 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010244 << Args[0]->getType() << Args[1]->getType()
10245 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010246 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010247 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010248 return ExprError();
10249
10250 case OR_Deleted:
10251 Diag(LLoc, diag::err_ovl_deleted_oper)
10252 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010253 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010254 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010256 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010257 return ExprError();
10258 }
10259
10260 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010261 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010262}
10263
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010264/// BuildCallToMemberFunction - Build a call to a member
10265/// function. MemExpr is the expression that refers to the member
10266/// function (and includes the object parameter), Args/NumArgs are the
10267/// arguments to the function call (not including the object
10268/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010269/// expression refers to a non-static member function or an overloaded
10270/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010271ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010272Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10273 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010274 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010275 assert(MemExprE->getType() == Context.BoundMemberTy ||
10276 MemExprE->getType() == Context.OverloadTy);
10277
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010278 // Dig out the member expression. This holds both the object
10279 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010280 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010281
John McCall0009fcc2011-04-26 20:42:42 +000010282 // Determine whether this is a call to a pointer-to-member function.
10283 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10284 assert(op->getType() == Context.BoundMemberTy);
10285 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10286
10287 QualType fnType =
10288 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10289
10290 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10291 QualType resultType = proto->getCallResultType(Context);
10292 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10293
10294 // Check that the object type isn't more qualified than the
10295 // member function we're calling.
10296 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10297
10298 QualType objectType = op->getLHS()->getType();
10299 if (op->getOpcode() == BO_PtrMemI)
10300 objectType = objectType->castAs<PointerType>()->getPointeeType();
10301 Qualifiers objectQuals = objectType.getQualifiers();
10302
10303 Qualifiers difference = objectQuals - funcQuals;
10304 difference.removeObjCGCAttr();
10305 difference.removeAddressSpace();
10306 if (difference) {
10307 std::string qualsString = difference.getAsString();
10308 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10309 << fnType.getUnqualifiedType()
10310 << qualsString
10311 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10312 }
10313
10314 CXXMemberCallExpr *call
10315 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10316 resultType, valueKind, RParenLoc);
10317
10318 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010319 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010320 call, 0))
10321 return ExprError();
10322
10323 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10324 return ExprError();
10325
10326 return MaybeBindToTemporary(call);
10327 }
10328
John McCall4124c492011-10-17 18:40:02 +000010329 UnbridgedCastsSet UnbridgedCasts;
10330 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10331 return ExprError();
10332
John McCall10eae182009-11-30 22:42:35 +000010333 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010334 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010335 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010336 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010337 if (isa<MemberExpr>(NakedMemExpr)) {
10338 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010339 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010340 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010341 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010342 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010343 } else {
10344 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010345 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010346
John McCall6e9f8f62009-12-03 04:06:58 +000010347 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010348 Expr::Classification ObjectClassification
10349 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10350 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010351
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010352 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010353 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010354
John McCall2d74de92009-12-01 22:10:20 +000010355 // FIXME: avoid copy.
10356 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10357 if (UnresExpr->hasExplicitTemplateArgs()) {
10358 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10359 TemplateArgs = &TemplateArgsBuffer;
10360 }
10361
John McCall10eae182009-11-30 22:42:35 +000010362 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10363 E = UnresExpr->decls_end(); I != E; ++I) {
10364
John McCall6e9f8f62009-12-03 04:06:58 +000010365 NamedDecl *Func = *I;
10366 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10367 if (isa<UsingShadowDecl>(Func))
10368 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10369
Douglas Gregor02824322011-01-26 19:30:28 +000010370
Francois Pichet64225792011-01-18 05:04:39 +000010371 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010372 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010373 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10374 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010375 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010376 // If explicit template arguments were provided, we can't call a
10377 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010378 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010379 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010380
John McCalla0296f72010-03-19 07:35:19 +000010381 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010382 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010383 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010384 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010385 } else {
John McCall10eae182009-11-30 22:42:35 +000010386 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010387 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010388 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010389 llvm::makeArrayRef(Args, NumArgs),
10390 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010391 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010392 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010393 }
Mike Stump11289f42009-09-09 15:08:12 +000010394
John McCall10eae182009-11-30 22:42:35 +000010395 DeclarationName DeclName = UnresExpr->getMemberName();
10396
John McCall4124c492011-10-17 18:40:02 +000010397 UnbridgedCasts.restore();
10398
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010399 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010400 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010401 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010402 case OR_Success:
10403 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010404 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010405 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010406 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010407 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010408 break;
10409
10410 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010411 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010412 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010413 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010414 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10415 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010416 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010417 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010418
10419 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010420 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010421 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10423 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010424 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010425 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010426
10427 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010428 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010429 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010430 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010431 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010432 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010433 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10434 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010435 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010436 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010437 }
10438
John McCall16df1e52010-03-30 21:47:33 +000010439 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010440
John McCall2d74de92009-12-01 22:10:20 +000010441 // If overload resolution picked a static member, build a
10442 // non-member call based on that function.
10443 if (Method->isStatic()) {
10444 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10445 Args, NumArgs, RParenLoc);
10446 }
10447
John McCall10eae182009-11-30 22:42:35 +000010448 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010449 }
10450
John McCall7decc9e2010-11-18 06:31:45 +000010451 QualType ResultType = Method->getResultType();
10452 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10453 ResultType = ResultType.getNonLValueExprType(Context);
10454
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010455 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010456 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010457 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010458 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010459
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010460 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010461 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010462 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010463 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010464
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010465 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010466 // We only need to do this if there was actually an overload; otherwise
10467 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010468 if (!Method->isStatic()) {
10469 ExprResult ObjectArg =
10470 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10471 FoundDecl, Method);
10472 if (ObjectArg.isInvalid())
10473 return ExprError();
10474 MemExpr->setBase(ObjectArg.take());
10475 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010476
10477 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010478 const FunctionProtoType *Proto =
10479 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010480 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010481 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010482 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010483
Eli Friedmanff4b4072012-02-18 04:48:30 +000010484 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10485
John McCallb268a282010-08-23 23:25:46 +000010486 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010487 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010488
Anders Carlsson47061ee2011-05-06 14:25:31 +000010489 if ((isa<CXXConstructorDecl>(CurContext) ||
10490 isa<CXXDestructorDecl>(CurContext)) &&
10491 TheCall->getMethodDecl()->isPure()) {
10492 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10493
Chandler Carruth59259262011-06-27 08:31:58 +000010494 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010495 Diag(MemExpr->getLocStart(),
10496 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10497 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10498 << MD->getParent()->getDeclName();
10499
10500 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010501 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010502 }
John McCallb268a282010-08-23 23:25:46 +000010503 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010504}
10505
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010506/// BuildCallToObjectOfClassType - Build a call to an object of class
10507/// type (C++ [over.call.object]), which can end up invoking an
10508/// overloaded function call operator (@c operator()) or performing a
10509/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010510ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010511Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010512 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010513 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010514 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010515 if (checkPlaceholderForOverload(*this, Obj))
10516 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010517 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010518
10519 UnbridgedCastsSet UnbridgedCasts;
10520 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10521 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010522
John Wiegley01296292011-04-08 18:41:53 +000010523 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10524 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010525
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010526 // C++ [over.call.object]p1:
10527 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010528 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010529 // candidate functions includes at least the function call
10530 // operators of T. The function call operators of T are obtained by
10531 // ordinary lookup of the name operator() in the context of
10532 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010533 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010534 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010535
John Wiegley01296292011-04-08 18:41:53 +000010536 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +000010537 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010538 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010539 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010540
John McCall27b18f82009-11-17 02:14:36 +000010541 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10542 LookupQualifiedName(R, Record->getDecl());
10543 R.suppressDiagnostics();
10544
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010545 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010546 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010547 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10548 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010549 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010551
Douglas Gregorab7897a2008-11-19 22:57:39 +000010552 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010553 // In addition, for each (non-explicit in C++0x) conversion function
10554 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010555 //
10556 // operator conversion-type-id () cv-qualifier;
10557 //
10558 // where cv-qualifier is the same cv-qualification as, or a
10559 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010560 // denotes the type "pointer to function of (P1,...,Pn) returning
10561 // R", or the type "reference to pointer to function of
10562 // (P1,...,Pn) returning R", or the type "reference to function
10563 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010564 // is also considered as a candidate function. Similarly,
10565 // surrogate call functions are added to the set of candidate
10566 // functions for each conversion function declared in an
10567 // accessible base class provided the function is not hidden
10568 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010569 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010570 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010571 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010572 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010573 NamedDecl *D = *I;
10574 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10575 if (isa<UsingShadowDecl>(D))
10576 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010577
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010578 // Skip over templated conversion functions; they aren't
10579 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010580 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010581 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010582
John McCall6e9f8f62009-12-03 04:06:58 +000010583 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010584 if (!Conv->isExplicit()) {
10585 // Strip the reference type (if any) and then the pointer type (if
10586 // any) to get down to what might be a function type.
10587 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10588 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10589 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010590
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010591 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10592 {
10593 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010594 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10595 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010596 }
10597 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010598 }
Mike Stump11289f42009-09-09 15:08:12 +000010599
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010600 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10601
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010602 // Perform overload resolution.
10603 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010604 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010605 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010606 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010607 // Overload resolution succeeded; we'll build the appropriate call
10608 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010609 break;
10610
10611 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010612 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010613 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010614 << Object.get()->getType() << /*call*/ 1
10615 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010616 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010617 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010618 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010619 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010620 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10621 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010622 break;
10623
10624 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010625 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010626 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010627 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010628 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10629 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010630 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010631
10632 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010633 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010634 diag::err_ovl_deleted_object_call)
10635 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010636 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010637 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010638 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010639 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10640 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010641 break;
Mike Stump11289f42009-09-09 15:08:12 +000010642 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010643
Douglas Gregorb412e172010-07-25 18:17:45 +000010644 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010645 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010646
John McCall4124c492011-10-17 18:40:02 +000010647 UnbridgedCasts.restore();
10648
Douglas Gregorab7897a2008-11-19 22:57:39 +000010649 if (Best->Function == 0) {
10650 // Since there is no function declaration, this is one of the
10651 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010652 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010653 = cast<CXXConversionDecl>(
10654 Best->Conversions[0].UserDefined.ConversionFunction);
10655
John Wiegley01296292011-04-08 18:41:53 +000010656 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010657 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010658
Douglas Gregorab7897a2008-11-19 22:57:39 +000010659 // We selected one of the surrogate functions that converts the
10660 // object parameter to a function pointer. Perform the conversion
10661 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010662
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010663 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010664 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010665 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10666 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010667 if (Call.isInvalid())
10668 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010669 // Record usage of conversion in an implicit cast.
10670 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10671 CK_UserDefinedConversion,
10672 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010673
Douglas Gregor668443e2011-01-20 00:18:04 +000010674 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010675 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010676 }
10677
Eli Friedmanfa0df832012-02-02 03:46:19 +000010678 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010679 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010680 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010681
Douglas Gregorab7897a2008-11-19 22:57:39 +000010682 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10683 // that calls this method, using Object for the implicit object
10684 // parameter and passing along the remaining arguments.
10685 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010686 const FunctionProtoType *Proto =
10687 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010688
10689 unsigned NumArgsInProto = Proto->getNumArgs();
10690 unsigned NumArgsToCheck = NumArgs;
10691
10692 // Build the full argument list for the method call (the
10693 // implicit object parameter is placed at the beginning of the
10694 // list).
10695 Expr **MethodArgs;
10696 if (NumArgs < NumArgsInProto) {
10697 NumArgsToCheck = NumArgsInProto;
10698 MethodArgs = new Expr*[NumArgsInProto + 1];
10699 } else {
10700 MethodArgs = new Expr*[NumArgs + 1];
10701 }
John Wiegley01296292011-04-08 18:41:53 +000010702 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010703 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10704 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010705
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010706 DeclarationNameInfo OpLocInfo(
10707 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10708 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010709 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010710 HadMultipleCandidates,
10711 OpLocInfo.getLoc(),
10712 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010713 if (NewFn.isInvalid())
10714 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010715
10716 // Once we've built TheCall, all of the expressions are properly
10717 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010718 QualType ResultTy = Method->getResultType();
10719 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10720 ResultTy = ResultTy.getNonLValueExprType(Context);
10721
John McCallb268a282010-08-23 23:25:46 +000010722 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010723 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010724 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010725 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010726 delete [] MethodArgs;
10727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010728 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010729 Method))
10730 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010731
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010732 // We may have default arguments. If so, we need to allocate more
10733 // slots in the call for them.
10734 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010735 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010736 else if (NumArgs > NumArgsInProto)
10737 NumArgsToCheck = NumArgsInProto;
10738
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010739 bool IsError = false;
10740
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010741 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010742 ExprResult ObjRes =
10743 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10744 Best->FoundDecl, Method);
10745 if (ObjRes.isInvalid())
10746 IsError = true;
10747 else
10748 Object = move(ObjRes);
10749 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010750
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010751 // Check the argument types.
10752 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010753 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010754 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010755 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010756
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010757 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010758
John McCalldadc5752010-08-24 06:29:42 +000010759 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010760 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010761 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010762 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010763 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010764
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010765 IsError |= InputInit.isInvalid();
10766 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010767 } else {
John McCalldadc5752010-08-24 06:29:42 +000010768 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010769 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10770 if (DefArg.isInvalid()) {
10771 IsError = true;
10772 break;
10773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010774
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010775 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010776 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010777
10778 TheCall->setArg(i + 1, Arg);
10779 }
10780
10781 // If this is a variadic call, handle args passed through "...".
10782 if (Proto->isVariadic()) {
10783 // Promote the arguments (C99 6.5.2.2p7).
10784 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010785 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10786 IsError |= Arg.isInvalid();
10787 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010788 }
10789 }
10790
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010791 if (IsError) return true;
10792
Eli Friedmanff4b4072012-02-18 04:48:30 +000010793 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10794
John McCallb268a282010-08-23 23:25:46 +000010795 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010796 return true;
10797
John McCalle172be52010-08-24 06:09:16 +000010798 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010799}
10800
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010801/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010802/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010803/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010804ExprResult
John McCallb268a282010-08-23 23:25:46 +000010805Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010806 assert(Base->getType()->isRecordType() &&
10807 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010808
John McCall4124c492011-10-17 18:40:02 +000010809 if (checkPlaceholderForOverload(*this, Base))
10810 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010811
John McCallbc077cf2010-02-08 23:07:23 +000010812 SourceLocation Loc = Base->getExprLoc();
10813
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010814 // C++ [over.ref]p1:
10815 //
10816 // [...] An expression x->m is interpreted as (x.operator->())->m
10817 // for a class object x of type T if T::operator->() exists and if
10818 // the operator is selected as the best match function by the
10819 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010820 DeclarationName OpName =
10821 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010822 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010823 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010824
John McCallbc077cf2010-02-08 23:07:23 +000010825 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010826 PDiag(diag::err_typecheck_incomplete_tag)
10827 << Base->getSourceRange()))
10828 return ExprError();
10829
John McCall27b18f82009-11-17 02:14:36 +000010830 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10831 LookupQualifiedName(R, BaseRecord->getDecl());
10832 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010833
10834 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010835 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010836 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10837 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010838 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010839
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010840 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10841
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010842 // Perform overload resolution.
10843 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010844 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010845 case OR_Success:
10846 // Overload resolution succeeded; we'll build the call below.
10847 break;
10848
10849 case OR_No_Viable_Function:
10850 if (CandidateSet.empty())
10851 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010852 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010853 else
10854 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010855 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010857 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010858
10859 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010860 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10861 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010862 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010863 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010864
10865 case OR_Deleted:
10866 Diag(OpLoc, diag::err_ovl_deleted_oper)
10867 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010868 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010869 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010870 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010871 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010872 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010873 }
10874
Eli Friedmanfa0df832012-02-02 03:46:19 +000010875 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010876 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010877 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010878
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010879 // Convert the object parameter.
10880 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010881 ExprResult BaseResult =
10882 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10883 Best->FoundDecl, Method);
10884 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010885 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010886 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010887
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010888 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010889 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010890 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010891 if (FnExpr.isInvalid())
10892 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010893
John McCall7decc9e2010-11-18 06:31:45 +000010894 QualType ResultTy = Method->getResultType();
10895 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10896 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010897 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010898 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010899 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010900
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010901 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010902 Method))
10903 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010904
10905 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010906}
10907
Richard Smithbcc22fc2012-03-09 08:00:36 +000010908/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10909/// a literal operator described by the provided lookup results.
10910ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10911 DeclarationNameInfo &SuffixInfo,
10912 ArrayRef<Expr*> Args,
10913 SourceLocation LitEndLoc,
10914 TemplateArgumentListInfo *TemplateArgs) {
10915 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000010916
Richard Smithbcc22fc2012-03-09 08:00:36 +000010917 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10918 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10919 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000010920
Richard Smithbcc22fc2012-03-09 08:00:36 +000010921 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10922
Richard Smithbcc22fc2012-03-09 08:00:36 +000010923 // Perform overload resolution. This will usually be trivial, but might need
10924 // to perform substitutions for a literal operator template.
10925 OverloadCandidateSet::iterator Best;
10926 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
10927 case OR_Success:
10928 case OR_Deleted:
10929 break;
10930
10931 case OR_No_Viable_Function:
10932 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
10933 << R.getLookupName();
10934 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10935 return ExprError();
10936
10937 case OR_Ambiguous:
10938 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
10939 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
10940 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000010941 }
10942
Richard Smithbcc22fc2012-03-09 08:00:36 +000010943 FunctionDecl *FD = Best->Function;
10944 MarkFunctionReferenced(UDSuffixLoc, FD);
10945 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000010946
Richard Smithbcc22fc2012-03-09 08:00:36 +000010947 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
10948 SuffixInfo.getLoc(),
10949 SuffixInfo.getInfo());
10950 if (Fn.isInvalid())
10951 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000010952
10953 // Check the argument types. This should almost always be a no-op, except
10954 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000010955 Expr *ConvArgs[2];
10956 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
10957 ExprResult InputInit = PerformCopyInitialization(
10958 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
10959 SourceLocation(), Args[ArgIdx]);
10960 if (InputInit.isInvalid())
10961 return true;
10962 ConvArgs[ArgIdx] = InputInit.take();
10963 }
10964
Richard Smithc67fdd42012-03-07 08:35:16 +000010965 QualType ResultTy = FD->getResultType();
10966 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10967 ResultTy = ResultTy.getNonLValueExprType(Context);
10968
Richard Smithc67fdd42012-03-07 08:35:16 +000010969 UserDefinedLiteral *UDL =
10970 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
10971 ResultTy, VK, LitEndLoc, UDSuffixLoc);
10972
10973 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
10974 return ExprError();
10975
10976 if (CheckFunctionCall(FD, UDL))
10977 return ExprError();
10978
10979 return MaybeBindToTemporary(UDL);
10980}
10981
Douglas Gregorcd695e52008-11-10 20:40:00 +000010982/// FixOverloadedFunctionReference - E is an expression that refers to
10983/// a C++ overloaded function (possibly with some parentheses and
10984/// perhaps a '&' around it). We have resolved the overloaded function
10985/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010986/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010987Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010988 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010989 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010990 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10991 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010992 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010993 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010994
Douglas Gregor51c538b2009-11-20 19:42:02 +000010995 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010996 }
10997
Douglas Gregor51c538b2009-11-20 19:42:02 +000010998 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010999 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11000 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011001 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011002 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011003 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011004 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011005 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011006 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011007
11008 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011009 ICE->getCastKind(),
11010 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011011 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011012 }
11013
Douglas Gregor51c538b2009-11-20 19:42:02 +000011014 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011015 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011016 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11018 if (Method->isStatic()) {
11019 // Do nothing: static member functions aren't any different
11020 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011021 } else {
John McCalle66edc12009-11-24 19:00:30 +000011022 // Fix the sub expression, which really has to be an
11023 // UnresolvedLookupExpr holding an overloaded member function
11024 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011025 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11026 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011027 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011028 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011029
John McCalld14a8642009-11-21 08:51:07 +000011030 assert(isa<DeclRefExpr>(SubExpr)
11031 && "fixed to something other than a decl ref");
11032 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11033 && "fixed to a member ref with no nested name qualifier");
11034
11035 // We have taken the address of a pointer to member
11036 // function. Perform the computation here so that we get the
11037 // appropriate pointer to member type.
11038 QualType ClassType
11039 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11040 QualType MemPtrType
11041 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11042
John McCall7decc9e2010-11-18 06:31:45 +000011043 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11044 VK_RValue, OK_Ordinary,
11045 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011046 }
11047 }
John McCall16df1e52010-03-30 21:47:33 +000011048 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11049 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011050 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011051 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011052
John McCalle3027922010-08-25 11:45:40 +000011053 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011054 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011055 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011056 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011057 }
John McCalld14a8642009-11-21 08:51:07 +000011058
11059 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011060 // FIXME: avoid copy.
11061 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011062 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011063 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11064 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011065 }
11066
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011067 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11068 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011069 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011070 Fn,
John McCall113bee02012-03-10 09:33:50 +000011071 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011072 ULE->getNameLoc(),
11073 Fn->getType(),
11074 VK_LValue,
11075 Found.getDecl(),
11076 TemplateArgs);
11077 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11078 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011079 }
11080
John McCall10eae182009-11-30 22:42:35 +000011081 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011082 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011083 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11084 if (MemExpr->hasExplicitTemplateArgs()) {
11085 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11086 TemplateArgs = &TemplateArgsBuffer;
11087 }
John McCall6b51f282009-11-23 01:53:49 +000011088
John McCall2d74de92009-12-01 22:10:20 +000011089 Expr *Base;
11090
John McCall7decc9e2010-11-18 06:31:45 +000011091 // If we're filling in a static method where we used to have an
11092 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011093 if (MemExpr->isImplicitAccess()) {
11094 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011095 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11096 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011097 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011098 Fn,
John McCall113bee02012-03-10 09:33:50 +000011099 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011100 MemExpr->getMemberLoc(),
11101 Fn->getType(),
11102 VK_LValue,
11103 Found.getDecl(),
11104 TemplateArgs);
11105 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11106 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011107 } else {
11108 SourceLocation Loc = MemExpr->getMemberLoc();
11109 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011110 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011111 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011112 Base = new (Context) CXXThisExpr(Loc,
11113 MemExpr->getBaseType(),
11114 /*isImplicit=*/true);
11115 }
John McCall2d74de92009-12-01 22:10:20 +000011116 } else
John McCallc3007a22010-10-26 07:05:15 +000011117 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011118
John McCall4adb38c2011-04-27 00:36:17 +000011119 ExprValueKind valueKind;
11120 QualType type;
11121 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11122 valueKind = VK_LValue;
11123 type = Fn->getType();
11124 } else {
11125 valueKind = VK_RValue;
11126 type = Context.BoundMemberTy;
11127 }
11128
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011129 MemberExpr *ME = MemberExpr::Create(Context, Base,
11130 MemExpr->isArrow(),
11131 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011132 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011133 Fn,
11134 Found,
11135 MemExpr->getMemberNameInfo(),
11136 TemplateArgs,
11137 type, valueKind, OK_Ordinary);
11138 ME->setHadMultipleCandidates(true);
11139 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011141
John McCallc3007a22010-10-26 07:05:15 +000011142 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011143}
11144
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011145ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011146 DeclAccessPair Found,
11147 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011148 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011149}
11150
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011151} // end namespace clang