blob: 973a2fe065739074ae1945483bd4879a918d1cd0 [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"
Richard Smith9ca64612012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
John McCall7decc9e2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley01296292011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
52 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000053}
54
John McCall5c32be02010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000060
61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62 QualType &ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
65 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000066static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68 UserDefinedConversionSequence& User,
69 OverloadCandidateSet& Conversions,
70 bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75 const StandardConversionSequence& SCS1,
76 const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88
89
Douglas Gregor5251f1b2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000093GetConversionCategory(ImplicitConversionKind Kind) {
94 static const ImplicitConversionCategory
95 Category[(int)ICK_Num_Conversion_Kinds] = {
96 ICC_Identity,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Conversion
118 };
119 return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125 static const ImplicitConversionRank
126 Rank[(int)ICK_Num_Conversion_Kinds] = {
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190 First = ICK_Identity;
191 Second = ICK_Identity;
192 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203}
204
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209 ImplicitConversionRank Rank = ICR_Exact_Match;
210 if (GetConversionRank(First) > Rank)
211 Rank = GetConversionRank(First);
212 if (GetConversionRank(Second) > Rank)
213 Rank = GetConversionRank(Second);
214 if (GetConversionRank(Third) > Rank)
215 Rank = GetConversionRank(Third);
216 return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer or function-to-pointer implicit conversions, so
226 // check for their presence as well as checking whether FromType is
227 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000243bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith66e05fe2012-01-18 05:21:49 +0000262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266 switch (ICE->getCastKind()) {
267 case CK_NoOp:
268 case CK_IntegralCast:
269 case CK_IntegralToBoolean:
270 case CK_IntegralToFloating:
271 case CK_FloatingToIntegral:
272 case CK_FloatingToBoolean:
273 case CK_FloatingCast:
274 Converted = ICE->getSubExpr();
275 continue;
276
277 default:
278 return Converted;
279 }
280 }
281
282 return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx The AST context.
289/// \param Converted The result of applying this standard conversion sequence.
290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
291/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
293/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000300
301 // C++11 [dcl.init.list]p7:
302 // A narrowing conversion is an implicit conversion ...
303 QualType FromType = getToType(0);
304 QualType ToType = getToType(1);
305 switch (Second) {
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000365 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000392 (FromWidth == ToWidth && FromSigned != ToSigned) ||
393 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000394 // Not all values of FromType can be represented in ToType.
395 llvm::APSInt InitializerValue;
396 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398 // Such conversions on variables are always narrowing.
399 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000400 }
401 bool Narrowing = false;
402 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000403 // Negative -> unsigned is narrowing. Otherwise, more bits is never
404 // narrowing.
405 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000406 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000407 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000408 // Add a bit to the InitializerValue so we don't have to worry about
409 // signed vs. unsigned comparisons.
410 InitializerValue = InitializerValue.extend(
411 InitializerValue.getBitWidth() + 1);
412 // Convert the initializer to and from the target width and signed-ness.
413 llvm::APSInt ConvertedValue = InitializerValue;
414 ConvertedValue = ConvertedValue.trunc(ToWidth);
415 ConvertedValue.setIsSigned(ToSigned);
416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
418 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000419 if (ConvertedValue != InitializerValue)
420 Narrowing = true;
421 }
422 if (Narrowing) {
423 ConstantType = Initializer->getType();
424 ConstantValue = APValue(InitializerValue);
425 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000426 }
427 }
428 return NK_Not_Narrowing;
429 }
430
431 default:
432 // Other kinds of conversions are not narrowings.
433 return NK_Not_Narrowing;
434 }
435}
436
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000440 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 bool PrintedSomething = false;
442 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444 PrintedSomething = true;
445 }
446
447 if (Second != ICK_Identity) {
448 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452
453 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000457 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000459 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Third != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 if (Before.First || Before.Second || Before.Third) {
481 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000484 if (ConversionFunction)
485 OS << '\'' << *ConversionFunction << '\'';
486 else
487 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 After.DebugPrint();
491 }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 switch (ConversionKind) {
499 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000500 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 Standard.DebugPrint();
502 break;
503 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000504 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 UserDefined.DebugPrint();
506 break;
507 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 break;
John McCall0d1da222010-01-12 00:44:57 +0000510 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000512 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 break;
516 }
517
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519}
520
John McCall0d1da222010-01-12 00:44:57 +0000521void AmbiguousConversionSequence::construct() {
522 new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526 conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531 FromTypePtr = O.FromTypePtr;
532 ToTypePtr = O.ToTypePtr;
533 new (&conversions()) ConversionSet(O.conversions());
534}
535
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536namespace {
537 // Structure used by OverloadCandidate::DeductionFailureInfo to store
538 // template parameter and template argument information.
539 struct DFIParamWithArguments {
540 TemplateParameter Param;
541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
544}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000549static MakeDeductionFailureInfo(ASTContext &Context,
550 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000551 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 OverloadCandidate::DeductionFailureInfo Result;
553 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000554 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Data = 0;
556 switch (TDK) {
557 case Sema::TDK_Success:
558 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000559 case Sema::TDK_TooManyArguments:
560 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000564 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 Result.Data = Info.Param.getOpaqueValue();
566 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000569 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000570 // FIXME: Should allocate from normal heap so that we can free this later.
571 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 Saved->Param = Info.Param;
573 Saved->FirstArg = Info.FirstArg;
574 Saved->SecondArg = Info.SecondArg;
575 Result.Data = Saved;
576 break;
577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000580 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000581 if (Info.hasSFINAEDiagnostic()) {
582 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
583 SourceLocation(), PartialDiagnostic::NullDiagnostic());
584 Info.takeSFINAEDiagnostic(*Diag);
585 Result.HasDiagnostic = true;
586 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 return Result;
595}
John McCall0d1da222010-01-12 00:44:57 +0000596
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000597void OverloadCandidate::DeductionFailureInfo::Destroy() {
598 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
599 case Sema::TDK_Success:
600 case Sema::TDK_InstantiationDepth:
601 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000602 case Sema::TDK_TooManyArguments:
603 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000604 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000608 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000609 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 Data = 0;
611 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000612
613 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000614 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000615 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000616 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
617 Diag->~PartialDiagnosticAt();
618 HasDiagnostic = false;
619 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621
Douglas Gregor461761d2010-05-08 18:20:53 +0000622 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 case Sema::TDK_FailedOverloadResolution:
625 break;
626 }
627}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Richard Smith9ca64612012-05-07 09:03:25 +0000629PartialDiagnosticAt *
630OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
631 if (HasDiagnostic)
632 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
633 return 0;
634}
635
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000637OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
638 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
639 case Sema::TDK_Success:
640 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000641 case Sema::TDK_TooManyArguments:
642 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000643 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000647 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649
650 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000651 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 case Sema::TDK_FailedOverloadResolution:
657 break;
658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 return TemplateParameter();
661}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Douglas Gregord09efd42010-05-08 20:07:26 +0000663TemplateArgumentList *
664OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
665 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
666 case Sema::TDK_Success:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_TooManyArguments:
669 case Sema::TDK_TooFewArguments:
670 case Sema::TDK_Incomplete:
671 case Sema::TDK_InvalidExplicitArguments:
672 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000673 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000674 return 0;
675
676 case Sema::TDK_SubstitutionFailure:
677 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 // Unhandled
680 case Sema::TDK_NonDeducedMismatch:
681 case Sema::TDK_FailedOverloadResolution:
682 break;
683 }
684
685 return 0;
686}
687
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
689 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
690 case Sema::TDK_Success:
691 case Sema::TDK_InstantiationDepth:
692 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000693 case Sema::TDK_TooManyArguments:
694 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000695 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000696 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 return 0;
698
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000700 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702
Douglas Gregor461761d2010-05-08 18:20:53 +0000703 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 case Sema::TDK_FailedOverloadResolution:
706 break;
707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000709 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711
712const TemplateArgument *
713OverloadCandidate::DeductionFailureInfo::getSecondArg() {
714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
715 case Sema::TDK_Success:
716 case Sema::TDK_InstantiationDepth:
717 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000718 case Sema::TDK_TooManyArguments:
719 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000720 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000721 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 return 0;
723
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000725 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
727
Douglas Gregor461761d2010-05-08 18:20:53 +0000728 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730 case Sema::TDK_FailedOverloadResolution:
731 break;
732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000734 return 0;
735}
736
737void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000738 for (iterator i = begin(), e = end(); i != e; ++i)
739 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
740 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000741 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000742 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743 Functions.clear();
744}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000745
John McCall4124c492011-10-17 18:40:02 +0000746namespace {
747 class UnbridgedCastsSet {
748 struct Entry {
749 Expr **Addr;
750 Expr *Saved;
751 };
752 SmallVector<Entry, 2> Entries;
753
754 public:
755 void save(Sema &S, Expr *&E) {
756 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
757 Entry entry = { &E, E };
758 Entries.push_back(entry);
759 E = S.stripARCUnbridgedCast(E);
760 }
761
762 void restore() {
763 for (SmallVectorImpl<Entry>::iterator
764 i = Entries.begin(), e = Entries.end(); i != e; ++i)
765 *i->Addr = i->Saved;
766 }
767 };
768}
769
770/// checkPlaceholderForOverload - Do any interesting placeholder-like
771/// preprocessing on the given expression.
772///
773/// \param unbridgedCasts a collection to which to add unbridged casts;
774/// without this, they will be immediately diagnosed as errors
775///
776/// Return true on unrecoverable error.
777static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
778 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000779 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
780 // We can't handle overloaded expressions here because overload
781 // resolution might reasonably tweak them.
782 if (placeholder->getKind() == BuiltinType::Overload) return false;
783
784 // If the context potentially accepts unbridged ARC casts, strip
785 // the unbridged cast and add it to the collection for later restoration.
786 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
787 unbridgedCasts) {
788 unbridgedCasts->save(S, E);
789 return false;
790 }
791
792 // Go ahead and check everything else.
793 ExprResult result = S.CheckPlaceholderExpr(E);
794 if (result.isInvalid())
795 return true;
796
797 E = result.take();
798 return false;
799 }
800
801 // Nothing to do.
802 return false;
803}
804
805/// checkArgPlaceholdersForOverload - Check a set of call operands for
806/// placeholders.
807static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
808 unsigned numArgs,
809 UnbridgedCastsSet &unbridged) {
810 for (unsigned i = 0; i != numArgs; ++i)
811 if (checkPlaceholderForOverload(S, args[i], &unbridged))
812 return true;
813
814 return false;
815}
816
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000818// overload of the declarations in Old. This routine returns false if
819// New and Old cannot be overloaded, e.g., if New has the same
820// signature as some function in Old (C++ 1.3.10) or if the Old
821// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000822// it does return false, MatchedDecl will point to the decl that New
823// cannot be overloaded with. This decl may be a UsingShadowDecl on
824// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000825//
826// Example: Given the following input:
827//
828// void f(int, float); // #1
829// void f(int, int); // #2
830// int f(int, int); // #3
831//
832// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000833// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000834//
John McCall3d988d92009-12-02 08:47:38 +0000835// When we process #2, Old contains only the FunctionDecl for #1. By
836// comparing the parameter types, we see that #1 and #2 are overloaded
837// (since they have different signatures), so this routine returns
838// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839//
John McCall3d988d92009-12-02 08:47:38 +0000840// When we process #3, Old is an overload set containing #1 and #2. We
841// compare the signatures of #3 to #1 (they're overloaded, so we do
842// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
843// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000844// signature), IsOverload returns false and MatchedDecl will be set to
845// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000846//
847// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
848// into a class by a using declaration. The rules for whether to hide
849// shadow declarations ignore some properties which otherwise figure
850// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000851Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000852Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
853 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000854 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000855 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000856 NamedDecl *OldD = *I;
857
858 bool OldIsUsingDecl = false;
859 if (isa<UsingShadowDecl>(OldD)) {
860 OldIsUsingDecl = true;
861
862 // We can always introduce two using declarations into the same
863 // context, even if they have identical signatures.
864 if (NewIsUsingDecl) continue;
865
866 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
867 }
868
869 // If either declaration was introduced by a using declaration,
870 // we'll need to use slightly different rules for matching.
871 // Essentially, these rules are the normal rules, except that
872 // function templates hide function templates with different
873 // return types or template parameter lists.
874 bool UseMemberUsingDeclRules =
875 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
876
John McCall3d988d92009-12-02 08:47:38 +0000877 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000878 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
879 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
880 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
881 continue;
882 }
883
John McCalldaa3d6b2009-12-09 03:35:25 +0000884 Match = *I;
885 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886 }
John McCall3d988d92009-12-02 08:47:38 +0000887 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000888 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
889 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
890 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
891 continue;
892 }
893
John McCalldaa3d6b2009-12-09 03:35:25 +0000894 Match = *I;
895 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000896 }
John McCalla8987a2942010-11-10 03:01:53 +0000897 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000898 // We can overload with these, which can show up when doing
899 // redeclaration checks for UsingDecls.
900 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000901 } else if (isa<TagDecl>(OldD)) {
902 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000903 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
904 // Optimistically assume that an unresolved using decl will
905 // overload; if it doesn't, we'll have to diagnose during
906 // template instantiation.
907 } else {
John McCall1f82f242009-11-18 22:49:29 +0000908 // (C++ 13p1):
909 // Only function declarations can be overloaded; object and type
910 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000911 Match = *I;
912 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000913 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914 }
John McCall1f82f242009-11-18 22:49:29 +0000915
John McCalldaa3d6b2009-12-09 03:35:25 +0000916 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000917}
918
John McCalle9cccd82010-06-16 08:42:20 +0000919bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
920 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000921 // If both of the functions are extern "C", then they are not
922 // overloads.
923 if (Old->isExternC() && New->isExternC())
924 return false;
925
John McCall1f82f242009-11-18 22:49:29 +0000926 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
927 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
928
929 // C++ [temp.fct]p2:
930 // A function template can be overloaded with other function templates
931 // and with normal (non-template) functions.
932 if ((OldTemplate == 0) != (NewTemplate == 0))
933 return true;
934
935 // Is the function New an overload of the function Old?
936 QualType OldQType = Context.getCanonicalType(Old->getType());
937 QualType NewQType = Context.getCanonicalType(New->getType());
938
939 // Compare the signatures (C++ 1.3.10) of the two functions to
940 // determine whether they are overloads. If we find any mismatch
941 // in the signature, they are overloads.
942
943 // If either of these functions is a K&R-style function (no
944 // prototype), then we consider them to have matching signatures.
945 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
946 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
947 return false;
948
John McCall424cec92011-01-19 06:33:43 +0000949 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
950 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000951
952 // The signature of a function includes the types of its
953 // parameters (C++ 1.3.10), which includes the presence or absence
954 // of the ellipsis; see C++ DR 357).
955 if (OldQType != NewQType &&
956 (OldType->getNumArgs() != NewType->getNumArgs() ||
957 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000958 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000959 return true;
960
961 // C++ [temp.over.link]p4:
962 // The signature of a function template consists of its function
963 // signature, its return type and its template parameter list. The names
964 // of the template parameters are significant only for establishing the
965 // relationship between the template parameters and the rest of the
966 // signature.
967 //
968 // We check the return type and template parameter lists for function
969 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000970 //
971 // However, we don't consider either of these when deciding whether
972 // a member introduced by a shadow declaration is hidden.
973 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000974 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
975 OldTemplate->getTemplateParameters(),
976 false, TPL_TemplateMatch) ||
977 OldType->getResultType() != NewType->getResultType()))
978 return true;
979
980 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000981 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000982 //
983 // As part of this, also check whether one of the member functions
984 // is static, in which case they are not overloads (C++
985 // 13.1p2). While not part of the definition of the signature,
986 // this check is important to determine whether these functions
987 // can be overloaded.
988 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
989 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
990 if (OldMethod && NewMethod &&
991 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000992 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000993 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
994 if (!UseUsingDeclRules &&
995 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
996 (OldMethod->getRefQualifier() == RQ_None ||
997 NewMethod->getRefQualifier() == RQ_None)) {
998 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999 // - Member function declarations with the same name and the same
1000 // parameter-type-list as well as member function template
1001 // declarations with the same name, the same parameter-type-list, and
1002 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001003 // them, but not all, have a ref-qualifier (8.3.5).
1004 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1005 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1006 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008
John McCall1f82f242009-11-18 22:49:29 +00001009 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
John McCall1f82f242009-11-18 22:49:29 +00001012 // The signatures match; this is not an overload.
1013 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001014}
1015
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001016/// \brief Checks availability of the function depending on the current
1017/// function context. Inside an unavailable function, unavailability is ignored.
1018///
1019/// \returns true if \arg FD is unavailable and current context is inside
1020/// an available function, false otherwise.
1021bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1022 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1023}
1024
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001025/// \brief Tries a user-defined conversion from From to ToType.
1026///
1027/// Produces an implicit conversion sequence for when a standard conversion
1028/// is not an option. See TryImplicitConversion for more information.
1029static ImplicitConversionSequence
1030TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1031 bool SuppressUserConversions,
1032 bool AllowExplicit,
1033 bool InOverloadResolution,
1034 bool CStyle,
1035 bool AllowObjCWritebackConversion) {
1036 ImplicitConversionSequence ICS;
1037
1038 if (SuppressUserConversions) {
1039 // We're not in the case above, so there is no conversion that
1040 // we can perform.
1041 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1042 return ICS;
1043 }
1044
1045 // Attempt user-defined conversion.
1046 OverloadCandidateSet Conversions(From->getExprLoc());
1047 OverloadingResult UserDefResult
1048 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1049 AllowExplicit);
1050
1051 if (UserDefResult == OR_Success) {
1052 ICS.setUserDefined();
1053 // C++ [over.ics.user]p4:
1054 // A conversion of an expression of class type to the same class
1055 // type is given Exact Match rank, and a conversion of an
1056 // expression of class type to a base class of that type is
1057 // given Conversion rank, in spite of the fact that a copy
1058 // constructor (i.e., a user-defined conversion function) is
1059 // called for those cases.
1060 if (CXXConstructorDecl *Constructor
1061 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1062 QualType FromCanon
1063 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1064 QualType ToCanon
1065 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1066 if (Constructor->isCopyConstructor() &&
1067 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1068 // Turn this into a "standard" conversion sequence, so that it
1069 // gets ranked with standard conversion sequences.
1070 ICS.setStandard();
1071 ICS.Standard.setAsIdentityConversion();
1072 ICS.Standard.setFromType(From->getType());
1073 ICS.Standard.setAllToTypes(ToType);
1074 ICS.Standard.CopyConstructor = Constructor;
1075 if (ToCanon != FromCanon)
1076 ICS.Standard.Second = ICK_Derived_To_Base;
1077 }
1078 }
1079
1080 // C++ [over.best.ics]p4:
1081 // However, when considering the argument of a user-defined
1082 // conversion function that is a candidate by 13.3.1.3 when
1083 // invoked for the copying of the temporary in the second step
1084 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1085 // 13.3.1.6 in all cases, only standard conversion sequences and
1086 // ellipsis conversion sequences are allowed.
1087 if (SuppressUserConversions && ICS.isUserDefined()) {
1088 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1089 }
1090 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1091 ICS.setAmbiguous();
1092 ICS.Ambiguous.setFromType(From->getType());
1093 ICS.Ambiguous.setToType(ToType);
1094 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1095 Cand != Conversions.end(); ++Cand)
1096 if (Cand->Viable)
1097 ICS.Ambiguous.addConversion(Cand->Function);
1098 } else {
1099 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1100 }
1101
1102 return ICS;
1103}
1104
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001105/// TryImplicitConversion - Attempt to perform an implicit conversion
1106/// from the given expression (Expr) to the given type (ToType). This
1107/// function returns an implicit conversion sequence that can be used
1108/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001109///
1110/// void f(float f);
1111/// void g(int i) { f(i); }
1112///
1113/// this routine would produce an implicit conversion sequence to
1114/// describe the initialization of f from i, which will be a standard
1115/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1116/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1117//
1118/// Note that this routine only determines how the conversion can be
1119/// performed; it does not actually perform the conversion. As such,
1120/// it will not produce any diagnostics if no conversion is available,
1121/// but will instead return an implicit conversion sequence of kind
1122/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001123///
1124/// If @p SuppressUserConversions, then user-defined conversions are
1125/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001126/// If @p AllowExplicit, then explicit user-defined conversions are
1127/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001128///
1129/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1130/// writeback conversion, which allows __autoreleasing id* parameters to
1131/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001132static ImplicitConversionSequence
1133TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1134 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001136 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001137 bool CStyle,
1138 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001139 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001140 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001141 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001142 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001143 return ICS;
1144 }
1145
David Blaikiebbafb8a2012-03-11 07:00:24 +00001146 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001147 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001148 return ICS;
1149 }
1150
Douglas Gregor836a7e82010-08-11 02:15:33 +00001151 // C++ [over.ics.user]p4:
1152 // A conversion of an expression of class type to the same class
1153 // type is given Exact Match rank, and a conversion of an
1154 // expression of class type to a base class of that type is
1155 // given Conversion rank, in spite of the fact that a copy/move
1156 // constructor (i.e., a user-defined conversion function) is
1157 // called for those cases.
1158 QualType FromType = From->getType();
1159 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001160 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1161 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001162 ICS.setStandard();
1163 ICS.Standard.setAsIdentityConversion();
1164 ICS.Standard.setFromType(FromType);
1165 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166
Douglas Gregor5ab11652010-04-17 22:01:05 +00001167 // We don't actually check at this point whether there is a valid
1168 // copy/move constructor, since overloading just assumes that it
1169 // exists. When we actually perform initialization, we'll find the
1170 // appropriate constructor to copy the returned object, if needed.
1171 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
Douglas Gregor5ab11652010-04-17 22:01:05 +00001173 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001174 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001175 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176
Douglas Gregor836a7e82010-08-11 02:15:33 +00001177 return ICS;
1178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001180 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1181 AllowExplicit, InOverloadResolution, CStyle,
1182 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001183}
1184
John McCall31168b02011-06-15 23:02:42 +00001185ImplicitConversionSequence
1186Sema::TryImplicitConversion(Expr *From, QualType ToType,
1187 bool SuppressUserConversions,
1188 bool AllowExplicit,
1189 bool InOverloadResolution,
1190 bool CStyle,
1191 bool AllowObjCWritebackConversion) {
1192 return clang::TryImplicitConversion(*this, From, ToType,
1193 SuppressUserConversions, AllowExplicit,
1194 InOverloadResolution, CStyle,
1195 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001196}
1197
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001198/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001199/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001200/// converted expression. Flavor is the kind of conversion we're
1201/// performing, used in the error message. If @p AllowExplicit,
1202/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001203ExprResult
1204Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001205 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001206 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001207 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001208}
1209
John Wiegley01296292011-04-08 18:41:53 +00001210ExprResult
1211Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001212 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001213 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001214 if (checkPlaceholderForOverload(*this, From))
1215 return ExprError();
1216
John McCall31168b02011-06-15 23:02:42 +00001217 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1218 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001219 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001220 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001221
John McCall5c32be02010-08-24 20:38:10 +00001222 ICS = clang::TryImplicitConversion(*this, From, ToType,
1223 /*SuppressUserConversions=*/false,
1224 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001225 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001226 /*CStyle=*/false,
1227 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001228 return PerformImplicitConversion(From, ToType, ICS, Action);
1229}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
1231/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001232/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001233bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1234 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001235 if (Context.hasSameUnqualifiedType(FromType, ToType))
1236 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237
John McCall991eb4b2010-12-21 00:44:39 +00001238 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1239 // where F adds one of the following at most once:
1240 // - a pointer
1241 // - a member pointer
1242 // - a block pointer
1243 CanQualType CanTo = Context.getCanonicalType(ToType);
1244 CanQualType CanFrom = Context.getCanonicalType(FromType);
1245 Type::TypeClass TyClass = CanTo->getTypeClass();
1246 if (TyClass != CanFrom->getTypeClass()) return false;
1247 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1248 if (TyClass == Type::Pointer) {
1249 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1250 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1251 } else if (TyClass == Type::BlockPointer) {
1252 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1253 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1254 } else if (TyClass == Type::MemberPointer) {
1255 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1256 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1257 } else {
1258 return false;
1259 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001260
John McCall991eb4b2010-12-21 00:44:39 +00001261 TyClass = CanTo->getTypeClass();
1262 if (TyClass != CanFrom->getTypeClass()) return false;
1263 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1264 return false;
1265 }
1266
1267 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1268 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1269 if (!EInfo.getNoReturn()) return false;
1270
1271 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1272 assert(QualType(FromFn, 0).isCanonical());
1273 if (QualType(FromFn, 0) != CanTo) return false;
1274
1275 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001276 return true;
1277}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregor46188682010-05-18 22:42:18 +00001279/// \brief Determine whether the conversion from FromType to ToType is a valid
1280/// vector conversion.
1281///
1282/// \param ICK Will be set to the vector conversion kind, if this is a vector
1283/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1285 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001286 // We need at least one of these types to be a vector type to have a vector
1287 // conversion.
1288 if (!ToType->isVectorType() && !FromType->isVectorType())
1289 return false;
1290
1291 // Identical types require no conversions.
1292 if (Context.hasSameUnqualifiedType(FromType, ToType))
1293 return false;
1294
1295 // There are no conversions between extended vector types, only identity.
1296 if (ToType->isExtVectorType()) {
1297 // There are no conversions between extended vector types other than the
1298 // identity conversion.
1299 if (FromType->isExtVectorType())
1300 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001301
Douglas Gregor46188682010-05-18 22:42:18 +00001302 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001303 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001304 ICK = ICK_Vector_Splat;
1305 return true;
1306 }
1307 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001308
1309 // We can perform the conversion between vector types in the following cases:
1310 // 1)vector types are equivalent AltiVec and GCC vector types
1311 // 2)lax vector conversions are permitted and the vector types are of the
1312 // same size
1313 if (ToType->isVectorType() && FromType->isVectorType()) {
1314 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001316 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001317 ICK = ICK_Vector_Conversion;
1318 return true;
1319 }
Douglas Gregor46188682010-05-18 22:42:18 +00001320 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001321
Douglas Gregor46188682010-05-18 22:42:18 +00001322 return false;
1323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001325static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1326 bool InOverloadResolution,
1327 StandardConversionSequence &SCS,
1328 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001329
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001330/// IsStandardConversion - Determines whether there is a standard
1331/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1332/// expression From to the type ToType. Standard conversion sequences
1333/// only consider non-class types; for conversions that involve class
1334/// types, use TryImplicitConversion. If a conversion exists, SCS will
1335/// contain the standard conversion sequence required to perform this
1336/// conversion and this routine will return true. Otherwise, this
1337/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001338static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1339 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001340 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001341 bool CStyle,
1342 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001345 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001346 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001347 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001348 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001349 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001350 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001351
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001352 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001353 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001354 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001355 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001356 return false;
1357
Mike Stump11289f42009-09-09 15:08:12 +00001358 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001359 }
1360
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001361 // The first conversion can be an lvalue-to-rvalue conversion,
1362 // array-to-pointer conversion, or function-to-pointer conversion
1363 // (C++ 4p1).
1364
John McCall5c32be02010-08-24 20:38:10 +00001365 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001366 DeclAccessPair AccessPair;
1367 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001369 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001370 // We were able to resolve the address of the overloaded function,
1371 // so we can convert to the type of that function.
1372 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001373
1374 // we can sometimes resolve &foo<int> regardless of ToType, so check
1375 // if the type matches (identity) or we are converting to bool
1376 if (!S.Context.hasSameUnqualifiedType(
1377 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1378 QualType resultTy;
1379 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001380 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001381 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1382 // otherwise, only a boolean conversion is standard
1383 if (!ToType->isBooleanType())
1384 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386
Chandler Carruthffce2452011-03-29 08:08:18 +00001387 // Check if the "from" expression is taking the address of an overloaded
1388 // function and recompute the FromType accordingly. Take advantage of the
1389 // fact that non-static member functions *must* have such an address-of
1390 // expression.
1391 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1392 if (Method && !Method->isStatic()) {
1393 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1394 "Non-unary operator on non-static member address");
1395 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1396 == UO_AddrOf &&
1397 "Non-address-of operator on non-static member address");
1398 const Type *ClassType
1399 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1400 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001401 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1402 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1403 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001404 "Non-address-of operator for overloaded function expression");
1405 FromType = S.Context.getPointerType(FromType);
1406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001407
Douglas Gregor980fb162010-04-29 18:24:40 +00001408 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001409 assert(S.Context.hasSameType(
1410 FromType,
1411 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001412 } else {
1413 return false;
1414 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001415 }
John McCall154a2fd2011-08-30 00:57:29 +00001416 // Lvalue-to-rvalue conversion (C++11 4.1):
1417 // A glvalue (3.10) of a non-function, non-array type T can
1418 // be converted to a prvalue.
1419 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001420 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001421 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001422 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001423 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424
Douglas Gregorc79862f2012-04-12 17:51:55 +00001425 // C11 6.3.2.1p2:
1426 // ... if the lvalue has atomic type, the value has the non-atomic version
1427 // of the type of the lvalue ...
1428 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1429 FromType = Atomic->getValueType();
1430
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001431 // If T is a non-class type, the type of the rvalue is the
1432 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001433 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1434 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001435 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001436 } else if (FromType->isArrayType()) {
1437 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001438 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001439
1440 // An lvalue or rvalue of type "array of N T" or "array of unknown
1441 // bound of T" can be converted to an rvalue of type "pointer to
1442 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001443 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001444
John McCall5c32be02010-08-24 20:38:10 +00001445 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001446 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001447 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448
1449 // For the purpose of ranking in overload resolution
1450 // (13.3.3.1.1), this conversion is considered an
1451 // array-to-pointer conversion followed by a qualification
1452 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001453 SCS.Second = ICK_Identity;
1454 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001455 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001456 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001457 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458 }
John McCall086a4642010-11-24 05:12:34 +00001459 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001460 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001461 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001462
1463 // An lvalue of function type T can be converted to an rvalue of
1464 // type "pointer to T." The result is a pointer to the
1465 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001466 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001467 } else {
1468 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001469 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001470 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001471 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472
1473 // The second conversion can be an integral promotion, floating
1474 // point promotion, integral conversion, floating point conversion,
1475 // floating-integral conversion, pointer conversion,
1476 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001477 // For overloading in C, this can also be a "compatible-type"
1478 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001479 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001480 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001481 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482 // The unqualified versions of the types are the same: there's no
1483 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001485 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001486 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001489 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001490 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001491 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001493 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001494 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001495 SCS.Second = ICK_Complex_Promotion;
1496 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001497 } else if (ToType->isBooleanType() &&
1498 (FromType->isArithmeticType() ||
1499 FromType->isAnyPointerType() ||
1500 FromType->isBlockPointerType() ||
1501 FromType->isMemberPointerType() ||
1502 FromType->isNullPtrType())) {
1503 // Boolean conversions (C++ 4.12).
1504 SCS.Second = ICK_Boolean_Conversion;
1505 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001506 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001507 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001508 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001509 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001510 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001511 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001512 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001513 SCS.Second = ICK_Complex_Conversion;
1514 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001515 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1516 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001517 // Complex-real conversions (C99 6.3.1.7)
1518 SCS.Second = ICK_Complex_Real;
1519 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001520 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001521 // Floating point conversions (C++ 4.8).
1522 SCS.Second = ICK_Floating_Conversion;
1523 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001525 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001526 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001527 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001528 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001531 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001532 SCS.Second = ICK_Block_Pointer_Conversion;
1533 } else if (AllowObjCWritebackConversion &&
1534 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1535 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001536 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1537 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001538 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001540 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001541 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001543 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001544 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001545 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001546 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001547 SCS.Second = SecondICK;
1548 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001549 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001550 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001552 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001553 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001554 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001555 // Treat a conversion that strips "noreturn" as an identity conversion.
1556 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001557 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1558 InOverloadResolution,
1559 SCS, CStyle)) {
1560 SCS.Second = ICK_TransparentUnionConversion;
1561 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001562 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1563 CStyle)) {
1564 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001565 // appropriately.
1566 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 } else {
1568 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001569 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001571 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001573 QualType CanonFrom;
1574 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001575 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001576 bool ObjCLifetimeConversion;
1577 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1578 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001579 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001580 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001582 CanonFrom = S.Context.getCanonicalType(FromType);
1583 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 } else {
1585 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.Third = ICK_Identity;
1587
Mike Stump11289f42009-09-09 15:08:12 +00001588 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 // [...] Any difference in top-level cv-qualification is
1590 // subsumed by the initialization itself and does not constitute
1591 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001592 CanonFrom = S.Context.getCanonicalType(FromType);
1593 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001595 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001596 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001597 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1598 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001599 FromType = ToType;
1600 CanonFrom = CanonTo;
1601 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001603 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604
1605 // If we have not converted the argument type to the parameter type,
1606 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001607 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001608 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001610 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001612
1613static bool
1614IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1615 QualType &ToType,
1616 bool InOverloadResolution,
1617 StandardConversionSequence &SCS,
1618 bool CStyle) {
1619
1620 const RecordType *UT = ToType->getAsUnionType();
1621 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1622 return false;
1623 // The field to initialize within the transparent union.
1624 RecordDecl *UD = UT->getDecl();
1625 // It's compatible if the expression matches any of the fields.
1626 for (RecordDecl::field_iterator it = UD->field_begin(),
1627 itend = UD->field_end();
1628 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001629 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1630 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001631 ToType = it->getType();
1632 return true;
1633 }
1634 }
1635 return false;
1636}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001637
1638/// IsIntegralPromotion - Determines whether the conversion from the
1639/// expression From (whose potentially-adjusted type is FromType) to
1640/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1641/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001642bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001643 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001644 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001645 if (!To) {
1646 return false;
1647 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001648
1649 // An rvalue of type char, signed char, unsigned char, short int, or
1650 // unsigned short int can be converted to an rvalue of type int if
1651 // int can represent all the values of the source type; otherwise,
1652 // the source rvalue can be converted to an rvalue of type unsigned
1653 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001654 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1655 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656 if (// We can promote any signed, promotable integer type to an int
1657 (FromType->isSignedIntegerType() ||
1658 // We can promote any unsigned integer type whose size is
1659 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001660 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001661 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001663 }
1664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 return To->getKind() == BuiltinType::UInt;
1666 }
1667
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668 // C++0x [conv.prom]p3:
1669 // A prvalue of an unscoped enumeration type whose underlying type is not
1670 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1671 // following types that can represent all the values of the enumeration
1672 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1673 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001674 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001676 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677 // with lowest integer conversion rank (4.13) greater than the rank of long
1678 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001679 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001680 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1681 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1682 // provided for a scoped enumeration.
1683 if (FromEnumType->getDecl()->isScoped())
1684 return false;
1685
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001686 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001688 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001689 return Context.hasSameUnqualifiedType(ToType,
1690 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001691 }
John McCall56774992009-12-09 09:09:27 +00001692
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001693 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001694 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1695 // to an rvalue a prvalue of the first of the following types that can
1696 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001697 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001699 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001701 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001703 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 // Determine whether the type we're converting from is signed or
1705 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001706 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001707 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001708
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 // The types we'll try to promote to, in the appropriate
1710 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001711 QualType PromoteTypes[6] = {
1712 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001713 Context.LongTy, Context.UnsignedLongTy ,
1714 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001716 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1718 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001719 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1721 // We found the type that we can promote to. If this is the
1722 // type we wanted, we have a promotion. Otherwise, no
1723 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001724 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 }
1726 }
1727 }
1728
1729 // An rvalue for an integral bit-field (9.6) can be converted to an
1730 // rvalue of type int if int can represent all the values of the
1731 // bit-field; otherwise, it can be converted to unsigned int if
1732 // unsigned int can represent all the values of the bit-field. If
1733 // the bit-field is larger yet, no integral promotion applies to
1734 // it. If the bit-field has an enumerated type, it is treated as any
1735 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001736 // FIXME: We should delay checking of bit-fields until we actually perform the
1737 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001738 using llvm::APSInt;
1739 if (From)
1740 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001741 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001742 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001743 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1744 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1745 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001747 // Are we promoting to an int from a bitfield that fits in an int?
1748 if (BitWidth < ToSize ||
1749 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1750 return To->getKind() == BuiltinType::Int;
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001753 // Are we promoting to an unsigned int from an unsigned bitfield
1754 // that fits into an unsigned int?
1755 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1756 return To->getKind() == BuiltinType::UInt;
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001759 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001760 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001761 }
Mike Stump11289f42009-09-09 15:08:12 +00001762
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001763 // An rvalue of type bool can be converted to an rvalue of type int,
1764 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001765 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001767 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768
1769 return false;
1770}
1771
1772/// IsFloatingPointPromotion - Determines whether the conversion from
1773/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1774/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001775bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001776 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1777 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001778 /// An rvalue of type float can be converted to an rvalue of type
1779 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780 if (FromBuiltin->getKind() == BuiltinType::Float &&
1781 ToBuiltin->getKind() == BuiltinType::Double)
1782 return true;
1783
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001784 // C99 6.3.1.5p1:
1785 // When a float is promoted to double or long double, or a
1786 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001787 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001788 (FromBuiltin->getKind() == BuiltinType::Float ||
1789 FromBuiltin->getKind() == BuiltinType::Double) &&
1790 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1791 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001792
1793 // Half can be promoted to float.
1794 if (FromBuiltin->getKind() == BuiltinType::Half &&
1795 ToBuiltin->getKind() == BuiltinType::Float)
1796 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001797 }
1798
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001799 return false;
1800}
1801
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001802/// \brief Determine if a conversion is a complex promotion.
1803///
1804/// A complex promotion is defined as a complex -> complex conversion
1805/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001806/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001807bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001808 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001809 if (!FromComplex)
1810 return false;
1811
John McCall9dd450b2009-09-21 23:43:11 +00001812 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001813 if (!ToComplex)
1814 return false;
1815
1816 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001817 ToComplex->getElementType()) ||
1818 IsIntegralPromotion(0, FromComplex->getElementType(),
1819 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001820}
1821
Douglas Gregor237f96c2008-11-26 23:31:11 +00001822/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1823/// the pointer type FromPtr to a pointer to type ToPointee, with the
1824/// same type qualifiers as FromPtr has on its pointee type. ToType,
1825/// if non-empty, will be a pointer to ToType that may or may not have
1826/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001827///
Mike Stump11289f42009-09-09 15:08:12 +00001828static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001829BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001830 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001831 ASTContext &Context,
1832 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001833 assert((FromPtr->getTypeClass() == Type::Pointer ||
1834 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1835 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001836
John McCall31168b02011-06-15 23:02:42 +00001837 /// Conversions to 'id' subsume cv-qualifier conversions.
1838 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001839 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
1841 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001842 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001843 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001844 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001845
John McCall31168b02011-06-15 23:02:42 +00001846 if (StripObjCLifetime)
1847 Quals.removeObjCLifetime();
1848
Mike Stump11289f42009-09-09 15:08:12 +00001849 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001850 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001851 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001852 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001853 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001854
1855 // Build a pointer to ToPointee. It has the right qualifiers
1856 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001857 if (isa<ObjCObjectPointerType>(ToType))
1858 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001859 return Context.getPointerType(ToPointee);
1860 }
1861
1862 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001863 QualType QualifiedCanonToPointee
1864 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001866 if (isa<ObjCObjectPointerType>(ToType))
1867 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1868 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001869}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870
Mike Stump11289f42009-09-09 15:08:12 +00001871static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001872 bool InOverloadResolution,
1873 ASTContext &Context) {
1874 // Handle value-dependent integral null pointer constants correctly.
1875 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1876 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001877 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001878 return !InOverloadResolution;
1879
Douglas Gregor56751b52009-09-25 04:25:58 +00001880 return Expr->isNullPointerConstant(Context,
1881 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1882 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001883}
Mike Stump11289f42009-09-09 15:08:12 +00001884
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885/// IsPointerConversion - Determines whether the conversion of the
1886/// expression From, which has the (possibly adjusted) type FromType,
1887/// can be converted to the type ToType via a pointer conversion (C++
1888/// 4.10). If so, returns true and places the converted type (that
1889/// might differ from ToType in its cv-qualifiers at some level) into
1890/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001891///
Douglas Gregora29dc052008-11-27 01:19:21 +00001892/// This routine also supports conversions to and from block pointers
1893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1894/// pointers to interfaces. FIXME: Once we've determined the
1895/// appropriate overloading rules for Objective-C, we may want to
1896/// split the Objective-C checks into a different routine; however,
1897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001898/// conversions, so for now they live here. IncompatibleObjC will be
1899/// set if the conversion is an allowed Objective-C conversion that
1900/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001902 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001903 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001904 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001905 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001906 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1907 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001908 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001909
Mike Stump11289f42009-09-09 15:08:12 +00001910 // Conversion from a null pointer constant to any Objective-C pointer type.
1911 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001913 ConvertedType = ToType;
1914 return true;
1915 }
1916
Douglas Gregor231d1c62008-11-27 00:15:41 +00001917 // Blocks: Block pointers can be converted to void*.
1918 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001919 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001920 ConvertedType = ToType;
1921 return true;
1922 }
1923 // Blocks: A null pointer constant can be converted to a block
1924 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001925 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001927 ConvertedType = ToType;
1928 return true;
1929 }
1930
Sebastian Redl576fd422009-05-10 18:38:11 +00001931 // If the left-hand-side is nullptr_t, the right side can be a null
1932 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001933 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001934 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001935 ConvertedType = ToType;
1936 return true;
1937 }
1938
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001939 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001940 if (!ToTypePtr)
1941 return false;
1942
1943 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001944 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001945 ConvertedType = ToType;
1946 return true;
1947 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001948
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001950 // , including objective-c pointers.
1951 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001952 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001953 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001954 ConvertedType = BuildSimilarlyQualifiedPointerType(
1955 FromType->getAs<ObjCObjectPointerType>(),
1956 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001957 ToType, Context);
1958 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001959 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001961 if (!FromTypePtr)
1962 return false;
1963
1964 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001967 // pointer conversion, so don't do all of the work below.
1968 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1969 return false;
1970
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001971 // An rvalue of type "pointer to cv T," where T is an object type,
1972 // can be converted to an rvalue of type "pointer to cv void" (C++
1973 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001974 if (FromPointeeType->isIncompleteOrObjectType() &&
1975 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001977 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001978 ToType, Context,
1979 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001980 return true;
1981 }
1982
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001983 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001984 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001985 ToPointeeType->isVoidType()) {
1986 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1987 ToPointeeType,
1988 ToType, Context);
1989 return true;
1990 }
1991
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001992 // When we're overloading in C, we allow a special kind of pointer
1993 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001994 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001995 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001997 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001998 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001999 return true;
2000 }
2001
Douglas Gregor5c407d92008-10-23 00:40:37 +00002002 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002003 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002004 // An rvalue of type "pointer to cv D," where D is a class type,
2005 // can be converted to an rvalue of type "pointer to cv B," where
2006 // B is a base class (clause 10) of D. If B is an inaccessible
2007 // (clause 11) or ambiguous (10.2) base class of D, a program that
2008 // necessitates this conversion is ill-formed. The result of the
2009 // conversion is a pointer to the base class sub-object of the
2010 // derived class object. The null pointer value is converted to
2011 // the null pointer value of the destination type.
2012 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002013 // Note that we do not check for ambiguity or inaccessibility
2014 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002015 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002016 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002017 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002018 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002019 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002020 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002021 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002022 ToType, Context);
2023 return true;
2024 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002025
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002026 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2027 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2028 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2029 ToPointeeType,
2030 ToType, Context);
2031 return true;
2032 }
2033
Douglas Gregora119f102008-12-19 19:13:09 +00002034 return false;
2035}
Douglas Gregoraec25842011-04-26 23:16:46 +00002036
2037/// \brief Adopt the given qualifiers for the given type.
2038static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2039 Qualifiers TQs = T.getQualifiers();
2040
2041 // Check whether qualifiers already match.
2042 if (TQs == Qs)
2043 return T;
2044
2045 if (Qs.compatiblyIncludes(TQs))
2046 return Context.getQualifiedType(T, Qs);
2047
2048 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2049}
Douglas Gregora119f102008-12-19 19:13:09 +00002050
2051/// isObjCPointerConversion - Determines whether this is an
2052/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2053/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002054bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002055 QualType& ConvertedType,
2056 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002057 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002058 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059
Douglas Gregoraec25842011-04-26 23:16:46 +00002060 // The set of qualifiers on the type we're converting from.
2061 Qualifiers FromQualifiers = FromType.getQualifiers();
2062
Steve Naroff7cae42b2009-07-10 23:34:53 +00002063 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002064 const ObjCObjectPointerType* ToObjCPtr =
2065 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002066 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002067 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002068
Steve Naroff7cae42b2009-07-10 23:34:53 +00002069 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002070 // If the pointee types are the same (ignoring qualifications),
2071 // then this is not a pointer conversion.
2072 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2073 FromObjCPtr->getPointeeType()))
2074 return false;
2075
Douglas Gregoraec25842011-04-26 23:16:46 +00002076 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002077 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002078 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002079 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002080 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002081 return true;
2082 }
2083 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002084 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002085 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002086 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002087 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002088 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002089 return true;
2090 }
2091 // Objective C++: We're able to convert from a pointer to an
2092 // interface to a pointer to a different interface.
2093 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002094 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2095 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002096 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002097 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2098 FromObjCPtr->getPointeeType()))
2099 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002101 ToObjCPtr->getPointeeType(),
2102 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002103 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002104 return true;
2105 }
2106
2107 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2108 // Okay: this is some kind of implicit downcast of Objective-C
2109 // interfaces, which is permitted. However, we're going to
2110 // complain about it.
2111 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002113 ToObjCPtr->getPointeeType(),
2114 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002115 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002116 return true;
2117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002119 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002120 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002121 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002122 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002124 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002125 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002126 // to a block pointer type.
2127 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002128 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002129 return true;
2130 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002131 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002134 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002136 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002137 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002138 return true;
2139 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002140 else
Douglas Gregora119f102008-12-19 19:13:09 +00002141 return false;
2142
Douglas Gregor033f56d2008-12-23 00:53:59 +00002143 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002144 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002145 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002146 else if (const BlockPointerType *FromBlockPtr =
2147 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002148 FromPointeeType = FromBlockPtr->getPointeeType();
2149 else
Douglas Gregora119f102008-12-19 19:13:09 +00002150 return false;
2151
Douglas Gregora119f102008-12-19 19:13:09 +00002152 // If we have pointers to pointers, recursively check whether this
2153 // is an Objective-C conversion.
2154 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2155 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2156 IncompatibleObjC)) {
2157 // We always complain about this conversion.
2158 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002159 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002160 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002161 return true;
2162 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002163 // Allow conversion of pointee being objective-c pointer to another one;
2164 // as in I* to id.
2165 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2166 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2167 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2168 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002169
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002170 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002171 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002172 return true;
2173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002174
Douglas Gregor033f56d2008-12-23 00:53:59 +00002175 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002176 // differences in the argument and result types are in Objective-C
2177 // pointer conversions. If so, we permit the conversion (but
2178 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002179 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002180 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002181 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002182 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002183 if (FromFunctionType && ToFunctionType) {
2184 // If the function types are exactly the same, this isn't an
2185 // Objective-C pointer conversion.
2186 if (Context.getCanonicalType(FromPointeeType)
2187 == Context.getCanonicalType(ToPointeeType))
2188 return false;
2189
2190 // Perform the quick checks that will tell us whether these
2191 // function types are obviously different.
2192 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2193 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2194 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2195 return false;
2196
2197 bool HasObjCConversion = false;
2198 if (Context.getCanonicalType(FromFunctionType->getResultType())
2199 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2200 // Okay, the types match exactly. Nothing to do.
2201 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2202 ToFunctionType->getResultType(),
2203 ConvertedType, IncompatibleObjC)) {
2204 // Okay, we have an Objective-C pointer conversion.
2205 HasObjCConversion = true;
2206 } else {
2207 // Function types are too different. Abort.
2208 return false;
2209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregora119f102008-12-19 19:13:09 +00002211 // Check argument types.
2212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2213 ArgIdx != NumArgs; ++ArgIdx) {
2214 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2215 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2216 if (Context.getCanonicalType(FromArgType)
2217 == Context.getCanonicalType(ToArgType)) {
2218 // Okay, the types match exactly. Nothing to do.
2219 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2220 ConvertedType, IncompatibleObjC)) {
2221 // Okay, we have an Objective-C pointer conversion.
2222 HasObjCConversion = true;
2223 } else {
2224 // Argument types are too different. Abort.
2225 return false;
2226 }
2227 }
2228
2229 if (HasObjCConversion) {
2230 // We had an Objective-C conversion. Allow this pointer
2231 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002232 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002233 IncompatibleObjC = true;
2234 return true;
2235 }
2236 }
2237
Sebastian Redl72b597d2009-01-25 19:43:20 +00002238 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002239}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240
John McCall31168b02011-06-15 23:02:42 +00002241/// \brief Determine whether this is an Objective-C writeback conversion,
2242/// used for parameter passing when performing automatic reference counting.
2243///
2244/// \param FromType The type we're converting form.
2245///
2246/// \param ToType The type we're converting to.
2247///
2248/// \param ConvertedType The type that will be produced after applying
2249/// this conversion.
2250bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2251 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002252 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002253 Context.hasSameUnqualifiedType(FromType, ToType))
2254 return false;
2255
2256 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2257 QualType ToPointee;
2258 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2259 ToPointee = ToPointer->getPointeeType();
2260 else
2261 return false;
2262
2263 Qualifiers ToQuals = ToPointee.getQualifiers();
2264 if (!ToPointee->isObjCLifetimeType() ||
2265 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002266 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002267 return false;
2268
2269 // Argument must be a pointer to __strong to __weak.
2270 QualType FromPointee;
2271 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2272 FromPointee = FromPointer->getPointeeType();
2273 else
2274 return false;
2275
2276 Qualifiers FromQuals = FromPointee.getQualifiers();
2277 if (!FromPointee->isObjCLifetimeType() ||
2278 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2279 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2280 return false;
2281
2282 // Make sure that we have compatible qualifiers.
2283 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2284 if (!ToQuals.compatiblyIncludes(FromQuals))
2285 return false;
2286
2287 // Remove qualifiers from the pointee type we're converting from; they
2288 // aren't used in the compatibility check belong, and we'll be adding back
2289 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2290 FromPointee = FromPointee.getUnqualifiedType();
2291
2292 // The unqualified form of the pointee types must be compatible.
2293 ToPointee = ToPointee.getUnqualifiedType();
2294 bool IncompatibleObjC;
2295 if (Context.typesAreCompatible(FromPointee, ToPointee))
2296 FromPointee = ToPointee;
2297 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2298 IncompatibleObjC))
2299 return false;
2300
2301 /// \brief Construct the type we're converting to, which is a pointer to
2302 /// __autoreleasing pointee.
2303 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2304 ConvertedType = Context.getPointerType(FromPointee);
2305 return true;
2306}
2307
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002308bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2309 QualType& ConvertedType) {
2310 QualType ToPointeeType;
2311 if (const BlockPointerType *ToBlockPtr =
2312 ToType->getAs<BlockPointerType>())
2313 ToPointeeType = ToBlockPtr->getPointeeType();
2314 else
2315 return false;
2316
2317 QualType FromPointeeType;
2318 if (const BlockPointerType *FromBlockPtr =
2319 FromType->getAs<BlockPointerType>())
2320 FromPointeeType = FromBlockPtr->getPointeeType();
2321 else
2322 return false;
2323 // We have pointer to blocks, check whether the only
2324 // differences in the argument and result types are in Objective-C
2325 // pointer conversions. If so, we permit the conversion.
2326
2327 const FunctionProtoType *FromFunctionType
2328 = FromPointeeType->getAs<FunctionProtoType>();
2329 const FunctionProtoType *ToFunctionType
2330 = ToPointeeType->getAs<FunctionProtoType>();
2331
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002332 if (!FromFunctionType || !ToFunctionType)
2333 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002334
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002335 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002336 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002337
2338 // Perform the quick checks that will tell us whether these
2339 // function types are obviously different.
2340 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2341 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2342 return false;
2343
2344 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2345 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2346 if (FromEInfo != ToEInfo)
2347 return false;
2348
2349 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002350 if (Context.hasSameType(FromFunctionType->getResultType(),
2351 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002352 // Okay, the types match exactly. Nothing to do.
2353 } else {
2354 QualType RHS = FromFunctionType->getResultType();
2355 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002356 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002357 !RHS.hasQualifiers() && LHS.hasQualifiers())
2358 LHS = LHS.getUnqualifiedType();
2359
2360 if (Context.hasSameType(RHS,LHS)) {
2361 // OK exact match.
2362 } else if (isObjCPointerConversion(RHS, LHS,
2363 ConvertedType, IncompatibleObjC)) {
2364 if (IncompatibleObjC)
2365 return false;
2366 // Okay, we have an Objective-C pointer conversion.
2367 }
2368 else
2369 return false;
2370 }
2371
2372 // Check argument types.
2373 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2374 ArgIdx != NumArgs; ++ArgIdx) {
2375 IncompatibleObjC = false;
2376 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2377 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2378 if (Context.hasSameType(FromArgType, ToArgType)) {
2379 // Okay, the types match exactly. Nothing to do.
2380 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2381 ConvertedType, IncompatibleObjC)) {
2382 if (IncompatibleObjC)
2383 return false;
2384 // Okay, we have an Objective-C pointer conversion.
2385 } else
2386 // Argument types are too different. Abort.
2387 return false;
2388 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002389 if (LangOpts.ObjCAutoRefCount &&
2390 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2391 ToFunctionType))
2392 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002393
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002394 ConvertedType = ToType;
2395 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002396}
2397
Richard Trieucaff2472011-11-23 22:32:32 +00002398enum {
2399 ft_default,
2400 ft_different_class,
2401 ft_parameter_arity,
2402 ft_parameter_mismatch,
2403 ft_return_type,
2404 ft_qualifer_mismatch
2405};
2406
2407/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2408/// function types. Catches different number of parameter, mismatch in
2409/// parameter types, and different return types.
2410void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2411 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002412 // If either type is not valid, include no extra info.
2413 if (FromType.isNull() || ToType.isNull()) {
2414 PDiag << ft_default;
2415 return;
2416 }
2417
Richard Trieucaff2472011-11-23 22:32:32 +00002418 // Get the function type from the pointers.
2419 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2420 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2421 *ToMember = ToType->getAs<MemberPointerType>();
2422 if (FromMember->getClass() != ToMember->getClass()) {
2423 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2424 << QualType(FromMember->getClass(), 0);
2425 return;
2426 }
2427 FromType = FromMember->getPointeeType();
2428 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002429 }
2430
Richard Trieu96ed5b62011-12-13 23:19:45 +00002431 if (FromType->isPointerType())
2432 FromType = FromType->getPointeeType();
2433 if (ToType->isPointerType())
2434 ToType = ToType->getPointeeType();
2435
2436 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002437 FromType = FromType.getNonReferenceType();
2438 ToType = ToType.getNonReferenceType();
2439
Richard Trieucaff2472011-11-23 22:32:32 +00002440 // Don't print extra info for non-specialized template functions.
2441 if (FromType->isInstantiationDependentType() &&
2442 !FromType->getAs<TemplateSpecializationType>()) {
2443 PDiag << ft_default;
2444 return;
2445 }
2446
Richard Trieu96ed5b62011-12-13 23:19:45 +00002447 // No extra info for same types.
2448 if (Context.hasSameType(FromType, ToType)) {
2449 PDiag << ft_default;
2450 return;
2451 }
2452
Richard Trieucaff2472011-11-23 22:32:32 +00002453 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2454 *ToFunction = ToType->getAs<FunctionProtoType>();
2455
2456 // Both types need to be function types.
2457 if (!FromFunction || !ToFunction) {
2458 PDiag << ft_default;
2459 return;
2460 }
2461
2462 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2463 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2464 << FromFunction->getNumArgs();
2465 return;
2466 }
2467
2468 // Handle different parameter types.
2469 unsigned ArgPos;
2470 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2471 PDiag << ft_parameter_mismatch << ArgPos + 1
2472 << ToFunction->getArgType(ArgPos)
2473 << FromFunction->getArgType(ArgPos);
2474 return;
2475 }
2476
2477 // Handle different return type.
2478 if (!Context.hasSameType(FromFunction->getResultType(),
2479 ToFunction->getResultType())) {
2480 PDiag << ft_return_type << ToFunction->getResultType()
2481 << FromFunction->getResultType();
2482 return;
2483 }
2484
2485 unsigned FromQuals = FromFunction->getTypeQuals(),
2486 ToQuals = ToFunction->getTypeQuals();
2487 if (FromQuals != ToQuals) {
2488 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2489 return;
2490 }
2491
2492 // Unable to find a difference, so add no extra info.
2493 PDiag << ft_default;
2494}
2495
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002496/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002497/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002498/// they have same number of arguments. This routine assumes that Objective-C
2499/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002500/// If the parameters are different, ArgPos will have the the parameter index
2501/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002502bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002503 const FunctionProtoType *NewType,
2504 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002505 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002506 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2507 N = NewType->arg_type_begin(),
2508 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2509 if (!Context.hasSameType(*O, *N)) {
2510 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2511 return false;
2512 }
2513 }
2514 return true;
2515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002517 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2518 N = NewType->arg_type_begin(),
2519 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2520 QualType ToType = (*O);
2521 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002522 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002523 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2524 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002525 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2526 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2527 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2528 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002529 continue;
2530 }
John McCall8b07ec22010-05-15 11:32:37 +00002531 else if (const ObjCObjectPointerType *PTTo =
2532 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002534 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002535 if (Context.hasSameUnqualifiedType(
2536 PTTo->getObjectType()->getBaseType(),
2537 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002538 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002539 }
Richard Trieucaff2472011-11-23 22:32:32 +00002540 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002541 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002542 }
2543 }
2544 return true;
2545}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002546
Douglas Gregor39c16d42008-10-24 04:54:22 +00002547/// CheckPointerConversion - Check the pointer conversion from the
2548/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002549/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002550/// conversions for which IsPointerConversion has already returned
2551/// true. It returns true and produces a diagnostic if there was an
2552/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002553bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002554 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002555 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002556 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002557 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002558 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002559
John McCall8cb679e2010-11-15 09:13:47 +00002560 Kind = CK_BitCast;
2561
Chandler Carruthffab8732011-04-09 07:32:05 +00002562 if (!IsCStyleOrFunctionalCast &&
2563 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2564 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2565 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002566 PDiag(diag::warn_impcast_bool_to_null_pointer)
2567 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002568
John McCall9320b872011-09-09 05:25:32 +00002569 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2570 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002571 QualType FromPointeeType = FromPtrType->getPointeeType(),
2572 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002573
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002574 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2575 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002576 // We must have a derived-to-base conversion. Check an
2577 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002578 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2579 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002580 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002581 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002582 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002583
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002584 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002585 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002586 }
2587 }
John McCall9320b872011-09-09 05:25:32 +00002588 } else if (const ObjCObjectPointerType *ToPtrType =
2589 ToType->getAs<ObjCObjectPointerType>()) {
2590 if (const ObjCObjectPointerType *FromPtrType =
2591 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002592 // Objective-C++ conversions are always okay.
2593 // FIXME: We should have a different class of conversions for the
2594 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002595 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002596 return false;
John McCall9320b872011-09-09 05:25:32 +00002597 } else if (FromType->isBlockPointerType()) {
2598 Kind = CK_BlockPointerToObjCPointerCast;
2599 } else {
2600 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002601 }
John McCall9320b872011-09-09 05:25:32 +00002602 } else if (ToType->isBlockPointerType()) {
2603 if (!FromType->isBlockPointerType())
2604 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002605 }
John McCall8cb679e2010-11-15 09:13:47 +00002606
2607 // We shouldn't fall into this case unless it's valid for other
2608 // reasons.
2609 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2610 Kind = CK_NullToPointer;
2611
Douglas Gregor39c16d42008-10-24 04:54:22 +00002612 return false;
2613}
2614
Sebastian Redl72b597d2009-01-25 19:43:20 +00002615/// IsMemberPointerConversion - Determines whether the conversion of the
2616/// expression From, which has the (possibly adjusted) type FromType, can be
2617/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2618/// If so, returns true and places the converted type (that might differ from
2619/// ToType in its cv-qualifiers at some level) into ConvertedType.
2620bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002621 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002622 bool InOverloadResolution,
2623 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002624 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002625 if (!ToTypePtr)
2626 return false;
2627
2628 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002629 if (From->isNullPointerConstant(Context,
2630 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2631 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002632 ConvertedType = ToType;
2633 return true;
2634 }
2635
2636 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002637 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002638 if (!FromTypePtr)
2639 return false;
2640
2641 // A pointer to member of B can be converted to a pointer to member of D,
2642 // where D is derived from B (C++ 4.11p2).
2643 QualType FromClass(FromTypePtr->getClass(), 0);
2644 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002645
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002646 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002647 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002648 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002649 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2650 ToClass.getTypePtr());
2651 return true;
2652 }
2653
2654 return false;
2655}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Sebastian Redl72b597d2009-01-25 19:43:20 +00002657/// CheckMemberPointerConversion - Check the member pointer conversion from the
2658/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002659/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002660/// for which IsMemberPointerConversion has already returned true. It returns
2661/// true and produces a diagnostic if there was an error, or returns false
2662/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002663bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002664 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002665 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002666 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002667 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002668 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002669 if (!FromPtrType) {
2670 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002672 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002673 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002674 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002675 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002676 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002678 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002679 assert(ToPtrType && "No member pointer cast has a target type "
2680 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002681
Sebastian Redled8f2002009-01-28 18:33:18 +00002682 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2683 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002684
Sebastian Redled8f2002009-01-28 18:33:18 +00002685 // FIXME: What about dependent types?
2686 assert(FromClass->isRecordType() && "Pointer into non-class.");
2687 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002688
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002690 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002691 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2692 assert(DerivationOkay &&
2693 "Should not have been called if derivation isn't OK.");
2694 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002695
Sebastian Redled8f2002009-01-28 18:33:18 +00002696 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2697 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002698 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2699 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2700 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2701 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002702 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002703
Douglas Gregor89ee6822009-02-28 01:32:25 +00002704 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002705 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2706 << FromClass << ToClass << QualType(VBase, 0)
2707 << From->getSourceRange();
2708 return true;
2709 }
2710
John McCall5b0829a2010-02-10 09:31:12 +00002711 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002712 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2713 Paths.front(),
2714 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002715
Anders Carlssond7923c62009-08-22 23:33:40 +00002716 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002717 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002718 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002719 return false;
2720}
2721
Douglas Gregor9a657932008-10-21 23:43:52 +00002722/// IsQualificationConversion - Determines whether the conversion from
2723/// an rvalue of type FromType to ToType is a qualification conversion
2724/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002725///
2726/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2727/// when the qualification conversion involves a change in the Objective-C
2728/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002729bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002730Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002731 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002732 FromType = Context.getCanonicalType(FromType);
2733 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002734 ObjCLifetimeConversion = false;
2735
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 // If FromType and ToType are the same type, this is not a
2737 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002738 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002739 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002740
Douglas Gregor9a657932008-10-21 23:43:52 +00002741 // (C++ 4.4p4):
2742 // A conversion can add cv-qualifiers at levels other than the first
2743 // in multi-level pointers, subject to the following rules: [...]
2744 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002745 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002746 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002747 // Within each iteration of the loop, we check the qualifiers to
2748 // determine if this still looks like a qualification
2749 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002750 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002751 // until there are no more pointers or pointers-to-members left to
2752 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002753 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002754
Douglas Gregor90609aa2011-04-25 18:40:17 +00002755 Qualifiers FromQuals = FromType.getQualifiers();
2756 Qualifiers ToQuals = ToType.getQualifiers();
2757
John McCall31168b02011-06-15 23:02:42 +00002758 // Objective-C ARC:
2759 // Check Objective-C lifetime conversions.
2760 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2761 UnwrappedAnyPointer) {
2762 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2763 ObjCLifetimeConversion = true;
2764 FromQuals.removeObjCLifetime();
2765 ToQuals.removeObjCLifetime();
2766 } else {
2767 // Qualification conversions cannot cast between different
2768 // Objective-C lifetime qualifiers.
2769 return false;
2770 }
2771 }
2772
Douglas Gregorf30053d2011-05-08 06:09:53 +00002773 // Allow addition/removal of GC attributes but not changing GC attributes.
2774 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2775 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2776 FromQuals.removeObjCGCAttr();
2777 ToQuals.removeObjCGCAttr();
2778 }
2779
Douglas Gregor9a657932008-10-21 23:43:52 +00002780 // -- for every j > 0, if const is in cv 1,j then const is in cv
2781 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002782 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002783 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002784
Douglas Gregor9a657932008-10-21 23:43:52 +00002785 // -- if the cv 1,j and cv 2,j are different, then const is in
2786 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002787 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002788 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002789 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002790
Douglas Gregor9a657932008-10-21 23:43:52 +00002791 // Keep track of whether all prior cv-qualifiers in the "to" type
2792 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002793 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002794 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002795 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002796
2797 // We are left with FromType and ToType being the pointee types
2798 // after unwrapping the original FromType and ToType the same number
2799 // of types. If we unwrapped any pointers, and if FromType and
2800 // ToType have the same unqualified type (since we checked
2801 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002802 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002803}
2804
Douglas Gregorc79862f2012-04-12 17:51:55 +00002805/// \brief - Determine whether this is a conversion from a scalar type to an
2806/// atomic type.
2807///
2808/// If successful, updates \c SCS's second and third steps in the conversion
2809/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002810static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2811 bool InOverloadResolution,
2812 StandardConversionSequence &SCS,
2813 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002814 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2815 if (!ToAtomic)
2816 return false;
2817
2818 StandardConversionSequence InnerSCS;
2819 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2820 InOverloadResolution, InnerSCS,
2821 CStyle, /*AllowObjCWritebackConversion=*/false))
2822 return false;
2823
2824 SCS.Second = InnerSCS.Second;
2825 SCS.setToType(1, InnerSCS.getToType(1));
2826 SCS.Third = InnerSCS.Third;
2827 SCS.QualificationIncludesObjCLifetime
2828 = InnerSCS.QualificationIncludesObjCLifetime;
2829 SCS.setToType(2, InnerSCS.getToType(2));
2830 return true;
2831}
2832
Sebastian Redle5417162012-03-27 18:33:03 +00002833static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2834 CXXConstructorDecl *Constructor,
2835 QualType Type) {
2836 const FunctionProtoType *CtorType =
2837 Constructor->getType()->getAs<FunctionProtoType>();
2838 if (CtorType->getNumArgs() > 0) {
2839 QualType FirstArg = CtorType->getArgType(0);
2840 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2841 return true;
2842 }
2843 return false;
2844}
2845
Sebastian Redl82ace982012-02-11 23:51:08 +00002846static OverloadingResult
2847IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2848 CXXRecordDecl *To,
2849 UserDefinedConversionSequence &User,
2850 OverloadCandidateSet &CandidateSet,
2851 bool AllowExplicit) {
2852 DeclContext::lookup_iterator Con, ConEnd;
2853 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2854 Con != ConEnd; ++Con) {
2855 NamedDecl *D = *Con;
2856 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2857
2858 // Find the constructor (which may be a template).
2859 CXXConstructorDecl *Constructor = 0;
2860 FunctionTemplateDecl *ConstructorTmpl
2861 = dyn_cast<FunctionTemplateDecl>(D);
2862 if (ConstructorTmpl)
2863 Constructor
2864 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2865 else
2866 Constructor = cast<CXXConstructorDecl>(D);
2867
2868 bool Usable = !Constructor->isInvalidDecl() &&
2869 S.isInitListConstructor(Constructor) &&
2870 (AllowExplicit || !Constructor->isExplicit());
2871 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002872 // If the first argument is (a reference to) the target type,
2873 // suppress conversions.
2874 bool SuppressUserConversions =
2875 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002876 if (ConstructorTmpl)
2877 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2878 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002879 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002880 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002881 else
2882 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002883 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002884 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002885 }
2886 }
2887
2888 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2889
2890 OverloadCandidateSet::iterator Best;
2891 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2892 case OR_Success: {
2893 // Record the standard conversion we used and the conversion function.
2894 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2895 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2896
2897 QualType ThisType = Constructor->getThisType(S.Context);
2898 // Initializer lists don't have conversions as such.
2899 User.Before.setAsIdentityConversion();
2900 User.HadMultipleCandidates = HadMultipleCandidates;
2901 User.ConversionFunction = Constructor;
2902 User.FoundConversionFunction = Best->FoundDecl;
2903 User.After.setAsIdentityConversion();
2904 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2905 User.After.setAllToTypes(ToType);
2906 return OR_Success;
2907 }
2908
2909 case OR_No_Viable_Function:
2910 return OR_No_Viable_Function;
2911 case OR_Deleted:
2912 return OR_Deleted;
2913 case OR_Ambiguous:
2914 return OR_Ambiguous;
2915 }
2916
2917 llvm_unreachable("Invalid OverloadResult!");
2918}
2919
Douglas Gregor576e98c2009-01-30 23:27:23 +00002920/// Determines whether there is a user-defined conversion sequence
2921/// (C++ [over.ics.user]) that converts expression From to the type
2922/// ToType. If such a conversion exists, User will contain the
2923/// user-defined conversion sequence that performs such a conversion
2924/// and this routine will return true. Otherwise, this routine returns
2925/// false and User is unspecified.
2926///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002927/// \param AllowExplicit true if the conversion should consider C++0x
2928/// "explicit" conversion functions as well as non-explicit conversion
2929/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002930static OverloadingResult
2931IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002932 UserDefinedConversionSequence &User,
2933 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002934 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002935 // Whether we will only visit constructors.
2936 bool ConstructorsOnly = false;
2937
2938 // If the type we are conversion to is a class type, enumerate its
2939 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002940 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002941 // C++ [over.match.ctor]p1:
2942 // When objects of class type are direct-initialized (8.5), or
2943 // copy-initialized from an expression of the same or a
2944 // derived class type (8.5), overload resolution selects the
2945 // constructor. [...] For copy-initialization, the candidate
2946 // functions are all the converting constructors (12.3.1) of
2947 // that class. The argument list is the expression-list within
2948 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002949 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002950 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002951 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002952 ConstructorsOnly = true;
2953
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002954 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002955 // RequireCompleteType may have returned true due to some invalid decl
2956 // during template instantiation, but ToType may be complete enough now
2957 // to try to recover.
2958 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002959 // We're not going to find any constructors.
2960 } else if (CXXRecordDecl *ToRecordDecl
2961 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002962
2963 Expr **Args = &From;
2964 unsigned NumArgs = 1;
2965 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002966 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002967 // But first, see if there is an init-list-contructor that will work.
2968 OverloadingResult Result = IsInitializerListConstructorConversion(
2969 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2970 if (Result != OR_No_Viable_Function)
2971 return Result;
2972 // Never mind.
2973 CandidateSet.clear();
2974
2975 // If we're list-initializing, we pass the individual elements as
2976 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002977 Args = InitList->getInits();
2978 NumArgs = InitList->getNumInits();
2979 ListInitializing = true;
2980 }
2981
Douglas Gregor89ee6822009-02-28 01:32:25 +00002982 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002983 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002984 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002985 NamedDecl *D = *Con;
2986 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2987
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002988 // Find the constructor (which may be a template).
2989 CXXConstructorDecl *Constructor = 0;
2990 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002991 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002992 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002993 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002994 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2995 else
John McCalla0296f72010-03-19 07:35:19 +00002996 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002998 bool Usable = !Constructor->isInvalidDecl();
2999 if (ListInitializing)
3000 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3001 else
3002 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3003 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003004 bool SuppressUserConversions = !ConstructorsOnly;
3005 if (SuppressUserConversions && ListInitializing) {
3006 SuppressUserConversions = false;
3007 if (NumArgs == 1) {
3008 // If the first argument is (a reference to) the target type,
3009 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003010 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3011 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003012 }
3013 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003014 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003015 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3016 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003017 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003018 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003019 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003020 // Allow one user-defined conversion when user specifies a
3021 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003022 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003023 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003024 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003025 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003026 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003027 }
3028 }
3029
Douglas Gregor5ab11652010-04-17 22:01:05 +00003030 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003031 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003032 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003033 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003034 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003035 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003036 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003037 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3038 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00003039 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003040 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003041 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003042 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003043 DeclAccessPair FoundDecl = I.getPair();
3044 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003045 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3046 if (isa<UsingShadowDecl>(D))
3047 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3048
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003049 CXXConversionDecl *Conv;
3050 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003051 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3052 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003053 else
John McCallda4458e2010-03-31 01:36:47 +00003054 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003055
3056 if (AllowExplicit || !Conv->isExplicit()) {
3057 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003058 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3059 ActingContext, From, ToType,
3060 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003061 else
John McCall5c32be02010-08-24 20:38:10 +00003062 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3063 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003064 }
3065 }
3066 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003067 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003068
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003069 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3070
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003071 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003072 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003073 case OR_Success:
3074 // Record the standard conversion we used and the conversion function.
3075 if (CXXConstructorDecl *Constructor
3076 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003077 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003078
John McCall5c32be02010-08-24 20:38:10 +00003079 // C++ [over.ics.user]p1:
3080 // If the user-defined conversion is specified by a
3081 // constructor (12.3.1), the initial standard conversion
3082 // sequence converts the source type to the type required by
3083 // the argument of the constructor.
3084 //
3085 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003086 if (isa<InitListExpr>(From)) {
3087 // Initializer lists don't have conversions as such.
3088 User.Before.setAsIdentityConversion();
3089 } else {
3090 if (Best->Conversions[0].isEllipsis())
3091 User.EllipsisConversion = true;
3092 else {
3093 User.Before = Best->Conversions[0].Standard;
3094 User.EllipsisConversion = false;
3095 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003096 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003097 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003098 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003099 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003100 User.After.setAsIdentityConversion();
3101 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3102 User.After.setAllToTypes(ToType);
3103 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003104 }
3105 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003106 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003107 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003108
John McCall5c32be02010-08-24 20:38:10 +00003109 // C++ [over.ics.user]p1:
3110 //
3111 // [...] If the user-defined conversion is specified by a
3112 // conversion function (12.3.2), the initial standard
3113 // conversion sequence converts the source type to the
3114 // implicit object parameter of the conversion function.
3115 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003116 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003117 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003118 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003119 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003120
John McCall5c32be02010-08-24 20:38:10 +00003121 // C++ [over.ics.user]p2:
3122 // The second standard conversion sequence converts the
3123 // result of the user-defined conversion to the target type
3124 // for the sequence. Since an implicit conversion sequence
3125 // is an initialization, the special rules for
3126 // initialization by user-defined conversion apply when
3127 // selecting the best user-defined conversion for a
3128 // user-defined conversion sequence (see 13.3.3 and
3129 // 13.3.3.1).
3130 User.After = Best->FinalConversion;
3131 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003132 }
David Blaikie8a40f702012-01-17 06:56:22 +00003133 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003134
John McCall5c32be02010-08-24 20:38:10 +00003135 case OR_No_Viable_Function:
3136 return OR_No_Viable_Function;
3137 case OR_Deleted:
3138 // No conversion here! We're done.
3139 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140
John McCall5c32be02010-08-24 20:38:10 +00003141 case OR_Ambiguous:
3142 return OR_Ambiguous;
3143 }
3144
David Blaikie8a40f702012-01-17 06:56:22 +00003145 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003146}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003148bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003149Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003150 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003151 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003153 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003154 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003155 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003156 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003157 diag::err_typecheck_ambiguous_condition)
3158 << From->getType() << ToType << From->getSourceRange();
3159 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003160 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003161 diag::err_typecheck_nonviable_condition)
3162 << From->getType() << ToType << From->getSourceRange();
3163 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003164 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003167}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003168
Douglas Gregor2837aa22012-02-22 17:32:19 +00003169/// \brief Compare the user-defined conversion functions or constructors
3170/// of two user-defined conversion sequences to determine whether any ordering
3171/// is possible.
3172static ImplicitConversionSequence::CompareKind
3173compareConversionFunctions(Sema &S,
3174 FunctionDecl *Function1,
3175 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003176 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003177 return ImplicitConversionSequence::Indistinguishable;
3178
3179 // Objective-C++:
3180 // If both conversion functions are implicitly-declared conversions from
3181 // a lambda closure type to a function pointer and a block pointer,
3182 // respectively, always prefer the conversion to a function pointer,
3183 // because the function pointer is more lightweight and is more likely
3184 // to keep code working.
3185 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3186 if (!Conv1)
3187 return ImplicitConversionSequence::Indistinguishable;
3188
3189 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3190 if (!Conv2)
3191 return ImplicitConversionSequence::Indistinguishable;
3192
3193 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3194 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3195 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3196 if (Block1 != Block2)
3197 return Block1? ImplicitConversionSequence::Worse
3198 : ImplicitConversionSequence::Better;
3199 }
3200
3201 return ImplicitConversionSequence::Indistinguishable;
3202}
3203
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003204/// CompareImplicitConversionSequences - Compare two implicit
3205/// conversion sequences to determine whether one is better than the
3206/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003207static ImplicitConversionSequence::CompareKind
3208CompareImplicitConversionSequences(Sema &S,
3209 const ImplicitConversionSequence& ICS1,
3210 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003211{
3212 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3213 // conversion sequences (as defined in 13.3.3.1)
3214 // -- a standard conversion sequence (13.3.3.1.1) is a better
3215 // conversion sequence than a user-defined conversion sequence or
3216 // an ellipsis conversion sequence, and
3217 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3218 // conversion sequence than an ellipsis conversion sequence
3219 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003220 //
John McCall0d1da222010-01-12 00:44:57 +00003221 // C++0x [over.best.ics]p10:
3222 // For the purpose of ranking implicit conversion sequences as
3223 // described in 13.3.3.2, the ambiguous conversion sequence is
3224 // treated as a user-defined sequence that is indistinguishable
3225 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003226 if (ICS1.getKindRank() < ICS2.getKindRank())
3227 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003228 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003229 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003230
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003231 // The following checks require both conversion sequences to be of
3232 // the same kind.
3233 if (ICS1.getKind() != ICS2.getKind())
3234 return ImplicitConversionSequence::Indistinguishable;
3235
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003236 ImplicitConversionSequence::CompareKind Result =
3237 ImplicitConversionSequence::Indistinguishable;
3238
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003239 // Two implicit conversion sequences of the same form are
3240 // indistinguishable conversion sequences unless one of the
3241 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003242 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003243 Result = CompareStandardConversionSequences(S,
3244 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003245 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003246 // User-defined conversion sequence U1 is a better conversion
3247 // sequence than another user-defined conversion sequence U2 if
3248 // they contain the same user-defined conversion function or
3249 // constructor and if the second standard conversion sequence of
3250 // U1 is better than the second standard conversion sequence of
3251 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003252 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003253 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003254 Result = CompareStandardConversionSequences(S,
3255 ICS1.UserDefined.After,
3256 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003257 else
3258 Result = compareConversionFunctions(S,
3259 ICS1.UserDefined.ConversionFunction,
3260 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003261 }
3262
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003263 // List-initialization sequence L1 is a better conversion sequence than
3264 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3265 // for some X and L2 does not.
3266 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003267 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003268 ICS1.isListInitializationSequence() &&
3269 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003270 if (ICS1.isStdInitializerListElement() &&
3271 !ICS2.isStdInitializerListElement())
3272 return ImplicitConversionSequence::Better;
3273 if (!ICS1.isStdInitializerListElement() &&
3274 ICS2.isStdInitializerListElement())
3275 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003276 }
3277
3278 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003279}
3280
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003281static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3282 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3283 Qualifiers Quals;
3284 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003285 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003288 return Context.hasSameUnqualifiedType(T1, T2);
3289}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003291// Per 13.3.3.2p3, compare the given standard conversion sequences to
3292// determine if one is a proper subset of the other.
3293static ImplicitConversionSequence::CompareKind
3294compareStandardConversionSubsets(ASTContext &Context,
3295 const StandardConversionSequence& SCS1,
3296 const StandardConversionSequence& SCS2) {
3297 ImplicitConversionSequence::CompareKind Result
3298 = ImplicitConversionSequence::Indistinguishable;
3299
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003301 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003302 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3303 return ImplicitConversionSequence::Better;
3304 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3305 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003307 if (SCS1.Second != SCS2.Second) {
3308 if (SCS1.Second == ICK_Identity)
3309 Result = ImplicitConversionSequence::Better;
3310 else if (SCS2.Second == ICK_Identity)
3311 Result = ImplicitConversionSequence::Worse;
3312 else
3313 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003314 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003315 return ImplicitConversionSequence::Indistinguishable;
3316
3317 if (SCS1.Third == SCS2.Third) {
3318 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3319 : ImplicitConversionSequence::Indistinguishable;
3320 }
3321
3322 if (SCS1.Third == ICK_Identity)
3323 return Result == ImplicitConversionSequence::Worse
3324 ? ImplicitConversionSequence::Indistinguishable
3325 : ImplicitConversionSequence::Better;
3326
3327 if (SCS2.Third == ICK_Identity)
3328 return Result == ImplicitConversionSequence::Better
3329 ? ImplicitConversionSequence::Indistinguishable
3330 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003332 return ImplicitConversionSequence::Indistinguishable;
3333}
3334
Douglas Gregore696ebb2011-01-26 14:52:12 +00003335/// \brief Determine whether one of the given reference bindings is better
3336/// than the other based on what kind of bindings they are.
3337static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3338 const StandardConversionSequence &SCS2) {
3339 // C++0x [over.ics.rank]p3b4:
3340 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3341 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003343 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003345 // reference*.
3346 //
3347 // FIXME: Rvalue references. We're going rogue with the above edits,
3348 // because the semantics in the current C++0x working paper (N3225 at the
3349 // time of this writing) break the standard definition of std::forward
3350 // and std::reference_wrapper when dealing with references to functions.
3351 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003352 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3353 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3354 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
Douglas Gregore696ebb2011-01-26 14:52:12 +00003356 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3357 SCS2.IsLvalueReference) ||
3358 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3359 !SCS2.IsLvalueReference);
3360}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003361
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003362/// CompareStandardConversionSequences - Compare two standard
3363/// conversion sequences to determine whether one is better than the
3364/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003365static ImplicitConversionSequence::CompareKind
3366CompareStandardConversionSequences(Sema &S,
3367 const StandardConversionSequence& SCS1,
3368 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003369{
3370 // Standard conversion sequence S1 is a better conversion sequence
3371 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3372
3373 // -- S1 is a proper subsequence of S2 (comparing the conversion
3374 // sequences in the canonical form defined by 13.3.3.1.1,
3375 // excluding any Lvalue Transformation; the identity conversion
3376 // sequence is considered to be a subsequence of any
3377 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003378 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003379 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003380 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003381
3382 // -- the rank of S1 is better than the rank of S2 (by the rules
3383 // defined below), or, if not that,
3384 ImplicitConversionRank Rank1 = SCS1.getRank();
3385 ImplicitConversionRank Rank2 = SCS2.getRank();
3386 if (Rank1 < Rank2)
3387 return ImplicitConversionSequence::Better;
3388 else if (Rank2 < Rank1)
3389 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003390
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003391 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3392 // are indistinguishable unless one of the following rules
3393 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003394
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003395 // A conversion that is not a conversion of a pointer, or
3396 // pointer to member, to bool is better than another conversion
3397 // that is such a conversion.
3398 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3399 return SCS2.isPointerConversionToBool()
3400 ? ImplicitConversionSequence::Better
3401 : ImplicitConversionSequence::Worse;
3402
Douglas Gregor5c407d92008-10-23 00:40:37 +00003403 // C++ [over.ics.rank]p4b2:
3404 //
3405 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003406 // conversion of B* to A* is better than conversion of B* to
3407 // void*, and conversion of A* to void* is better than conversion
3408 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003409 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003410 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003411 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003412 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003413 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3414 // Exactly one of the conversion sequences is a conversion to
3415 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003416 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3417 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003418 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3419 // Neither conversion sequence converts to a void pointer; compare
3420 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003421 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003422 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003423 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003424 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3425 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003426 // Both conversion sequences are conversions to void
3427 // pointers. Compare the source types to determine if there's an
3428 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003429 QualType FromType1 = SCS1.getFromType();
3430 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003431
3432 // Adjust the types we're converting from via the array-to-pointer
3433 // conversion, if we need to.
3434 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003435 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003436 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003437 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003438
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003439 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3440 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003441
John McCall5c32be02010-08-24 20:38:10 +00003442 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003443 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003444 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003445 return ImplicitConversionSequence::Worse;
3446
3447 // Objective-C++: If one interface is more specific than the
3448 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003449 const ObjCObjectPointerType* FromObjCPtr1
3450 = FromType1->getAs<ObjCObjectPointerType>();
3451 const ObjCObjectPointerType* FromObjCPtr2
3452 = FromType2->getAs<ObjCObjectPointerType>();
3453 if (FromObjCPtr1 && FromObjCPtr2) {
3454 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3455 FromObjCPtr2);
3456 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3457 FromObjCPtr1);
3458 if (AssignLeft != AssignRight) {
3459 return AssignLeft? ImplicitConversionSequence::Better
3460 : ImplicitConversionSequence::Worse;
3461 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003462 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003463 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003464
3465 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3466 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003467 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003468 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003469 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003470
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003471 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003472 // Check for a better reference binding based on the kind of bindings.
3473 if (isBetterReferenceBindingKind(SCS1, SCS2))
3474 return ImplicitConversionSequence::Better;
3475 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3476 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Sebastian Redlb28b4072009-03-22 23:49:27 +00003478 // C++ [over.ics.rank]p3b4:
3479 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3480 // which the references refer are the same type except for
3481 // top-level cv-qualifiers, and the type to which the reference
3482 // initialized by S2 refers is more cv-qualified than the type
3483 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003484 QualType T1 = SCS1.getToType(2);
3485 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003486 T1 = S.Context.getCanonicalType(T1);
3487 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003488 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003489 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3490 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003491 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003492 // Objective-C++ ARC: If the references refer to objects with different
3493 // lifetimes, prefer bindings that don't change lifetime.
3494 if (SCS1.ObjCLifetimeConversionBinding !=
3495 SCS2.ObjCLifetimeConversionBinding) {
3496 return SCS1.ObjCLifetimeConversionBinding
3497 ? ImplicitConversionSequence::Worse
3498 : ImplicitConversionSequence::Better;
3499 }
3500
Chandler Carruth8e543b32010-12-12 08:17:55 +00003501 // If the type is an array type, promote the element qualifiers to the
3502 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003503 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003504 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003505 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003506 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003507 if (T2.isMoreQualifiedThan(T1))
3508 return ImplicitConversionSequence::Better;
3509 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003510 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003511 }
3512 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003513
Francois Pichet08d2fa02011-09-18 21:37:37 +00003514 // In Microsoft mode, prefer an integral conversion to a
3515 // floating-to-integral conversion if the integral conversion
3516 // is between types of the same size.
3517 // For example:
3518 // void f(float);
3519 // void f(int);
3520 // int main {
3521 // long a;
3522 // f(a);
3523 // }
3524 // Here, MSVC will call f(int) instead of generating a compile error
3525 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003526 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003527 SCS1.Second == ICK_Integral_Conversion &&
3528 SCS2.Second == ICK_Floating_Integral &&
3529 S.Context.getTypeSize(SCS1.getFromType()) ==
3530 S.Context.getTypeSize(SCS1.getToType(2)))
3531 return ImplicitConversionSequence::Better;
3532
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003533 return ImplicitConversionSequence::Indistinguishable;
3534}
3535
3536/// CompareQualificationConversions - Compares two standard conversion
3537/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003538/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3539ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003540CompareQualificationConversions(Sema &S,
3541 const StandardConversionSequence& SCS1,
3542 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003543 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003544 // -- S1 and S2 differ only in their qualification conversion and
3545 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3546 // cv-qualification signature of type T1 is a proper subset of
3547 // the cv-qualification signature of type T2, and S1 is not the
3548 // deprecated string literal array-to-pointer conversion (4.2).
3549 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3550 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3551 return ImplicitConversionSequence::Indistinguishable;
3552
3553 // FIXME: the example in the standard doesn't use a qualification
3554 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003555 QualType T1 = SCS1.getToType(2);
3556 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003557 T1 = S.Context.getCanonicalType(T1);
3558 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003559 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003560 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3561 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003562
3563 // If the types are the same, we won't learn anything by unwrapped
3564 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003565 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003566 return ImplicitConversionSequence::Indistinguishable;
3567
Chandler Carruth607f38e2009-12-29 07:16:59 +00003568 // If the type is an array type, promote the element qualifiers to the type
3569 // for comparison.
3570 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003571 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003572 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003573 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003574
Mike Stump11289f42009-09-09 15:08:12 +00003575 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003576 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003577
3578 // Objective-C++ ARC:
3579 // Prefer qualification conversions not involving a change in lifetime
3580 // to qualification conversions that do not change lifetime.
3581 if (SCS1.QualificationIncludesObjCLifetime !=
3582 SCS2.QualificationIncludesObjCLifetime) {
3583 Result = SCS1.QualificationIncludesObjCLifetime
3584 ? ImplicitConversionSequence::Worse
3585 : ImplicitConversionSequence::Better;
3586 }
3587
John McCall5c32be02010-08-24 20:38:10 +00003588 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003589 // Within each iteration of the loop, we check the qualifiers to
3590 // determine if this still looks like a qualification
3591 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003592 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003593 // until there are no more pointers or pointers-to-members left
3594 // to unwrap. This essentially mimics what
3595 // IsQualificationConversion does, but here we're checking for a
3596 // strict subset of qualifiers.
3597 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3598 // The qualifiers are the same, so this doesn't tell us anything
3599 // about how the sequences rank.
3600 ;
3601 else if (T2.isMoreQualifiedThan(T1)) {
3602 // T1 has fewer qualifiers, so it could be the better sequence.
3603 if (Result == ImplicitConversionSequence::Worse)
3604 // Neither has qualifiers that are a subset of the other's
3605 // qualifiers.
3606 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003607
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003608 Result = ImplicitConversionSequence::Better;
3609 } else if (T1.isMoreQualifiedThan(T2)) {
3610 // T2 has fewer qualifiers, so it could be the better sequence.
3611 if (Result == ImplicitConversionSequence::Better)
3612 // Neither has qualifiers that are a subset of the other's
3613 // qualifiers.
3614 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003615
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003616 Result = ImplicitConversionSequence::Worse;
3617 } else {
3618 // Qualifiers are disjoint.
3619 return ImplicitConversionSequence::Indistinguishable;
3620 }
3621
3622 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003623 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003624 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003625 }
3626
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003627 // Check that the winning standard conversion sequence isn't using
3628 // the deprecated string literal array to pointer conversion.
3629 switch (Result) {
3630 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003631 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003632 Result = ImplicitConversionSequence::Indistinguishable;
3633 break;
3634
3635 case ImplicitConversionSequence::Indistinguishable:
3636 break;
3637
3638 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003639 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003640 Result = ImplicitConversionSequence::Indistinguishable;
3641 break;
3642 }
3643
3644 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003645}
3646
Douglas Gregor5c407d92008-10-23 00:40:37 +00003647/// CompareDerivedToBaseConversions - Compares two standard conversion
3648/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003649/// various kinds of derived-to-base conversions (C++
3650/// [over.ics.rank]p4b3). As part of these checks, we also look at
3651/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003652ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003653CompareDerivedToBaseConversions(Sema &S,
3654 const StandardConversionSequence& SCS1,
3655 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003656 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003657 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003658 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003659 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003660
3661 // Adjust the types we're converting from via the array-to-pointer
3662 // conversion, if we need to.
3663 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003664 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003665 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003666 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003667
3668 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003669 FromType1 = S.Context.getCanonicalType(FromType1);
3670 ToType1 = S.Context.getCanonicalType(ToType1);
3671 FromType2 = S.Context.getCanonicalType(FromType2);
3672 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003673
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003674 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003675 //
3676 // If class B is derived directly or indirectly from class A and
3677 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003678 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003679 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003680 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003681 SCS2.Second == ICK_Pointer_Conversion &&
3682 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3683 FromType1->isPointerType() && FromType2->isPointerType() &&
3684 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003685 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003686 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003687 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003688 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003689 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003690 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003691 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003692 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003693
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003694 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003696 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003697 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003698 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003699 return ImplicitConversionSequence::Worse;
3700 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003701
3702 // -- conversion of B* to A* is better than conversion of C* to A*,
3703 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003704 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003705 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003706 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003707 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003708 }
3709 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3710 SCS2.Second == ICK_Pointer_Conversion) {
3711 const ObjCObjectPointerType *FromPtr1
3712 = FromType1->getAs<ObjCObjectPointerType>();
3713 const ObjCObjectPointerType *FromPtr2
3714 = FromType2->getAs<ObjCObjectPointerType>();
3715 const ObjCObjectPointerType *ToPtr1
3716 = ToType1->getAs<ObjCObjectPointerType>();
3717 const ObjCObjectPointerType *ToPtr2
3718 = ToType2->getAs<ObjCObjectPointerType>();
3719
3720 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3721 // Apply the same conversion ranking rules for Objective-C pointer types
3722 // that we do for C++ pointers to class types. However, we employ the
3723 // Objective-C pseudo-subtyping relationship used for assignment of
3724 // Objective-C pointer types.
3725 bool FromAssignLeft
3726 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3727 bool FromAssignRight
3728 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3729 bool ToAssignLeft
3730 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3731 bool ToAssignRight
3732 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3733
3734 // A conversion to an a non-id object pointer type or qualified 'id'
3735 // type is better than a conversion to 'id'.
3736 if (ToPtr1->isObjCIdType() &&
3737 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3738 return ImplicitConversionSequence::Worse;
3739 if (ToPtr2->isObjCIdType() &&
3740 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3741 return ImplicitConversionSequence::Better;
3742
3743 // A conversion to a non-id object pointer type is better than a
3744 // conversion to a qualified 'id' type
3745 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3746 return ImplicitConversionSequence::Worse;
3747 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3748 return ImplicitConversionSequence::Better;
3749
3750 // A conversion to an a non-Class object pointer type or qualified 'Class'
3751 // type is better than a conversion to 'Class'.
3752 if (ToPtr1->isObjCClassType() &&
3753 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3754 return ImplicitConversionSequence::Worse;
3755 if (ToPtr2->isObjCClassType() &&
3756 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3757 return ImplicitConversionSequence::Better;
3758
3759 // A conversion to a non-Class object pointer type is better than a
3760 // conversion to a qualified 'Class' type.
3761 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3762 return ImplicitConversionSequence::Worse;
3763 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3764 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003765
Douglas Gregor058d3de2011-01-31 18:51:41 +00003766 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3767 if (S.Context.hasSameType(FromType1, FromType2) &&
3768 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3769 (ToAssignLeft != ToAssignRight))
3770 return ToAssignLeft? ImplicitConversionSequence::Worse
3771 : ImplicitConversionSequence::Better;
3772
3773 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3774 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3775 (FromAssignLeft != FromAssignRight))
3776 return FromAssignLeft? ImplicitConversionSequence::Better
3777 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003778 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003780
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003781 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003782 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3783 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3784 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003786 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003788 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003790 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003792 ToType2->getAs<MemberPointerType>();
3793 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3794 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3795 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3796 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3797 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3798 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3799 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3800 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003801 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003802 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003803 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003804 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003805 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003806 return ImplicitConversionSequence::Better;
3807 }
3808 // conversion of B::* to C::* is better than conversion of A::* to C::*
3809 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003810 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003811 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003812 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003813 return ImplicitConversionSequence::Worse;
3814 }
3815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Douglas Gregor5ab11652010-04-17 22:01:05 +00003817 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003818 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003819 // -- binding of an expression of type C to a reference of type
3820 // B& is better than binding an expression of type C to a
3821 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003822 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3823 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3824 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003825 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003826 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003827 return ImplicitConversionSequence::Worse;
3828 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003829
Douglas Gregor2fe98832008-11-03 19:09:14 +00003830 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003831 // -- binding of an expression of type B to a reference of type
3832 // A& is better than binding an expression of type C to a
3833 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003834 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3835 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3836 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003837 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003838 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003839 return ImplicitConversionSequence::Worse;
3840 }
3841 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842
Douglas Gregor5c407d92008-10-23 00:40:37 +00003843 return ImplicitConversionSequence::Indistinguishable;
3844}
3845
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003846/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3847/// determine whether they are reference-related,
3848/// reference-compatible, reference-compatible with added
3849/// qualification, or incompatible, for use in C++ initialization by
3850/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3851/// type, and the first type (T1) is the pointee type of the reference
3852/// type being initialized.
3853Sema::ReferenceCompareResult
3854Sema::CompareReferenceRelationship(SourceLocation Loc,
3855 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003856 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003857 bool &ObjCConversion,
3858 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003859 assert(!OrigT1->isReferenceType() &&
3860 "T1 must be the pointee type of the reference type");
3861 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3862
3863 QualType T1 = Context.getCanonicalType(OrigT1);
3864 QualType T2 = Context.getCanonicalType(OrigT2);
3865 Qualifiers T1Quals, T2Quals;
3866 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3867 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3868
3869 // C++ [dcl.init.ref]p4:
3870 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3871 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3872 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003873 DerivedToBase = false;
3874 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003875 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003876 if (UnqualT1 == UnqualT2) {
3877 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003878 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003879 IsDerivedFrom(UnqualT2, UnqualT1))
3880 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003881 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3882 UnqualT2->isObjCObjectOrInterfaceType() &&
3883 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3884 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003885 else
3886 return Ref_Incompatible;
3887
3888 // At this point, we know that T1 and T2 are reference-related (at
3889 // least).
3890
3891 // If the type is an array type, promote the element qualifiers to the type
3892 // for comparison.
3893 if (isa<ArrayType>(T1) && T1Quals)
3894 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3895 if (isa<ArrayType>(T2) && T2Quals)
3896 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3897
3898 // C++ [dcl.init.ref]p4:
3899 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3900 // reference-related to T2 and cv1 is the same cv-qualification
3901 // as, or greater cv-qualification than, cv2. For purposes of
3902 // overload resolution, cases for which cv1 is greater
3903 // cv-qualification than cv2 are identified as
3904 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003905 //
3906 // Note that we also require equivalence of Objective-C GC and address-space
3907 // qualifiers when performing these computations, so that e.g., an int in
3908 // address space 1 is not reference-compatible with an int in address
3909 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003910 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3911 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3912 T1Quals.removeObjCLifetime();
3913 T2Quals.removeObjCLifetime();
3914 ObjCLifetimeConversion = true;
3915 }
3916
Douglas Gregord517d552011-04-28 17:56:11 +00003917 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003918 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003919 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003920 return Ref_Compatible_With_Added_Qualification;
3921 else
3922 return Ref_Related;
3923}
3924
Douglas Gregor836a7e82010-08-11 02:15:33 +00003925/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003926/// with DeclType. Return true if something definite is found.
3927static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003928FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3929 QualType DeclType, SourceLocation DeclLoc,
3930 Expr *Init, QualType T2, bool AllowRvalues,
3931 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003932 assert(T2->isRecordType() && "Can only find conversions of record types.");
3933 CXXRecordDecl *T2RecordDecl
3934 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3935
3936 OverloadCandidateSet CandidateSet(DeclLoc);
3937 const UnresolvedSetImpl *Conversions
3938 = T2RecordDecl->getVisibleConversionFunctions();
3939 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3940 E = Conversions->end(); I != E; ++I) {
3941 NamedDecl *D = *I;
3942 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946 FunctionTemplateDecl *ConvTemplate
3947 = dyn_cast<FunctionTemplateDecl>(D);
3948 CXXConversionDecl *Conv;
3949 if (ConvTemplate)
3950 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3951 else
3952 Conv = cast<CXXConversionDecl>(D);
3953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003955 // explicit conversions, skip it.
3956 if (!AllowExplicit && Conv->isExplicit())
3957 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Douglas Gregor836a7e82010-08-11 02:15:33 +00003959 if (AllowRvalues) {
3960 bool DerivedToBase = false;
3961 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003962 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003963
3964 // If we are initializing an rvalue reference, don't permit conversion
3965 // functions that return lvalues.
3966 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3967 const ReferenceType *RefType
3968 = Conv->getConversionType()->getAs<LValueReferenceType>();
3969 if (RefType && !RefType->getPointeeType()->isFunctionType())
3970 continue;
3971 }
3972
Douglas Gregor836a7e82010-08-11 02:15:33 +00003973 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003974 S.CompareReferenceRelationship(
3975 DeclLoc,
3976 Conv->getConversionType().getNonReferenceType()
3977 .getUnqualifiedType(),
3978 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003979 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003980 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003981 continue;
3982 } else {
3983 // If the conversion function doesn't return a reference type,
3984 // it can't be considered for this conversion. An rvalue reference
3985 // is only acceptable if its referencee is a function type.
3986
3987 const ReferenceType *RefType =
3988 Conv->getConversionType()->getAs<ReferenceType>();
3989 if (!RefType ||
3990 (!RefType->isLValueReferenceType() &&
3991 !RefType->getPointeeType()->isFunctionType()))
3992 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994
Douglas Gregor836a7e82010-08-11 02:15:33 +00003995 if (ConvTemplate)
3996 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003997 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003998 else
3999 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004000 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00004001 }
4002
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004003 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4004
Sebastian Redld92badf2010-06-30 18:13:39 +00004005 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004006 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004007 case OR_Success:
4008 // C++ [over.ics.ref]p1:
4009 //
4010 // [...] If the parameter binds directly to the result of
4011 // applying a conversion function to the argument
4012 // expression, the implicit conversion sequence is a
4013 // user-defined conversion sequence (13.3.3.1.2), with the
4014 // second standard conversion sequence either an identity
4015 // conversion or, if the conversion function returns an
4016 // entity of a type that is a derived class of the parameter
4017 // type, a derived-to-base Conversion.
4018 if (!Best->FinalConversion.DirectBinding)
4019 return false;
4020
Chandler Carruth30141632011-02-25 19:41:05 +00004021 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004022 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004023 ICS.setUserDefined();
4024 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4025 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004026 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004027 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004028 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004029 ICS.UserDefined.EllipsisConversion = false;
4030 assert(ICS.UserDefined.After.ReferenceBinding &&
4031 ICS.UserDefined.After.DirectBinding &&
4032 "Expected a direct reference binding!");
4033 return true;
4034
4035 case OR_Ambiguous:
4036 ICS.setAmbiguous();
4037 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4038 Cand != CandidateSet.end(); ++Cand)
4039 if (Cand->Viable)
4040 ICS.Ambiguous.addConversion(Cand->Function);
4041 return true;
4042
4043 case OR_No_Viable_Function:
4044 case OR_Deleted:
4045 // There was no suitable conversion, or we found a deleted
4046 // conversion; continue with other checks.
4047 return false;
4048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
David Blaikie8a40f702012-01-17 06:56:22 +00004050 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004051}
4052
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004053/// \brief Compute an implicit conversion sequence for reference
4054/// initialization.
4055static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004056TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004057 SourceLocation DeclLoc,
4058 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004059 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004060 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4061
4062 // Most paths end in a failed conversion.
4063 ImplicitConversionSequence ICS;
4064 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4065
4066 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4067 QualType T2 = Init->getType();
4068
4069 // If the initializer is the address of an overloaded function, try
4070 // to resolve the overloaded function. If all goes well, T2 is the
4071 // type of the resulting function.
4072 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4073 DeclAccessPair Found;
4074 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4075 false, Found))
4076 T2 = Fn->getType();
4077 }
4078
4079 // Compute some basic properties of the types and the initializer.
4080 bool isRValRef = DeclType->isRValueReferenceType();
4081 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004082 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004083 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004084 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004085 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004086 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004087 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004088
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004089
Sebastian Redld92badf2010-06-30 18:13:39 +00004090 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004091 // A reference to type "cv1 T1" is initialized by an expression
4092 // of type "cv2 T2" as follows:
4093
Sebastian Redld92badf2010-06-30 18:13:39 +00004094 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004095 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004096 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4097 // reference-compatible with "cv2 T2," or
4098 //
4099 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4100 if (InitCategory.isLValue() &&
4101 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004102 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004103 // When a parameter of reference type binds directly (8.5.3)
4104 // to an argument expression, the implicit conversion sequence
4105 // is the identity conversion, unless the argument expression
4106 // has a type that is a derived class of the parameter type,
4107 // in which case the implicit conversion sequence is a
4108 // derived-to-base Conversion (13.3.3.1).
4109 ICS.setStandard();
4110 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004111 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4112 : ObjCConversion? ICK_Compatible_Conversion
4113 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004114 ICS.Standard.Third = ICK_Identity;
4115 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4116 ICS.Standard.setToType(0, T2);
4117 ICS.Standard.setToType(1, T1);
4118 ICS.Standard.setToType(2, T1);
4119 ICS.Standard.ReferenceBinding = true;
4120 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004121 ICS.Standard.IsLvalueReference = !isRValRef;
4122 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4123 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004124 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004125 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004126 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004127
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 // Nothing more to do: the inaccessibility/ambiguity check for
4129 // derived-to-base conversions is suppressed when we're
4130 // computing the implicit conversion sequence (C++
4131 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004132 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004133 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004134
Sebastian Redld92badf2010-06-30 18:13:39 +00004135 // -- has a class type (i.e., T2 is a class type), where T1 is
4136 // not reference-related to T2, and can be implicitly
4137 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4138 // is reference-compatible with "cv3 T3" 92) (this
4139 // conversion is selected by enumerating the applicable
4140 // conversion functions (13.3.1.6) and choosing the best
4141 // one through overload resolution (13.3)),
4142 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004144 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004145 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4146 Init, T2, /*AllowRvalues=*/false,
4147 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004148 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004149 }
4150 }
4151
Sebastian Redld92badf2010-06-30 18:13:39 +00004152 // -- Otherwise, the reference shall be an lvalue reference to a
4153 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004154 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004156 // We actually handle one oddity of C++ [over.ics.ref] at this
4157 // point, which is that, due to p2 (which short-circuits reference
4158 // binding by only attempting a simple conversion for non-direct
4159 // bindings) and p3's strange wording, we allow a const volatile
4160 // reference to bind to an rvalue. Hence the check for the presence
4161 // of "const" rather than checking for "const" being the only
4162 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004163 // This is also the point where rvalue references and lvalue inits no longer
4164 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004165 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004166 return ICS;
4167
Douglas Gregorf143cd52011-01-24 16:14:37 +00004168 // -- If the initializer expression
4169 //
4170 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004171 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004172 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4173 (InitCategory.isXValue() ||
4174 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4175 (InitCategory.isLValue() && T2->isFunctionType()))) {
4176 ICS.setStandard();
4177 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004179 : ObjCConversion? ICK_Compatible_Conversion
4180 : ICK_Identity;
4181 ICS.Standard.Third = ICK_Identity;
4182 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4183 ICS.Standard.setToType(0, T2);
4184 ICS.Standard.setToType(1, T1);
4185 ICS.Standard.setToType(2, T1);
4186 ICS.Standard.ReferenceBinding = true;
4187 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4188 // binding unless we're binding to a class prvalue.
4189 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4190 // allow the use of rvalue references in C++98/03 for the benefit of
4191 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004193 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004194 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004195 ICS.Standard.IsLvalueReference = !isRValRef;
4196 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004198 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004199 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004200 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203
Douglas Gregorf143cd52011-01-24 16:14:37 +00004204 // -- has a class type (i.e., T2 is a class type), where T1 is not
4205 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206 // an xvalue, class prvalue, or function lvalue of type
4207 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004208 // "cv3 T3",
4209 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004211 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004213 // class subobject).
4214 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004216 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4217 Init, T2, /*AllowRvalues=*/true,
4218 AllowExplicit)) {
4219 // In the second case, if the reference is an rvalue reference
4220 // and the second standard conversion sequence of the
4221 // user-defined conversion sequence includes an lvalue-to-rvalue
4222 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004224 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4225 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4226
Douglas Gregor95273c32011-01-21 16:36:05 +00004227 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004230 // -- Otherwise, a temporary of type "cv1 T1" is created and
4231 // initialized from the initializer expression using the
4232 // rules for a non-reference copy initialization (8.5). The
4233 // reference is then bound to the temporary. If T1 is
4234 // reference-related to T2, cv1 must be the same
4235 // cv-qualification as, or greater cv-qualification than,
4236 // cv2; otherwise, the program is ill-formed.
4237 if (RefRelationship == Sema::Ref_Related) {
4238 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4239 // we would be reference-compatible or reference-compatible with
4240 // added qualification. But that wasn't the case, so the reference
4241 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004242 //
4243 // Note that we only want to check address spaces and cvr-qualifiers here.
4244 // ObjC GC and lifetime qualifiers aren't important.
4245 Qualifiers T1Quals = T1.getQualifiers();
4246 Qualifiers T2Quals = T2.getQualifiers();
4247 T1Quals.removeObjCGCAttr();
4248 T1Quals.removeObjCLifetime();
4249 T2Quals.removeObjCGCAttr();
4250 T2Quals.removeObjCLifetime();
4251 if (!T1Quals.compatiblyIncludes(T2Quals))
4252 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004253 }
4254
4255 // If at least one of the types is a class type, the types are not
4256 // related, and we aren't allowed any user conversions, the
4257 // reference binding fails. This case is important for breaking
4258 // recursion, since TryImplicitConversion below will attempt to
4259 // create a temporary through the use of a copy constructor.
4260 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4261 (T1->isRecordType() || T2->isRecordType()))
4262 return ICS;
4263
Douglas Gregorcba72b12011-01-21 05:18:22 +00004264 // If T1 is reference-related to T2 and the reference is an rvalue
4265 // reference, the initializer expression shall not be an lvalue.
4266 if (RefRelationship >= Sema::Ref_Related &&
4267 isRValRef && Init->Classify(S.Context).isLValue())
4268 return ICS;
4269
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004270 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004271 // When a parameter of reference type is not bound directly to
4272 // an argument expression, the conversion sequence is the one
4273 // required to convert the argument expression to the
4274 // underlying type of the reference according to
4275 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4276 // to copy-initializing a temporary of the underlying type with
4277 // the argument expression. Any difference in top-level
4278 // cv-qualification is subsumed by the initialization itself
4279 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004280 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4281 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004282 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004283 /*CStyle=*/false,
4284 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004285
4286 // Of course, that's still a reference binding.
4287 if (ICS.isStandard()) {
4288 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004289 ICS.Standard.IsLvalueReference = !isRValRef;
4290 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4291 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004292 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004293 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004294 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004295 // Don't allow rvalue references to bind to lvalues.
4296 if (DeclType->isRValueReferenceType()) {
4297 if (const ReferenceType *RefType
4298 = ICS.UserDefined.ConversionFunction->getResultType()
4299 ->getAs<LValueReferenceType>()) {
4300 if (!RefType->getPointeeType()->isFunctionType()) {
4301 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4302 DeclType);
4303 return ICS;
4304 }
4305 }
4306 }
4307
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004308 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004309 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4310 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4311 ICS.UserDefined.After.BindsToRvalue = true;
4312 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4313 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004314 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004315
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004316 return ICS;
4317}
4318
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004319static ImplicitConversionSequence
4320TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4321 bool SuppressUserConversions,
4322 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004323 bool AllowObjCWritebackConversion,
4324 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004325
4326/// TryListConversion - Try to copy-initialize a value of type ToType from the
4327/// initializer list From.
4328static ImplicitConversionSequence
4329TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4330 bool SuppressUserConversions,
4331 bool InOverloadResolution,
4332 bool AllowObjCWritebackConversion) {
4333 // C++11 [over.ics.list]p1:
4334 // When an argument is an initializer list, it is not an expression and
4335 // special rules apply for converting it to a parameter type.
4336
4337 ImplicitConversionSequence Result;
4338 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004339 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004340
Sebastian Redl09edce02012-01-23 22:09:39 +00004341 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004342 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004343 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004344 return Result;
4345
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004346 // C++11 [over.ics.list]p2:
4347 // If the parameter type is std::initializer_list<X> or "array of X" and
4348 // all the elements can be implicitly converted to X, the implicit
4349 // conversion sequence is the worst conversion necessary to convert an
4350 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004351 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004352 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004353 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004354 X = S.Context.getBaseElementType(ToType);
4355 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004356 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004357 if (!X.isNull()) {
4358 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4359 Expr *Init = From->getInit(i);
4360 ImplicitConversionSequence ICS =
4361 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4362 InOverloadResolution,
4363 AllowObjCWritebackConversion);
4364 // If a single element isn't convertible, fail.
4365 if (ICS.isBad()) {
4366 Result = ICS;
4367 break;
4368 }
4369 // Otherwise, look for the worst conversion.
4370 if (Result.isBad() ||
4371 CompareImplicitConversionSequences(S, ICS, Result) ==
4372 ImplicitConversionSequence::Worse)
4373 Result = ICS;
4374 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004375
4376 // For an empty list, we won't have computed any conversion sequence.
4377 // Introduce the identity conversion sequence.
4378 if (From->getNumInits() == 0) {
4379 Result.setStandard();
4380 Result.Standard.setAsIdentityConversion();
4381 Result.Standard.setFromType(ToType);
4382 Result.Standard.setAllToTypes(ToType);
4383 }
4384
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004385 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004386 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004387 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004388 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004389
4390 // C++11 [over.ics.list]p3:
4391 // Otherwise, if the parameter is a non-aggregate class X and overload
4392 // resolution chooses a single best constructor [...] the implicit
4393 // conversion sequence is a user-defined conversion sequence. If multiple
4394 // constructors are viable but none is better than the others, the
4395 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004396 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4397 // This function can deal with initializer lists.
4398 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4399 /*AllowExplicit=*/false,
4400 InOverloadResolution, /*CStyle=*/false,
4401 AllowObjCWritebackConversion);
4402 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004403 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004404 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004405
4406 // C++11 [over.ics.list]p4:
4407 // Otherwise, if the parameter has an aggregate type which can be
4408 // initialized from the initializer list [...] the implicit conversion
4409 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004410 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004411 // Type is an aggregate, argument is an init list. At this point it comes
4412 // down to checking whether the initialization works.
4413 // FIXME: Find out whether this parameter is consumed or not.
4414 InitializedEntity Entity =
4415 InitializedEntity::InitializeParameter(S.Context, ToType,
4416 /*Consumed=*/false);
4417 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4418 Result.setUserDefined();
4419 Result.UserDefined.Before.setAsIdentityConversion();
4420 // Initializer lists don't have a type.
4421 Result.UserDefined.Before.setFromType(QualType());
4422 Result.UserDefined.Before.setAllToTypes(QualType());
4423
4424 Result.UserDefined.After.setAsIdentityConversion();
4425 Result.UserDefined.After.setFromType(ToType);
4426 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004427 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004428 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004429 return Result;
4430 }
4431
4432 // C++11 [over.ics.list]p5:
4433 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004434 if (ToType->isReferenceType()) {
4435 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4436 // mention initializer lists in any way. So we go by what list-
4437 // initialization would do and try to extrapolate from that.
4438
4439 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4440
4441 // If the initializer list has a single element that is reference-related
4442 // to the parameter type, we initialize the reference from that.
4443 if (From->getNumInits() == 1) {
4444 Expr *Init = From->getInit(0);
4445
4446 QualType T2 = Init->getType();
4447
4448 // If the initializer is the address of an overloaded function, try
4449 // to resolve the overloaded function. If all goes well, T2 is the
4450 // type of the resulting function.
4451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452 DeclAccessPair Found;
4453 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4454 Init, ToType, false, Found))
4455 T2 = Fn->getType();
4456 }
4457
4458 // Compute some basic properties of the types and the initializer.
4459 bool dummy1 = false;
4460 bool dummy2 = false;
4461 bool dummy3 = false;
4462 Sema::ReferenceCompareResult RefRelationship
4463 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4464 dummy2, dummy3);
4465
4466 if (RefRelationship >= Sema::Ref_Related)
4467 return TryReferenceInit(S, Init, ToType,
4468 /*FIXME:*/From->getLocStart(),
4469 SuppressUserConversions,
4470 /*AllowExplicit=*/false);
4471 }
4472
4473 // Otherwise, we bind the reference to a temporary created from the
4474 // initializer list.
4475 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4476 InOverloadResolution,
4477 AllowObjCWritebackConversion);
4478 if (Result.isFailure())
4479 return Result;
4480 assert(!Result.isEllipsis() &&
4481 "Sub-initialization cannot result in ellipsis conversion.");
4482
4483 // Can we even bind to a temporary?
4484 if (ToType->isRValueReferenceType() ||
4485 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4486 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4487 Result.UserDefined.After;
4488 SCS.ReferenceBinding = true;
4489 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4490 SCS.BindsToRvalue = true;
4491 SCS.BindsToFunctionLvalue = false;
4492 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4493 SCS.ObjCLifetimeConversionBinding = false;
4494 } else
4495 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4496 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004497 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004498 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004499
4500 // C++11 [over.ics.list]p6:
4501 // Otherwise, if the parameter type is not a class:
4502 if (!ToType->isRecordType()) {
4503 // - if the initializer list has one element, the implicit conversion
4504 // sequence is the one required to convert the element to the
4505 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004506 unsigned NumInits = From->getNumInits();
4507 if (NumInits == 1)
4508 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4509 SuppressUserConversions,
4510 InOverloadResolution,
4511 AllowObjCWritebackConversion);
4512 // - if the initializer list has no elements, the implicit conversion
4513 // sequence is the identity conversion.
4514 else if (NumInits == 0) {
4515 Result.setStandard();
4516 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004517 Result.Standard.setFromType(ToType);
4518 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004519 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004520 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004521 return Result;
4522 }
4523
4524 // C++11 [over.ics.list]p7:
4525 // In all cases other than those enumerated above, no conversion is possible
4526 return Result;
4527}
4528
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004529/// TryCopyInitialization - Try to copy-initialize a value of type
4530/// ToType from the expression From. Return the implicit conversion
4531/// sequence required to pass this argument, which may be a bad
4532/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004533/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004534/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004535static ImplicitConversionSequence
4536TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004538 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004539 bool AllowObjCWritebackConversion,
4540 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004541 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4542 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4543 InOverloadResolution,AllowObjCWritebackConversion);
4544
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004545 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004546 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004547 /*FIXME:*/From->getLocStart(),
4548 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004549 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004550
John McCall5c32be02010-08-24 20:38:10 +00004551 return TryImplicitConversion(S, From, ToType,
4552 SuppressUserConversions,
4553 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004554 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004555 /*CStyle=*/false,
4556 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004557}
4558
Anna Zaks1b068122011-07-28 19:46:48 +00004559static bool TryCopyInitialization(const CanQualType FromQTy,
4560 const CanQualType ToQTy,
4561 Sema &S,
4562 SourceLocation Loc,
4563 ExprValueKind FromVK) {
4564 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4565 ImplicitConversionSequence ICS =
4566 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4567
4568 return !ICS.isBad();
4569}
4570
Douglas Gregor436424c2008-11-18 23:14:02 +00004571/// TryObjectArgumentInitialization - Try to initialize the object
4572/// parameter of the given member function (@c Method) from the
4573/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004574static ImplicitConversionSequence
4575TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004576 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004577 CXXMethodDecl *Method,
4578 CXXRecordDecl *ActingContext) {
4579 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004580 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4581 // const volatile object.
4582 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4583 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004584 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004585
4586 // Set up the conversion sequence as a "bad" conversion, to allow us
4587 // to exit early.
4588 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004589
4590 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004591 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004592 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004593 FromType = PT->getPointeeType();
4594
Douglas Gregor02824322011-01-26 19:30:28 +00004595 // When we had a pointer, it's implicitly dereferenced, so we
4596 // better have an lvalue.
4597 assert(FromClassification.isLValue());
4598 }
4599
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004600 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004601
Douglas Gregor02824322011-01-26 19:30:28 +00004602 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004604 // parameter is
4605 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004606 // - "lvalue reference to cv X" for functions declared without a
4607 // ref-qualifier or with the & ref-qualifier
4608 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004609 // ref-qualifier
4610 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004612 // cv-qualification on the member function declaration.
4613 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004615 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004616 // (C++ [over.match.funcs]p5). We perform a simplified version of
4617 // reference binding here, that allows class rvalues to bind to
4618 // non-constant references.
4619
Douglas Gregor02824322011-01-26 19:30:28 +00004620 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004621 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004623 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004624 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004625 ICS.setBad(BadConversionSequence::bad_qualifiers,
4626 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004627 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004628 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004629
4630 // Check that we have either the same type or a derived type. It
4631 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004632 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004633 ImplicitConversionKind SecondKind;
4634 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4635 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004636 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004637 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004638 else {
John McCall65eb8792010-02-25 01:37:24 +00004639 ICS.setBad(BadConversionSequence::unrelated_class,
4640 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004641 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004642 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004643
Douglas Gregor02824322011-01-26 19:30:28 +00004644 // Check the ref-qualifier.
4645 switch (Method->getRefQualifier()) {
4646 case RQ_None:
4647 // Do nothing; we don't care about lvalueness or rvalueness.
4648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Douglas Gregor02824322011-01-26 19:30:28 +00004650 case RQ_LValue:
4651 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4652 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004654 ImplicitParamType);
4655 return ICS;
4656 }
4657 break;
4658
4659 case RQ_RValue:
4660 if (!FromClassification.isRValue()) {
4661 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004663 ImplicitParamType);
4664 return ICS;
4665 }
4666 break;
4667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Douglas Gregor436424c2008-11-18 23:14:02 +00004669 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004670 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004671 ICS.Standard.setAsIdentityConversion();
4672 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004673 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004674 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004675 ICS.Standard.ReferenceBinding = true;
4676 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004678 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004679 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4680 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4681 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004682 return ICS;
4683}
4684
4685/// PerformObjectArgumentInitialization - Perform initialization of
4686/// the implicit object parameter for the given Method with the given
4687/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004688ExprResult
4689Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004690 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004691 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004692 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004693 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004694 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004695 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004696
Douglas Gregor02824322011-01-26 19:30:28 +00004697 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004698 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004699 FromRecordType = PT->getPointeeType();
4700 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004701 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004702 } else {
4703 FromRecordType = From->getType();
4704 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004705 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004706 }
4707
John McCall6e9f8f62009-12-03 04:06:58 +00004708 // Note that we always use the true parent context when performing
4709 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004710 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004711 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4712 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004713 if (ICS.isBad()) {
4714 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4715 Qualifiers FromQs = FromRecordType.getQualifiers();
4716 Qualifiers ToQs = DestType.getQualifiers();
4717 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4718 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004719 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004720 diag::err_member_function_call_bad_cvr)
4721 << Method->getDeclName() << FromRecordType << (CVR - 1)
4722 << From->getSourceRange();
4723 Diag(Method->getLocation(), diag::note_previous_decl)
4724 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004725 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004726 }
4727 }
4728
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004729 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004730 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004731 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004732 }
Mike Stump11289f42009-09-09 15:08:12 +00004733
John Wiegley01296292011-04-08 18:41:53 +00004734 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4735 ExprResult FromRes =
4736 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4737 if (FromRes.isInvalid())
4738 return ExprError();
4739 From = FromRes.take();
4740 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004741
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004742 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004743 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004744 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004745 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004746}
4747
Douglas Gregor5fb53972009-01-14 15:45:31 +00004748/// TryContextuallyConvertToBool - Attempt to contextually convert the
4749/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004750static ImplicitConversionSequence
4751TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004752 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004753 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004754 // FIXME: Are these flags correct?
4755 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004756 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004757 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004758 /*CStyle=*/false,
4759 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004760}
4761
4762/// PerformContextuallyConvertToBool - Perform a contextual conversion
4763/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004764ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004765 if (checkPlaceholderForOverload(*this, From))
4766 return ExprError();
4767
John McCall5c32be02010-08-24 20:38:10 +00004768 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004769 if (!ICS.isBad())
4770 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Fariborz Jahanian76197412009-11-18 18:26:29 +00004772 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004773 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004774 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004775 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004776 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004777}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Richard Smithf8379a02012-01-18 23:55:52 +00004779/// Check that the specified conversion is permitted in a converted constant
4780/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4781/// is acceptable.
4782static bool CheckConvertedConstantConversions(Sema &S,
4783 StandardConversionSequence &SCS) {
4784 // Since we know that the target type is an integral or unscoped enumeration
4785 // type, most conversion kinds are impossible. All possible First and Third
4786 // conversions are fine.
4787 switch (SCS.Second) {
4788 case ICK_Identity:
4789 case ICK_Integral_Promotion:
4790 case ICK_Integral_Conversion:
4791 return true;
4792
4793 case ICK_Boolean_Conversion:
4794 // Conversion from an integral or unscoped enumeration type to bool is
4795 // classified as ICK_Boolean_Conversion, but it's also an integral
4796 // conversion, so it's permitted in a converted constant expression.
4797 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4798 SCS.getToType(2)->isBooleanType();
4799
4800 case ICK_Floating_Integral:
4801 case ICK_Complex_Real:
4802 return false;
4803
4804 case ICK_Lvalue_To_Rvalue:
4805 case ICK_Array_To_Pointer:
4806 case ICK_Function_To_Pointer:
4807 case ICK_NoReturn_Adjustment:
4808 case ICK_Qualification:
4809 case ICK_Compatible_Conversion:
4810 case ICK_Vector_Conversion:
4811 case ICK_Vector_Splat:
4812 case ICK_Derived_To_Base:
4813 case ICK_Pointer_Conversion:
4814 case ICK_Pointer_Member:
4815 case ICK_Block_Pointer_Conversion:
4816 case ICK_Writeback_Conversion:
4817 case ICK_Floating_Promotion:
4818 case ICK_Complex_Promotion:
4819 case ICK_Complex_Conversion:
4820 case ICK_Floating_Conversion:
4821 case ICK_TransparentUnionConversion:
4822 llvm_unreachable("unexpected second conversion kind");
4823
4824 case ICK_Num_Conversion_Kinds:
4825 break;
4826 }
4827
4828 llvm_unreachable("unknown conversion kind");
4829}
4830
4831/// CheckConvertedConstantExpression - Check that the expression From is a
4832/// converted constant expression of type T, perform the conversion and produce
4833/// the converted expression, per C++11 [expr.const]p3.
4834ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4835 llvm::APSInt &Value,
4836 CCEKind CCE) {
4837 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4838 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4839
4840 if (checkPlaceholderForOverload(*this, From))
4841 return ExprError();
4842
4843 // C++11 [expr.const]p3 with proposed wording fixes:
4844 // A converted constant expression of type T is a core constant expression,
4845 // implicitly converted to a prvalue of type T, where the converted
4846 // expression is a literal constant expression and the implicit conversion
4847 // sequence contains only user-defined conversions, lvalue-to-rvalue
4848 // conversions, integral promotions, and integral conversions other than
4849 // narrowing conversions.
4850 ImplicitConversionSequence ICS =
4851 TryImplicitConversion(From, T,
4852 /*SuppressUserConversions=*/false,
4853 /*AllowExplicit=*/false,
4854 /*InOverloadResolution=*/false,
4855 /*CStyle=*/false,
4856 /*AllowObjcWritebackConversion=*/false);
4857 StandardConversionSequence *SCS = 0;
4858 switch (ICS.getKind()) {
4859 case ImplicitConversionSequence::StandardConversion:
4860 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004861 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004862 diag::err_typecheck_converted_constant_expression_disallowed)
4863 << From->getType() << From->getSourceRange() << T;
4864 SCS = &ICS.Standard;
4865 break;
4866 case ImplicitConversionSequence::UserDefinedConversion:
4867 // We are converting from class type to an integral or enumeration type, so
4868 // the Before sequence must be trivial.
4869 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004870 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004871 diag::err_typecheck_converted_constant_expression_disallowed)
4872 << From->getType() << From->getSourceRange() << T;
4873 SCS = &ICS.UserDefined.After;
4874 break;
4875 case ImplicitConversionSequence::AmbiguousConversion:
4876 case ImplicitConversionSequence::BadConversion:
4877 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004878 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004879 diag::err_typecheck_converted_constant_expression)
4880 << From->getType() << From->getSourceRange() << T;
4881 return ExprError();
4882
4883 case ImplicitConversionSequence::EllipsisConversion:
4884 llvm_unreachable("ellipsis conversion in converted constant expression");
4885 }
4886
4887 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4888 if (Result.isInvalid())
4889 return Result;
4890
4891 // Check for a narrowing implicit conversion.
4892 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004893 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004894 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4895 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004896 case NK_Variable_Narrowing:
4897 // Implicit conversion to a narrower type, and the value is not a constant
4898 // expression. We'll diagnose this in a moment.
4899 case NK_Not_Narrowing:
4900 break;
4901
4902 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004903 Diag(From->getLocStart(),
4904 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4905 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004906 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004907 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004908 break;
4909
4910 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004911 Diag(From->getLocStart(),
4912 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4913 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004914 << CCE << /*Constant*/0 << From->getType() << T;
4915 break;
4916 }
4917
4918 // Check the expression is a constant expression.
4919 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4920 Expr::EvalResult Eval;
4921 Eval.Diag = &Notes;
4922
4923 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4924 // The expression can't be folded, so we can't keep it at this position in
4925 // the AST.
4926 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004927 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004928 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004929
4930 if (Notes.empty()) {
4931 // It's a constant expression.
4932 return Result;
4933 }
Richard Smithf8379a02012-01-18 23:55:52 +00004934 }
4935
4936 // It's not a constant expression. Produce an appropriate diagnostic.
4937 if (Notes.size() == 1 &&
4938 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4939 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4940 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004941 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004942 << CCE << From->getSourceRange();
4943 for (unsigned I = 0; I < Notes.size(); ++I)
4944 Diag(Notes[I].first, Notes[I].second);
4945 }
Richard Smith911e1422012-01-30 22:27:01 +00004946 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004947}
4948
John McCallfec112d2011-09-09 06:11:02 +00004949/// dropPointerConversions - If the given standard conversion sequence
4950/// involves any pointer conversions, remove them. This may change
4951/// the result type of the conversion sequence.
4952static void dropPointerConversion(StandardConversionSequence &SCS) {
4953 if (SCS.Second == ICK_Pointer_Conversion) {
4954 SCS.Second = ICK_Identity;
4955 SCS.Third = ICK_Identity;
4956 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4957 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004958}
John McCall5c32be02010-08-24 20:38:10 +00004959
John McCallfec112d2011-09-09 06:11:02 +00004960/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4961/// convert the expression From to an Objective-C pointer type.
4962static ImplicitConversionSequence
4963TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4964 // Do an implicit conversion to 'id'.
4965 QualType Ty = S.Context.getObjCIdType();
4966 ImplicitConversionSequence ICS
4967 = TryImplicitConversion(S, From, Ty,
4968 // FIXME: Are these flags correct?
4969 /*SuppressUserConversions=*/false,
4970 /*AllowExplicit=*/true,
4971 /*InOverloadResolution=*/false,
4972 /*CStyle=*/false,
4973 /*AllowObjCWritebackConversion=*/false);
4974
4975 // Strip off any final conversions to 'id'.
4976 switch (ICS.getKind()) {
4977 case ImplicitConversionSequence::BadConversion:
4978 case ImplicitConversionSequence::AmbiguousConversion:
4979 case ImplicitConversionSequence::EllipsisConversion:
4980 break;
4981
4982 case ImplicitConversionSequence::UserDefinedConversion:
4983 dropPointerConversion(ICS.UserDefined.After);
4984 break;
4985
4986 case ImplicitConversionSequence::StandardConversion:
4987 dropPointerConversion(ICS.Standard);
4988 break;
4989 }
4990
4991 return ICS;
4992}
4993
4994/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4995/// conversion of the expression From to an Objective-C pointer type.
4996ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004997 if (checkPlaceholderForOverload(*this, From))
4998 return ExprError();
4999
John McCall8b07ec22010-05-15 11:32:37 +00005000 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005001 ImplicitConversionSequence ICS =
5002 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005003 if (!ICS.isBad())
5004 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005005 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005006}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005007
Richard Smith8dd34252012-02-04 07:07:42 +00005008/// Determine whether the provided type is an integral type, or an enumeration
5009/// type of a permitted flavor.
5010static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5011 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5012 : T->isIntegralOrUnscopedEnumerationType();
5013}
5014
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005016/// enumeration type.
5017///
5018/// This routine will attempt to convert an expression of class type to an
5019/// integral or enumeration type, if that class type only has a single
5020/// conversion to an integral or enumeration type.
5021///
Douglas Gregor4799d032010-06-30 00:20:43 +00005022/// \param Loc The source location of the construct that requires the
5023/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005024///
James Dennett18348b62012-06-22 08:52:37 +00005025/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005026///
James Dennett18348b62012-06-22 08:52:37 +00005027/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005028///
Richard Smith8dd34252012-02-04 07:07:42 +00005029/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5030/// enumerations should be considered.
5031///
Douglas Gregor4799d032010-06-30 00:20:43 +00005032/// \returns The expression, converted to an integral or enumeration type if
5033/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034ExprResult
John McCallb268a282010-08-23 23:25:46 +00005035Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005036 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005037 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005038 // We can't perform any more checking for type-dependent expressions.
5039 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005040 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Eli Friedman1da70392012-01-26 00:26:18 +00005042 // Process placeholders immediately.
5043 if (From->hasPlaceholderType()) {
5044 ExprResult result = CheckPlaceholderExpr(From);
5045 if (result.isInvalid()) return result;
5046 From = result.take();
5047 }
5048
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005049 // If the expression already has integral or enumeration type, we're golden.
5050 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005051 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005052 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005053
5054 // FIXME: Check for missing '()' if T is a function type?
5055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 // 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 +00005057 // expression of integral or enumeration type.
5058 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005059 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005060 if (!Diagnoser.Suppress)
5061 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005062 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005065 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005066 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005067 ICEConvertDiagnoser &Diagnoser;
5068 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005069
Douglas Gregore2b37442012-05-04 22:38:52 +00005070 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5071 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005072
5073 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005074 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005075 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005076 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005077
5078 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005079 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005081 // Look for a conversion to an integral or enumeration type.
5082 UnresolvedSet<4> ViableConversions;
5083 UnresolvedSet<4> ExplicitConversions;
5084 const UnresolvedSetImpl *Conversions
5085 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005087 bool HadMultipleCandidates = (Conversions->size() > 1);
5088
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005089 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090 E = Conversions->end();
5091 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005092 ++I) {
5093 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005094 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5095 if (isIntegralOrEnumerationType(
5096 Conversion->getConversionType().getNonReferenceType(),
5097 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005098 if (Conversion->isExplicit())
5099 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5100 else
5101 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5102 }
Richard Smith8dd34252012-02-04 07:07:42 +00005103 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 switch (ViableConversions.size()) {
5107 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005108 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005109 DeclAccessPair Found = ExplicitConversions[0];
5110 CXXConversionDecl *Conversion
5111 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005113 // The user probably meant to invoke the given explicit
5114 // conversion; use it.
5115 QualType ConvTy
5116 = Conversion->getConversionType().getNonReferenceType();
5117 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005118 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119
Douglas Gregore2b37442012-05-04 22:38:52 +00005120 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005121 << FixItHint::CreateInsertion(From->getLocStart(),
5122 "static_cast<" + TypeStr + ">(")
5123 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5124 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005125 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126
5127 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005128 // explicit conversion function.
5129 if (isSFINAEContext())
5130 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005131
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005133 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5134 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005135 if (Result.isInvalid())
5136 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005137 // Record usage of conversion in an implicit cast.
5138 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5139 CK_UserDefinedConversion,
5140 Result.get(), 0,
5141 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005144 // We'll complain below about a non-integral condition type.
5145 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005146
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005147 case 1: {
5148 // Apply this conversion.
5149 DeclAccessPair Found = ViableConversions[0];
5150 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Douglas Gregor4799d032010-06-30 00:20:43 +00005152 CXXConversionDecl *Conversion
5153 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5154 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005156 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005157 if (isSFINAEContext())
5158 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Douglas Gregore2b37442012-05-04 22:38:52 +00005160 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5161 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005164 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5165 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005166 if (Result.isInvalid())
5167 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005168 // Record usage of conversion in an implicit cast.
5169 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5170 CK_UserDefinedConversion,
5171 Result.get(), 0,
5172 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005173 break;
5174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005176 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005177 if (Diagnoser.Suppress)
5178 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005179
Douglas Gregore2b37442012-05-04 22:38:52 +00005180 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005181 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5182 CXXConversionDecl *Conv
5183 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5184 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005185 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005186 }
John McCallb268a282010-08-23 23:25:46 +00005187 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Richard Smithf4c51d92012-02-04 09:53:13 +00005190 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005191 !Diagnoser.Suppress) {
5192 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5193 << From->getSourceRange();
5194 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005195
Eli Friedman1da70392012-01-26 00:26:18 +00005196 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005197}
5198
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005199/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005200/// candidate functions, using the given function call arguments. If
5201/// @p SuppressUserConversions, then don't allow user-defined
5202/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005203///
James Dennett2a4d13c2012-06-15 07:13:21 +00005204/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005205/// based on an incomplete set of function arguments. This feature is used by
5206/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005207void
5208Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005209 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005210 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005211 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005212 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005213 bool PartialOverloading,
5214 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005215 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005216 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005217 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005218 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005219 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005220
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005221 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005222 if (!isa<CXXConstructorDecl>(Method)) {
5223 // If we get here, it's because we're calling a member function
5224 // that is named without a member access expression (e.g.,
5225 // "this->f") that was either written explicitly or created
5226 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005227 // function, e.g., X::f(). We use an empty type for the implied
5228 // object argument (C++ [over.call.func]p3), and the acting context
5229 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005230 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005231 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005232 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005233 return;
5234 }
5235 // We treat a constructor like a non-member function, since its object
5236 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005237 }
5238
Douglas Gregorff7028a2009-11-13 23:59:09 +00005239 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005240 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005241
Douglas Gregor27381f32009-11-23 12:27:39 +00005242 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005243 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005244
Douglas Gregorffe14e32009-11-14 01:20:54 +00005245 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5246 // C++ [class.copy]p3:
5247 // A member function template is never instantiated to perform the copy
5248 // of a class object to an object of its class type.
5249 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005250 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005251 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005252 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5253 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005254 return;
5255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005256
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005257 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005258 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005259 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005260 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005261 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005262 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005263 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005264 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005266 unsigned NumArgsInProto = Proto->getNumArgs();
5267
5268 // (C++ 13.3.2p2): A candidate function having fewer than m
5269 // parameters is viable only if it has an ellipsis in its parameter
5270 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005271 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005272 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005273 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005274 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005275 return;
5276 }
5277
5278 // (C++ 13.3.2p2): A candidate function having more than m parameters
5279 // is viable only if the (m+1)st parameter has a default argument
5280 // (8.3.6). For the purposes of overload resolution, the
5281 // parameter list is truncated on the right, so that there are
5282 // exactly m parameters.
5283 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005284 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005285 // Not enough arguments.
5286 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005287 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005288 return;
5289 }
5290
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005291 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005292 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005293 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5294 if (CheckCUDATarget(Caller, Function)) {
5295 Candidate.Viable = false;
5296 Candidate.FailureKind = ovl_fail_bad_target;
5297 return;
5298 }
5299
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005300 // Determine the implicit conversion sequences for each of the
5301 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005302 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005303 if (ArgIdx < NumArgsInProto) {
5304 // (C++ 13.3.2p3): for F to be a viable function, there shall
5305 // exist for each argument an implicit conversion sequence
5306 // (13.3.3.1) that converts that argument to the corresponding
5307 // parameter of F.
5308 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005309 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005310 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005312 /*InOverloadResolution=*/true,
5313 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005314 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005315 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005316 if (Candidate.Conversions[ArgIdx].isBad()) {
5317 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005318 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005319 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005320 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005321 } else {
5322 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5323 // argument for which there is no corresponding parameter is
5324 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005325 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005326 }
5327 }
5328}
5329
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005330/// \brief Add all of the function declarations in the given function set to
5331/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005332void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005333 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005334 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005335 bool SuppressUserConversions,
5336 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005337 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005338 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005340 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005341 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005342 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005343 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005344 Args.slice(1), CandidateSet,
5345 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005346 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005347 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005348 SuppressUserConversions);
5349 } else {
John McCalla0296f72010-03-19 07:35:19 +00005350 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005351 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5352 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005353 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005354 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005355 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005357 Args[0]->Classify(Context), Args.slice(1),
5358 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005359 else
John McCalla0296f72010-03-19 07:35:19 +00005360 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005361 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005362 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005363 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005364 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005365}
5366
John McCallf0f1cf02009-11-17 07:50:12 +00005367/// AddMethodCandidate - Adds a named decl (which is some kind of
5368/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005369void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005370 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005371 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005372 Expr **Args, unsigned NumArgs,
5373 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005374 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005375 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005376 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005377
5378 if (isa<UsingShadowDecl>(Decl))
5379 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
John McCallf0f1cf02009-11-17 07:50:12 +00005381 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5382 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5383 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005384 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5385 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005386 ObjectType, ObjectClassification,
5387 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005388 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005389 } else {
John McCalla0296f72010-03-19 07:35:19 +00005390 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005391 ObjectType, ObjectClassification,
5392 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005393 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005394 }
5395}
5396
Douglas Gregor436424c2008-11-18 23:14:02 +00005397/// AddMethodCandidate - Adds the given C++ member function to the set
5398/// of candidate functions, using the given function call arguments
5399/// and the object argument (@c Object). For example, in a call
5400/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5401/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5402/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005403/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005404void
John McCalla0296f72010-03-19 07:35:19 +00005405Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005406 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005407 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005408 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005409 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005410 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005411 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005412 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005413 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005414 assert(!isa<CXXConstructorDecl>(Method) &&
5415 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005416
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005417 if (!CandidateSet.isNewCandidate(Method))
5418 return;
5419
Douglas Gregor27381f32009-11-23 12:27:39 +00005420 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005421 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005422
Douglas Gregor436424c2008-11-18 23:14:02 +00005423 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005424 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005425 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005426 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005427 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005428 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005429 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005430
5431 unsigned NumArgsInProto = Proto->getNumArgs();
5432
5433 // (C++ 13.3.2p2): A candidate function having fewer than m
5434 // parameters is viable only if it has an ellipsis in its parameter
5435 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005436 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005437 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005438 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005439 return;
5440 }
5441
5442 // (C++ 13.3.2p2): A candidate function having more than m parameters
5443 // is viable only if the (m+1)st parameter has a default argument
5444 // (8.3.6). For the purposes of overload resolution, the
5445 // parameter list is truncated on the right, so that there are
5446 // exactly m parameters.
5447 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005448 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005449 // Not enough arguments.
5450 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005451 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005452 return;
5453 }
5454
5455 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005456
John McCall6e9f8f62009-12-03 04:06:58 +00005457 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005458 // The implicit object argument is ignored.
5459 Candidate.IgnoreObjectArgument = true;
5460 else {
5461 // Determine the implicit conversion sequence for the object
5462 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005463 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005464 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5465 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005466 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005467 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005468 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005469 return;
5470 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005471 }
5472
5473 // Determine the implicit conversion sequences for each of the
5474 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005475 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005476 if (ArgIdx < NumArgsInProto) {
5477 // (C++ 13.3.2p3): for F to be a viable function, there shall
5478 // exist for each argument an implicit conversion sequence
5479 // (13.3.3.1) that converts that argument to the corresponding
5480 // parameter of F.
5481 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005482 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005483 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005485 /*InOverloadResolution=*/true,
5486 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005487 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005488 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005489 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005490 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005491 break;
5492 }
5493 } else {
5494 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5495 // argument for which there is no corresponding parameter is
5496 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005497 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005498 }
5499 }
5500}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501
Douglas Gregor97628d62009-08-21 00:16:32 +00005502/// \brief Add a C++ member function template as a candidate to the candidate
5503/// set, using template argument deduction to produce an appropriate member
5504/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005505void
Douglas Gregor97628d62009-08-21 00:16:32 +00005506Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005507 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005508 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005509 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005510 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005511 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005512 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005513 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005514 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005515 if (!CandidateSet.isNewCandidate(MethodTmpl))
5516 return;
5517
Douglas Gregor97628d62009-08-21 00:16:32 +00005518 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005519 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005520 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005522 // candidate functions in the usual way.113) A given name can refer to one
5523 // or more function templates and also to a set of overloaded non-template
5524 // functions. In such a case, the candidate functions generated from each
5525 // function template are combined with the set of non-template candidate
5526 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005527 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005528 FunctionDecl *Specialization = 0;
5529 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005530 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5531 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005532 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005533 Candidate.FoundDecl = FoundDecl;
5534 Candidate.Function = MethodTmpl->getTemplatedDecl();
5535 Candidate.Viable = false;
5536 Candidate.FailureKind = ovl_fail_bad_deduction;
5537 Candidate.IsSurrogate = false;
5538 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005539 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005541 Info);
5542 return;
5543 }
Mike Stump11289f42009-09-09 15:08:12 +00005544
Douglas Gregor97628d62009-08-21 00:16:32 +00005545 // Add the function template specialization produced by template argument
5546 // deduction as a candidate.
5547 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005548 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005549 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005550 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005551 ActingContext, ObjectType, ObjectClassification, Args,
5552 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005553}
5554
Douglas Gregor05155d82009-08-21 23:19:43 +00005555/// \brief Add a C++ function template specialization as a candidate
5556/// in the candidate set, using template argument deduction to produce
5557/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005558void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005559Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005560 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005561 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005562 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005563 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005564 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005565 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5566 return;
5567
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005568 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005569 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005570 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005571 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005572 // candidate functions in the usual way.113) A given name can refer to one
5573 // or more function templates and also to a set of overloaded non-template
5574 // functions. In such a case, the candidate functions generated from each
5575 // function template are combined with the set of non-template candidate
5576 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005577 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005578 FunctionDecl *Specialization = 0;
5579 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005580 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5581 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005582 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005583 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005584 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5585 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005586 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005587 Candidate.IsSurrogate = false;
5588 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005589 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005590 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005591 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005592 return;
5593 }
Mike Stump11289f42009-09-09 15:08:12 +00005594
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005595 // Add the function template specialization produced by template argument
5596 // deduction as a candidate.
5597 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005598 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005599 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005600}
Mike Stump11289f42009-09-09 15:08:12 +00005601
Douglas Gregora1f013e2008-11-07 22:36:19 +00005602/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005603/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005604/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005605/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005606/// (which may or may not be the same type as the type that the
5607/// conversion function produces).
5608void
5609Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005610 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005611 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005612 Expr *From, QualType ToType,
5613 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005614 assert(!Conversion->getDescribedFunctionTemplate() &&
5615 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005616 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005617 if (!CandidateSet.isNewCandidate(Conversion))
5618 return;
5619
Douglas Gregor27381f32009-11-23 12:27:39 +00005620 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005621 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005622
Douglas Gregora1f013e2008-11-07 22:36:19 +00005623 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005624 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005625 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005626 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005627 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005628 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005629 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005630 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005631 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005632 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005633 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005634
Douglas Gregor6affc782010-08-19 15:37:02 +00005635 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636 // For conversion functions, the function is considered to be a member of
5637 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005638 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005639 //
5640 // Determine the implicit conversion sequence for the implicit
5641 // object parameter.
5642 QualType ImplicitParamType = From->getType();
5643 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5644 ImplicitParamType = FromPtrType->getPointeeType();
5645 CXXRecordDecl *ConversionContext
5646 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005648 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649 = TryObjectArgumentInitialization(*this, From->getType(),
5650 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005651 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
John McCall0d1da222010-01-12 00:44:57 +00005653 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005654 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005655 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005656 return;
5657 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005660 // derived to base as such conversions are given Conversion Rank. They only
5661 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5662 QualType FromCanon
5663 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5664 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5665 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5666 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005667 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005668 return;
5669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregora1f013e2008-11-07 22:36:19 +00005671 // To determine what the conversion from the result of calling the
5672 // conversion function to the type we're eventually trying to
5673 // convert to (ToType), we need to synthesize a call to the
5674 // conversion function and attempt copy initialization from it. This
5675 // makes sure that we get the right semantics with respect to
5676 // lvalues/rvalues and the type. Fortunately, we can allocate this
5677 // call on the stack and we don't need its arguments to be
5678 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005679 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005680 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005681 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5682 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005683 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005684 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005685
Richard Smith48d24642011-07-13 22:53:21 +00005686 QualType ConversionType = Conversion->getConversionType();
5687 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005688 Candidate.Viable = false;
5689 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5690 return;
5691 }
5692
Richard Smith48d24642011-07-13 22:53:21 +00005693 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005694
Mike Stump11289f42009-09-09 15:08:12 +00005695 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005696 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5697 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005698 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005699 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005700 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005701 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005702 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005703 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005704 /*InOverloadResolution=*/false,
5705 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005706
John McCall0d1da222010-01-12 00:44:57 +00005707 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005708 case ImplicitConversionSequence::StandardConversion:
5709 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005711 // C++ [over.ics.user]p3:
5712 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005714 // shall have exact match rank.
5715 if (Conversion->getPrimaryTemplate() &&
5716 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5717 Candidate.Viable = false;
5718 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregorcba72b12011-01-21 05:18:22 +00005721 // C++0x [dcl.init.ref]p5:
5722 // In the second case, if the reference is an rvalue reference and
5723 // the second standard conversion sequence of the user-defined
5724 // conversion sequence includes an lvalue-to-rvalue conversion, the
5725 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005727 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5728 Candidate.Viable = false;
5729 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5730 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005731 break;
5732
5733 case ImplicitConversionSequence::BadConversion:
5734 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005735 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005736 break;
5737
5738 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005739 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005740 "Can only end up with a standard conversion sequence or failure");
5741 }
5742}
5743
Douglas Gregor05155d82009-08-21 23:19:43 +00005744/// \brief Adds a conversion function template specialization
5745/// candidate to the overload set, using template argument deduction
5746/// to deduce the template arguments of the conversion function
5747/// template from the type that we are converting to (C++
5748/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005749void
Douglas Gregor05155d82009-08-21 23:19:43 +00005750Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005751 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005752 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005753 Expr *From, QualType ToType,
5754 OverloadCandidateSet &CandidateSet) {
5755 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5756 "Only conversion function templates permitted here");
5757
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005758 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5759 return;
5760
John McCallbc077cf2010-02-08 23:07:23 +00005761 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005762 CXXConversionDecl *Specialization = 0;
5763 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005764 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005765 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005766 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005767 Candidate.FoundDecl = FoundDecl;
5768 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5769 Candidate.Viable = false;
5770 Candidate.FailureKind = ovl_fail_bad_deduction;
5771 Candidate.IsSurrogate = false;
5772 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005773 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005775 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005776 return;
5777 }
Mike Stump11289f42009-09-09 15:08:12 +00005778
Douglas Gregor05155d82009-08-21 23:19:43 +00005779 // Add the conversion function template specialization produced by
5780 // template argument deduction as a candidate.
5781 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005782 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005783 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005784}
5785
Douglas Gregorab7897a2008-11-19 22:57:39 +00005786/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5787/// converts the given @c Object to a function pointer via the
5788/// conversion function @c Conversion, and then attempts to call it
5789/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5790/// the type of function that we'll eventually be calling.
5791void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005792 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005793 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005794 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005795 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005796 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005797 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005798 if (!CandidateSet.isNewCandidate(Conversion))
5799 return;
5800
Douglas Gregor27381f32009-11-23 12:27:39 +00005801 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005802 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005803
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005804 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005805 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005806 Candidate.Function = 0;
5807 Candidate.Surrogate = Conversion;
5808 Candidate.Viable = true;
5809 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005810 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005811 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005812
5813 // Determine the implicit conversion sequence for the implicit
5814 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005815 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005817 Object->Classify(Context),
5818 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005819 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005820 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005821 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005822 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005823 return;
5824 }
5825
5826 // The first conversion is actually a user-defined conversion whose
5827 // first conversion is ObjectInit's standard conversion (which is
5828 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005829 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005830 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005831 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005832 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005833 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005834 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005835 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005836 = Candidate.Conversions[0].UserDefined.Before;
5837 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5838
Mike Stump11289f42009-09-09 15:08:12 +00005839 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005840 unsigned NumArgsInProto = Proto->getNumArgs();
5841
5842 // (C++ 13.3.2p2): A candidate function having fewer than m
5843 // parameters is viable only if it has an ellipsis in its parameter
5844 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005845 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005846 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005847 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005848 return;
5849 }
5850
5851 // Function types don't have any default arguments, so just check if
5852 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005853 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005854 // Not enough arguments.
5855 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005856 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005857 return;
5858 }
5859
5860 // Determine the implicit conversion sequences for each of the
5861 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005862 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005863 if (ArgIdx < NumArgsInProto) {
5864 // (C++ 13.3.2p3): for F to be a viable function, there shall
5865 // exist for each argument an implicit conversion sequence
5866 // (13.3.3.1) that converts that argument to the corresponding
5867 // parameter of F.
5868 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005869 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005870 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005871 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005872 /*InOverloadResolution=*/false,
5873 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005874 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005875 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005876 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005877 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005878 break;
5879 }
5880 } else {
5881 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5882 // argument for which there is no corresponding parameter is
5883 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005884 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005885 }
5886 }
5887}
5888
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005889/// \brief Add overload candidates for overloaded operators that are
5890/// member functions.
5891///
5892/// Add the overloaded operator candidates that are member functions
5893/// for the operator Op that was used in an operator expression such
5894/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5895/// CandidateSet will store the added overload candidates. (C++
5896/// [over.match.oper]).
5897void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5898 SourceLocation OpLoc,
5899 Expr **Args, unsigned NumArgs,
5900 OverloadCandidateSet& CandidateSet,
5901 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005902 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5903
5904 // C++ [over.match.oper]p3:
5905 // For a unary operator @ with an operand of a type whose
5906 // cv-unqualified version is T1, and for a binary operator @ with
5907 // a left operand of a type whose cv-unqualified version is T1 and
5908 // a right operand of a type whose cv-unqualified version is T2,
5909 // three sets of candidate functions, designated member
5910 // candidates, non-member candidates and built-in candidates, are
5911 // constructed as follows:
5912 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005913
5914 // -- If T1 is a class type, the set of member candidates is the
5915 // result of the qualified lookup of T1::operator@
5916 // (13.3.1.1.1); otherwise, the set of member candidates is
5917 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005918 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005919 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005920 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005921 return;
Mike Stump11289f42009-09-09 15:08:12 +00005922
John McCall27b18f82009-11-17 02:14:36 +00005923 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5924 LookupQualifiedName(Operators, T1Rec->getDecl());
5925 Operators.suppressDiagnostics();
5926
Mike Stump11289f42009-09-09 15:08:12 +00005927 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005928 OperEnd = Operators.end();
5929 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005930 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005931 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005932 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005933 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005934 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005935 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005936}
5937
Douglas Gregora11693b2008-11-12 17:17:38 +00005938/// AddBuiltinCandidate - Add a candidate for a built-in
5939/// operator. ResultTy and ParamTys are the result and parameter types
5940/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005941/// arguments being passed to the candidate. IsAssignmentOperator
5942/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005943/// operator. NumContextualBoolArguments is the number of arguments
5944/// (at the beginning of the argument list) that will be contextually
5945/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005946void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005947 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005948 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005949 bool IsAssignmentOperator,
5950 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005951 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005952 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005953
Douglas Gregora11693b2008-11-12 17:17:38 +00005954 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005955 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005956 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005957 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005958 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005959 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005960 Candidate.BuiltinTypes.ResultTy = ResultTy;
5961 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5962 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5963
5964 // Determine the implicit conversion sequences for each of the
5965 // arguments.
5966 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005967 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005968 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005969 // C++ [over.match.oper]p4:
5970 // For the built-in assignment operators, conversions of the
5971 // left operand are restricted as follows:
5972 // -- no temporaries are introduced to hold the left operand, and
5973 // -- no user-defined conversions are applied to the left
5974 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005975 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005976 //
5977 // We block these conversions by turning off user-defined
5978 // conversions, since that is the only way that initialization of
5979 // a reference to a non-class type can occur from something that
5980 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005981 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005982 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005983 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005984 Candidate.Conversions[ArgIdx]
5985 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005986 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005987 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005988 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005989 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005990 /*InOverloadResolution=*/false,
5991 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005992 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005993 }
John McCall0d1da222010-01-12 00:44:57 +00005994 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005995 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005996 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005997 break;
5998 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005999 }
6000}
6001
6002/// BuiltinCandidateTypeSet - A set of types that will be used for the
6003/// candidate operator functions for built-in operators (C++
6004/// [over.built]). The types are separated into pointer types and
6005/// enumeration types.
6006class BuiltinCandidateTypeSet {
6007 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006008 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006009
6010 /// PointerTypes - The set of pointer types that will be used in the
6011 /// built-in candidates.
6012 TypeSet PointerTypes;
6013
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006014 /// MemberPointerTypes - The set of member pointer types that will be
6015 /// used in the built-in candidates.
6016 TypeSet MemberPointerTypes;
6017
Douglas Gregora11693b2008-11-12 17:17:38 +00006018 /// EnumerationTypes - The set of enumeration types that will be
6019 /// used in the built-in candidates.
6020 TypeSet EnumerationTypes;
6021
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006022 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006023 /// candidates.
6024 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006025
6026 /// \brief A flag indicating non-record types are viable candidates
6027 bool HasNonRecordTypes;
6028
6029 /// \brief A flag indicating whether either arithmetic or enumeration types
6030 /// were present in the candidate set.
6031 bool HasArithmeticOrEnumeralTypes;
6032
Douglas Gregor80af3132011-05-21 23:15:46 +00006033 /// \brief A flag indicating whether the nullptr type was present in the
6034 /// candidate set.
6035 bool HasNullPtrType;
6036
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006037 /// Sema - The semantic analysis instance where we are building the
6038 /// candidate type set.
6039 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006040
Douglas Gregora11693b2008-11-12 17:17:38 +00006041 /// Context - The AST context in which we will build the type sets.
6042 ASTContext &Context;
6043
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006044 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6045 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006046 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006047
6048public:
6049 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006050 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006051
Mike Stump11289f42009-09-09 15:08:12 +00006052 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006053 : HasNonRecordTypes(false),
6054 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006055 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006056 SemaRef(SemaRef),
6057 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006058
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006060 SourceLocation Loc,
6061 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006062 bool AllowExplicitConversions,
6063 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006064
6065 /// pointer_begin - First pointer type found;
6066 iterator pointer_begin() { return PointerTypes.begin(); }
6067
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006068 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006069 iterator pointer_end() { return PointerTypes.end(); }
6070
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006071 /// member_pointer_begin - First member pointer type found;
6072 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6073
6074 /// member_pointer_end - Past the last member pointer type found;
6075 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6076
Douglas Gregora11693b2008-11-12 17:17:38 +00006077 /// enumeration_begin - First enumeration type found;
6078 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6079
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006080 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006081 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006083 iterator vector_begin() { return VectorTypes.begin(); }
6084 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006085
6086 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6087 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006088 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006089};
6090
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006091/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006092/// the set of pointer types along with any more-qualified variants of
6093/// that type. For example, if @p Ty is "int const *", this routine
6094/// will add "int const *", "int const volatile *", "int const
6095/// restrict *", and "int const volatile restrict *" to the set of
6096/// pointer types. Returns true if the add of @p Ty itself succeeded,
6097/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006098///
6099/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006100bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006101BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6102 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006103
Douglas Gregora11693b2008-11-12 17:17:38 +00006104 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006105 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006106 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006108 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006109 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006110 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006111 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006112 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6113 PointeeTy = PTy->getPointeeType();
6114 buildObjCPtr = true;
6115 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006116 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006117 }
6118
Sebastian Redl4990a632009-11-18 20:39:26 +00006119 // Don't add qualified variants of arrays. For one, they're not allowed
6120 // (the qualifier would sink to the element type), and for another, the
6121 // only overload situation where it matters is subscript or pointer +- int,
6122 // and those shouldn't have qualifier variants anyway.
6123 if (PointeeTy->isArrayType())
6124 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006125
John McCall8ccfcb52009-09-24 19:53:00 +00006126 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006127 bool hasVolatile = VisibleQuals.hasVolatile();
6128 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
John McCall8ccfcb52009-09-24 19:53:00 +00006130 // Iterate through all strict supersets of BaseCVR.
6131 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6132 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006133 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006134 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006135
6136 // Skip over restrict if no restrict found anywhere in the types, or if
6137 // the type cannot be restrict-qualified.
6138 if ((CVR & Qualifiers::Restrict) &&
6139 (!hasRestrict ||
6140 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6141 continue;
6142
6143 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006144 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006145
6146 // Build qualified pointer type.
6147 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006148 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006149 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006150 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006151 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6152
6153 // Insert qualified pointer type.
6154 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006155 }
6156
6157 return true;
6158}
6159
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006160/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6161/// to the set of pointer types along with any more-qualified variants of
6162/// that type. For example, if @p Ty is "int const *", this routine
6163/// will add "int const *", "int const volatile *", "int const
6164/// restrict *", and "int const volatile restrict *" to the set of
6165/// pointer types. Returns true if the add of @p Ty itself succeeded,
6166/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006167///
6168/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006169bool
6170BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6171 QualType Ty) {
6172 // Insert this type.
6173 if (!MemberPointerTypes.insert(Ty))
6174 return false;
6175
John McCall8ccfcb52009-09-24 19:53:00 +00006176 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6177 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006178
John McCall8ccfcb52009-09-24 19:53:00 +00006179 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006180 // Don't add qualified variants of arrays. For one, they're not allowed
6181 // (the qualifier would sink to the element type), and for another, the
6182 // only overload situation where it matters is subscript or pointer +- int,
6183 // and those shouldn't have qualifier variants anyway.
6184 if (PointeeTy->isArrayType())
6185 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006186 const Type *ClassTy = PointerTy->getClass();
6187
6188 // Iterate through all strict supersets of the pointee type's CVR
6189 // qualifiers.
6190 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6191 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6192 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193
John McCall8ccfcb52009-09-24 19:53:00 +00006194 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006195 MemberPointerTypes.insert(
6196 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006197 }
6198
6199 return true;
6200}
6201
Douglas Gregora11693b2008-11-12 17:17:38 +00006202/// AddTypesConvertedFrom - Add each of the types to which the type @p
6203/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006204/// primarily interested in pointer types and enumeration types. We also
6205/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006206/// AllowUserConversions is true if we should look at the conversion
6207/// functions of a class type, and AllowExplicitConversions if we
6208/// should also include the explicit conversion functions of a class
6209/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006210void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006211BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006212 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006213 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006214 bool AllowExplicitConversions,
6215 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006216 // Only deal with canonical types.
6217 Ty = Context.getCanonicalType(Ty);
6218
6219 // Look through reference types; they aren't part of the type of an
6220 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006221 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006222 Ty = RefTy->getPointeeType();
6223
John McCall33ddac02011-01-19 10:06:00 +00006224 // If we're dealing with an array type, decay to the pointer.
6225 if (Ty->isArrayType())
6226 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6227
6228 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006229 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006230
Chandler Carruth00a38332010-12-13 01:44:01 +00006231 // Flag if we ever add a non-record type.
6232 const RecordType *TyRec = Ty->getAs<RecordType>();
6233 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6234
Chandler Carruth00a38332010-12-13 01:44:01 +00006235 // Flag if we encounter an arithmetic type.
6236 HasArithmeticOrEnumeralTypes =
6237 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6238
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006239 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6240 PointerTypes.insert(Ty);
6241 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006242 // Insert our type, and its more-qualified variants, into the set
6243 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006244 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006245 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006246 } else if (Ty->isMemberPointerType()) {
6247 // Member pointers are far easier, since the pointee can't be converted.
6248 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6249 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006250 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006251 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006252 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006253 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006254 // We treat vector types as arithmetic types in many contexts as an
6255 // extension.
6256 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006257 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006258 } else if (Ty->isNullPtrType()) {
6259 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006260 } else if (AllowUserConversions && TyRec) {
6261 // No conversion functions in incomplete types.
6262 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6263 return;
Mike Stump11289f42009-09-09 15:08:12 +00006264
Chandler Carruth00a38332010-12-13 01:44:01 +00006265 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6266 const UnresolvedSetImpl *Conversions
6267 = ClassDecl->getVisibleConversionFunctions();
6268 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6269 E = Conversions->end(); I != E; ++I) {
6270 NamedDecl *D = I.getDecl();
6271 if (isa<UsingShadowDecl>(D))
6272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006273
Chandler Carruth00a38332010-12-13 01:44:01 +00006274 // Skip conversion function templates; they don't tell us anything
6275 // about which builtin types we can convert to.
6276 if (isa<FunctionTemplateDecl>(D))
6277 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006278
Chandler Carruth00a38332010-12-13 01:44:01 +00006279 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6280 if (AllowExplicitConversions || !Conv->isExplicit()) {
6281 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6282 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006283 }
6284 }
6285 }
6286}
6287
Douglas Gregor84605ae2009-08-24 13:43:27 +00006288/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6289/// the volatile- and non-volatile-qualified assignment operators for the
6290/// given type to the candidate set.
6291static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6292 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006293 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006294 unsigned NumArgs,
6295 OverloadCandidateSet &CandidateSet) {
6296 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006297
Douglas Gregor84605ae2009-08-24 13:43:27 +00006298 // T& operator=(T&, T)
6299 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6300 ParamTypes[1] = T;
6301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6302 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006303
Douglas Gregor84605ae2009-08-24 13:43:27 +00006304 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6305 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006306 ParamTypes[0]
6307 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006308 ParamTypes[1] = T;
6309 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006310 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006311 }
6312}
Mike Stump11289f42009-09-09 15:08:12 +00006313
Sebastian Redl1054fae2009-10-25 17:03:50 +00006314/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6315/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006316static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6317 Qualifiers VRQuals;
6318 const RecordType *TyRec;
6319 if (const MemberPointerType *RHSMPType =
6320 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006321 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006322 else
6323 TyRec = ArgExpr->getType()->getAs<RecordType>();
6324 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006325 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006326 VRQuals.addVolatile();
6327 VRQuals.addRestrict();
6328 return VRQuals;
6329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006330
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006331 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006332 if (!ClassDecl->hasDefinition())
6333 return VRQuals;
6334
John McCallad371252010-01-20 00:46:10 +00006335 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006336 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
John McCallad371252010-01-20 00:46:10 +00006338 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006339 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006340 NamedDecl *D = I.getDecl();
6341 if (isa<UsingShadowDecl>(D))
6342 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6343 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006344 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6345 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6346 CanTy = ResTypeRef->getPointeeType();
6347 // Need to go down the pointer/mempointer chain and add qualifiers
6348 // as see them.
6349 bool done = false;
6350 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006351 if (CanTy.isRestrictQualified())
6352 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006353 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6354 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006355 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006356 CanTy->getAs<MemberPointerType>())
6357 CanTy = ResTypeMPtr->getPointeeType();
6358 else
6359 done = true;
6360 if (CanTy.isVolatileQualified())
6361 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006362 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6363 return VRQuals;
6364 }
6365 }
6366 }
6367 return VRQuals;
6368}
John McCall52872982010-11-13 05:51:15 +00006369
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006370namespace {
John McCall52872982010-11-13 05:51:15 +00006371
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006372/// \brief Helper class to manage the addition of builtin operator overload
6373/// candidates. It provides shared state and utility methods used throughout
6374/// the process, as well as a helper method to add each group of builtin
6375/// operator overloads from the standard to a candidate set.
6376class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006377 // Common instance state available to all overload candidate addition methods.
6378 Sema &S;
6379 Expr **Args;
6380 unsigned NumArgs;
6381 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006382 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006383 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006384 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006385
Chandler Carruthc6586e52010-12-12 10:35:00 +00006386 // Define some constants used to index and iterate over the arithemetic types
6387 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006388 // The "promoted arithmetic types" are the arithmetic
6389 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006390 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006391 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006392 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006393 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006394 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006395 LastPromotedArithmeticType = 11;
6396 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006397
Chandler Carruthc6586e52010-12-12 10:35:00 +00006398 /// \brief Get the canonical type for a given arithmetic type index.
6399 CanQualType getArithmeticType(unsigned index) {
6400 assert(index < NumArithmeticTypes);
6401 static CanQualType ASTContext::* const
6402 ArithmeticTypes[NumArithmeticTypes] = {
6403 // Start of promoted types.
6404 &ASTContext::FloatTy,
6405 &ASTContext::DoubleTy,
6406 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006407
Chandler Carruthc6586e52010-12-12 10:35:00 +00006408 // Start of integral types.
6409 &ASTContext::IntTy,
6410 &ASTContext::LongTy,
6411 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006412 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006413 &ASTContext::UnsignedIntTy,
6414 &ASTContext::UnsignedLongTy,
6415 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006416 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006417 // End of promoted types.
6418
6419 &ASTContext::BoolTy,
6420 &ASTContext::CharTy,
6421 &ASTContext::WCharTy,
6422 &ASTContext::Char16Ty,
6423 &ASTContext::Char32Ty,
6424 &ASTContext::SignedCharTy,
6425 &ASTContext::ShortTy,
6426 &ASTContext::UnsignedCharTy,
6427 &ASTContext::UnsignedShortTy,
6428 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006429 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006430 };
6431 return S.Context.*ArithmeticTypes[index];
6432 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006433
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006434 /// \brief Gets the canonical type resulting from the usual arithemetic
6435 /// converions for the given arithmetic types.
6436 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6437 // Accelerator table for performing the usual arithmetic conversions.
6438 // The rules are basically:
6439 // - if either is floating-point, use the wider floating-point
6440 // - if same signedness, use the higher rank
6441 // - if same size, use unsigned of the higher rank
6442 // - use the larger type
6443 // These rules, together with the axiom that higher ranks are
6444 // never smaller, are sufficient to precompute all of these results
6445 // *except* when dealing with signed types of higher rank.
6446 // (we could precompute SLL x UI for all known platforms, but it's
6447 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006448 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006449 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006450 Dep=-1,
6451 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006452 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006453 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006454 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006455/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6456/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6457/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6458/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6459/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6460/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6461/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6462/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6463/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6464/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6465/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006466 };
6467
6468 assert(L < LastPromotedArithmeticType);
6469 assert(R < LastPromotedArithmeticType);
6470 int Idx = ConversionsTable[L][R];
6471
6472 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006473 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006474
6475 // Slow path: we need to compare widths.
6476 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006477 CanQualType LT = getArithmeticType(L),
6478 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006479 unsigned LW = S.Context.getIntWidth(LT),
6480 RW = S.Context.getIntWidth(RT);
6481
6482 // If they're different widths, use the signed type.
6483 if (LW > RW) return LT;
6484 else if (LW < RW) return RT;
6485
6486 // Otherwise, use the unsigned type of the signed type's rank.
6487 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6488 assert(L == SLL || R == SLL);
6489 return S.Context.UnsignedLongLongTy;
6490 }
6491
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006492 /// \brief Helper method to factor out the common pattern of adding overloads
6493 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006494 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006495 bool HasVolatile,
6496 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006497 QualType ParamTypes[2] = {
6498 S.Context.getLValueReferenceType(CandidateTy),
6499 S.Context.IntTy
6500 };
6501
6502 // Non-volatile version.
6503 if (NumArgs == 1)
6504 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6505 else
6506 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6507
6508 // Use a heuristic to reduce number of builtin candidates in the set:
6509 // add volatile version only if there are conversions to a volatile type.
6510 if (HasVolatile) {
6511 ParamTypes[0] =
6512 S.Context.getLValueReferenceType(
6513 S.Context.getVolatileType(CandidateTy));
6514 if (NumArgs == 1)
6515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6516 else
6517 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6518 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006519
6520 // Add restrict version only if there are conversions to a restrict type
6521 // and our candidate type is a non-restrict-qualified pointer.
6522 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6523 !CandidateTy.isRestrictQualified()) {
6524 ParamTypes[0]
6525 = S.Context.getLValueReferenceType(
6526 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6527 if (NumArgs == 1)
6528 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6529 else
6530 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6531
6532 if (HasVolatile) {
6533 ParamTypes[0]
6534 = S.Context.getLValueReferenceType(
6535 S.Context.getCVRQualifiedType(CandidateTy,
6536 (Qualifiers::Volatile |
6537 Qualifiers::Restrict)));
6538 if (NumArgs == 1)
6539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6540 CandidateSet);
6541 else
6542 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6543 }
6544 }
6545
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006546 }
6547
6548public:
6549 BuiltinOperatorOverloadBuilder(
6550 Sema &S, Expr **Args, unsigned NumArgs,
6551 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006552 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006553 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006554 OverloadCandidateSet &CandidateSet)
6555 : S(S), Args(Args), NumArgs(NumArgs),
6556 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006557 HasArithmeticOrEnumeralCandidateType(
6558 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006559 CandidateTypes(CandidateTypes),
6560 CandidateSet(CandidateSet) {
6561 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006562 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006563 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006564 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006565 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006566 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006567 assert(getArithmeticType(FirstPromotedArithmeticType)
6568 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006569 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006570 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006571 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006572 "Invalid last promoted arithmetic type");
6573 }
6574
6575 // C++ [over.built]p3:
6576 //
6577 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6578 // is either volatile or empty, there exist candidate operator
6579 // functions of the form
6580 //
6581 // VQ T& operator++(VQ T&);
6582 // T operator++(VQ T&, int);
6583 //
6584 // C++ [over.built]p4:
6585 //
6586 // For every pair (T, VQ), where T is an arithmetic type other
6587 // than bool, and VQ is either volatile or empty, there exist
6588 // candidate operator functions of the form
6589 //
6590 // VQ T& operator--(VQ T&);
6591 // T operator--(VQ T&, int);
6592 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006593 if (!HasArithmeticOrEnumeralCandidateType)
6594 return;
6595
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006596 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6597 Arith < NumArithmeticTypes; ++Arith) {
6598 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006599 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006600 VisibleTypeConversionsQuals.hasVolatile(),
6601 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006602 }
6603 }
6604
6605 // C++ [over.built]p5:
6606 //
6607 // For every pair (T, VQ), where T is a cv-qualified or
6608 // cv-unqualified object type, and VQ is either volatile or
6609 // empty, there exist candidate operator functions of the form
6610 //
6611 // T*VQ& operator++(T*VQ&);
6612 // T*VQ& operator--(T*VQ&);
6613 // T* operator++(T*VQ&, int);
6614 // T* operator--(T*VQ&, int);
6615 void addPlusPlusMinusMinusPointerOverloads() {
6616 for (BuiltinCandidateTypeSet::iterator
6617 Ptr = CandidateTypes[0].pointer_begin(),
6618 PtrEnd = CandidateTypes[0].pointer_end();
6619 Ptr != PtrEnd; ++Ptr) {
6620 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006621 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006622 continue;
6623
6624 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006625 (!(*Ptr).isVolatileQualified() &&
6626 VisibleTypeConversionsQuals.hasVolatile()),
6627 (!(*Ptr).isRestrictQualified() &&
6628 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006629 }
6630 }
6631
6632 // C++ [over.built]p6:
6633 // For every cv-qualified or cv-unqualified object type T, there
6634 // exist candidate operator functions of the form
6635 //
6636 // T& operator*(T*);
6637 //
6638 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006640 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006641 // T& operator*(T*);
6642 void addUnaryStarPointerOverloads() {
6643 for (BuiltinCandidateTypeSet::iterator
6644 Ptr = CandidateTypes[0].pointer_begin(),
6645 PtrEnd = CandidateTypes[0].pointer_end();
6646 Ptr != PtrEnd; ++Ptr) {
6647 QualType ParamTy = *Ptr;
6648 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006649 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6650 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Douglas Gregor02824322011-01-26 19:30:28 +00006652 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6653 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6654 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006656 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6657 &ParamTy, Args, 1, CandidateSet);
6658 }
6659 }
6660
6661 // C++ [over.built]p9:
6662 // For every promoted arithmetic type T, there exist candidate
6663 // operator functions of the form
6664 //
6665 // T operator+(T);
6666 // T operator-(T);
6667 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006668 if (!HasArithmeticOrEnumeralCandidateType)
6669 return;
6670
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006671 for (unsigned Arith = FirstPromotedArithmeticType;
6672 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006673 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006674 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6675 }
6676
6677 // Extension: We also add these operators for vector types.
6678 for (BuiltinCandidateTypeSet::iterator
6679 Vec = CandidateTypes[0].vector_begin(),
6680 VecEnd = CandidateTypes[0].vector_end();
6681 Vec != VecEnd; ++Vec) {
6682 QualType VecTy = *Vec;
6683 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6684 }
6685 }
6686
6687 // C++ [over.built]p8:
6688 // For every type T, there exist candidate operator functions of
6689 // the form
6690 //
6691 // T* operator+(T*);
6692 void addUnaryPlusPointerOverloads() {
6693 for (BuiltinCandidateTypeSet::iterator
6694 Ptr = CandidateTypes[0].pointer_begin(),
6695 PtrEnd = CandidateTypes[0].pointer_end();
6696 Ptr != PtrEnd; ++Ptr) {
6697 QualType ParamTy = *Ptr;
6698 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6699 }
6700 }
6701
6702 // C++ [over.built]p10:
6703 // For every promoted integral type T, there exist candidate
6704 // operator functions of the form
6705 //
6706 // T operator~(T);
6707 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006708 if (!HasArithmeticOrEnumeralCandidateType)
6709 return;
6710
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006711 for (unsigned Int = FirstPromotedIntegralType;
6712 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006713 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006714 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6715 }
6716
6717 // Extension: We also add this operator for vector types.
6718 for (BuiltinCandidateTypeSet::iterator
6719 Vec = CandidateTypes[0].vector_begin(),
6720 VecEnd = CandidateTypes[0].vector_end();
6721 Vec != VecEnd; ++Vec) {
6722 QualType VecTy = *Vec;
6723 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6724 }
6725 }
6726
6727 // C++ [over.match.oper]p16:
6728 // For every pointer to member type T, there exist candidate operator
6729 // functions of the form
6730 //
6731 // bool operator==(T,T);
6732 // bool operator!=(T,T);
6733 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6734 /// Set of (canonical) types that we've already handled.
6735 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6736
6737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6738 for (BuiltinCandidateTypeSet::iterator
6739 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6740 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6741 MemPtr != MemPtrEnd;
6742 ++MemPtr) {
6743 // Don't add the same builtin candidate twice.
6744 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6745 continue;
6746
6747 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6748 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6749 CandidateSet);
6750 }
6751 }
6752 }
6753
6754 // C++ [over.built]p15:
6755 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006756 // For every T, where T is an enumeration type, a pointer type, or
6757 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006758 //
6759 // bool operator<(T, T);
6760 // bool operator>(T, T);
6761 // bool operator<=(T, T);
6762 // bool operator>=(T, T);
6763 // bool operator==(T, T);
6764 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006765 void addRelationalPointerOrEnumeralOverloads() {
6766 // C++ [over.built]p1:
6767 // If there is a user-written candidate with the same name and parameter
6768 // types as a built-in candidate operator function, the built-in operator
6769 // function is hidden and is not included in the set of candidate
6770 // functions.
6771 //
6772 // The text is actually in a note, but if we don't implement it then we end
6773 // up with ambiguities when the user provides an overloaded operator for
6774 // an enumeration type. Note that only enumeration types have this problem,
6775 // so we track which enumeration types we've seen operators for. Also, the
6776 // only other overloaded operator with enumeration argumenst, operator=,
6777 // cannot be overloaded for enumeration types, so this is the only place
6778 // where we must suppress candidates like this.
6779 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6780 UserDefinedBinaryOperators;
6781
6782 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6783 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6784 CandidateTypes[ArgIdx].enumeration_end()) {
6785 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6786 CEnd = CandidateSet.end();
6787 C != CEnd; ++C) {
6788 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6789 continue;
6790
6791 QualType FirstParamType =
6792 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6793 QualType SecondParamType =
6794 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6795
6796 // Skip if either parameter isn't of enumeral type.
6797 if (!FirstParamType->isEnumeralType() ||
6798 !SecondParamType->isEnumeralType())
6799 continue;
6800
6801 // Add this operator to the set of known user-defined operators.
6802 UserDefinedBinaryOperators.insert(
6803 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6804 S.Context.getCanonicalType(SecondParamType)));
6805 }
6806 }
6807 }
6808
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006809 /// Set of (canonical) types that we've already handled.
6810 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6811
6812 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6813 for (BuiltinCandidateTypeSet::iterator
6814 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6815 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6816 Ptr != PtrEnd; ++Ptr) {
6817 // Don't add the same builtin candidate twice.
6818 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6819 continue;
6820
6821 QualType ParamTypes[2] = { *Ptr, *Ptr };
6822 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6823 CandidateSet);
6824 }
6825 for (BuiltinCandidateTypeSet::iterator
6826 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6827 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6828 Enum != EnumEnd; ++Enum) {
6829 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6830
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006831 // Don't add the same builtin candidate twice, or if a user defined
6832 // candidate exists.
6833 if (!AddedTypes.insert(CanonType) ||
6834 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6835 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006836 continue;
6837
6838 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006839 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6840 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006841 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006842
6843 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6844 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6845 if (AddedTypes.insert(NullPtrTy) &&
6846 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6847 NullPtrTy))) {
6848 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6849 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6850 CandidateSet);
6851 }
6852 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006853 }
6854 }
6855
6856 // C++ [over.built]p13:
6857 //
6858 // For every cv-qualified or cv-unqualified object type T
6859 // there exist candidate operator functions of the form
6860 //
6861 // T* operator+(T*, ptrdiff_t);
6862 // T& operator[](T*, ptrdiff_t); [BELOW]
6863 // T* operator-(T*, ptrdiff_t);
6864 // T* operator+(ptrdiff_t, T*);
6865 // T& operator[](ptrdiff_t, T*); [BELOW]
6866 //
6867 // C++ [over.built]p14:
6868 //
6869 // For every T, where T is a pointer to object type, there
6870 // exist candidate operator functions of the form
6871 //
6872 // ptrdiff_t operator-(T, T);
6873 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6874 /// Set of (canonical) types that we've already handled.
6875 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6876
6877 for (int Arg = 0; Arg < 2; ++Arg) {
6878 QualType AsymetricParamTypes[2] = {
6879 S.Context.getPointerDiffType(),
6880 S.Context.getPointerDiffType(),
6881 };
6882 for (BuiltinCandidateTypeSet::iterator
6883 Ptr = CandidateTypes[Arg].pointer_begin(),
6884 PtrEnd = CandidateTypes[Arg].pointer_end();
6885 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006886 QualType PointeeTy = (*Ptr)->getPointeeType();
6887 if (!PointeeTy->isObjectType())
6888 continue;
6889
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006890 AsymetricParamTypes[Arg] = *Ptr;
6891 if (Arg == 0 || Op == OO_Plus) {
6892 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6893 // T* operator+(ptrdiff_t, T*);
6894 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6895 CandidateSet);
6896 }
6897 if (Op == OO_Minus) {
6898 // ptrdiff_t operator-(T, T);
6899 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6900 continue;
6901
6902 QualType ParamTypes[2] = { *Ptr, *Ptr };
6903 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6904 Args, 2, CandidateSet);
6905 }
6906 }
6907 }
6908 }
6909
6910 // C++ [over.built]p12:
6911 //
6912 // For every pair of promoted arithmetic types L and R, there
6913 // exist candidate operator functions of the form
6914 //
6915 // LR operator*(L, R);
6916 // LR operator/(L, R);
6917 // LR operator+(L, R);
6918 // LR operator-(L, R);
6919 // bool operator<(L, R);
6920 // bool operator>(L, R);
6921 // bool operator<=(L, R);
6922 // bool operator>=(L, R);
6923 // bool operator==(L, R);
6924 // bool operator!=(L, R);
6925 //
6926 // where LR is the result of the usual arithmetic conversions
6927 // between types L and R.
6928 //
6929 // C++ [over.built]p24:
6930 //
6931 // For every pair of promoted arithmetic types L and R, there exist
6932 // candidate operator functions of the form
6933 //
6934 // LR operator?(bool, L, R);
6935 //
6936 // where LR is the result of the usual arithmetic conversions
6937 // between types L and R.
6938 // Our candidates ignore the first parameter.
6939 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006940 if (!HasArithmeticOrEnumeralCandidateType)
6941 return;
6942
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006943 for (unsigned Left = FirstPromotedArithmeticType;
6944 Left < LastPromotedArithmeticType; ++Left) {
6945 for (unsigned Right = FirstPromotedArithmeticType;
6946 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006947 QualType LandR[2] = { getArithmeticType(Left),
6948 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006949 QualType Result =
6950 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006951 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006952 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6953 }
6954 }
6955
6956 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6957 // conditional operator for vector types.
6958 for (BuiltinCandidateTypeSet::iterator
6959 Vec1 = CandidateTypes[0].vector_begin(),
6960 Vec1End = CandidateTypes[0].vector_end();
6961 Vec1 != Vec1End; ++Vec1) {
6962 for (BuiltinCandidateTypeSet::iterator
6963 Vec2 = CandidateTypes[1].vector_begin(),
6964 Vec2End = CandidateTypes[1].vector_end();
6965 Vec2 != Vec2End; ++Vec2) {
6966 QualType LandR[2] = { *Vec1, *Vec2 };
6967 QualType Result = S.Context.BoolTy;
6968 if (!isComparison) {
6969 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6970 Result = *Vec1;
6971 else
6972 Result = *Vec2;
6973 }
6974
6975 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6976 }
6977 }
6978 }
6979
6980 // C++ [over.built]p17:
6981 //
6982 // For every pair of promoted integral types L and R, there
6983 // exist candidate operator functions of the form
6984 //
6985 // LR operator%(L, R);
6986 // LR operator&(L, R);
6987 // LR operator^(L, R);
6988 // LR operator|(L, R);
6989 // L operator<<(L, R);
6990 // L operator>>(L, R);
6991 //
6992 // where LR is the result of the usual arithmetic conversions
6993 // between types L and R.
6994 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006995 if (!HasArithmeticOrEnumeralCandidateType)
6996 return;
6997
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006998 for (unsigned Left = FirstPromotedIntegralType;
6999 Left < LastPromotedIntegralType; ++Left) {
7000 for (unsigned Right = FirstPromotedIntegralType;
7001 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007002 QualType LandR[2] = { getArithmeticType(Left),
7003 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007004 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7005 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007006 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007007 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7008 }
7009 }
7010 }
7011
7012 // C++ [over.built]p20:
7013 //
7014 // For every pair (T, VQ), where T is an enumeration or
7015 // pointer to member type and VQ is either volatile or
7016 // empty, there exist candidate operator functions of the form
7017 //
7018 // VQ T& operator=(VQ T&, T);
7019 void addAssignmentMemberPointerOrEnumeralOverloads() {
7020 /// Set of (canonical) types that we've already handled.
7021 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7022
7023 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7024 for (BuiltinCandidateTypeSet::iterator
7025 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7026 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7027 Enum != EnumEnd; ++Enum) {
7028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7029 continue;
7030
7031 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7032 CandidateSet);
7033 }
7034
7035 for (BuiltinCandidateTypeSet::iterator
7036 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7037 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7038 MemPtr != MemPtrEnd; ++MemPtr) {
7039 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7040 continue;
7041
7042 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7043 CandidateSet);
7044 }
7045 }
7046 }
7047
7048 // C++ [over.built]p19:
7049 //
7050 // For every pair (T, VQ), where T is any type and VQ is either
7051 // volatile or empty, there exist candidate operator functions
7052 // of the form
7053 //
7054 // T*VQ& operator=(T*VQ&, T*);
7055 //
7056 // C++ [over.built]p21:
7057 //
7058 // For every pair (T, VQ), where T is a cv-qualified or
7059 // cv-unqualified object type and VQ is either volatile or
7060 // empty, there exist candidate operator functions of the form
7061 //
7062 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7063 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7064 void addAssignmentPointerOverloads(bool isEqualOp) {
7065 /// Set of (canonical) types that we've already handled.
7066 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7067
7068 for (BuiltinCandidateTypeSet::iterator
7069 Ptr = CandidateTypes[0].pointer_begin(),
7070 PtrEnd = CandidateTypes[0].pointer_end();
7071 Ptr != PtrEnd; ++Ptr) {
7072 // If this is operator=, keep track of the builtin candidates we added.
7073 if (isEqualOp)
7074 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007075 else if (!(*Ptr)->getPointeeType()->isObjectType())
7076 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007077
7078 // non-volatile version
7079 QualType ParamTypes[2] = {
7080 S.Context.getLValueReferenceType(*Ptr),
7081 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7082 };
7083 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7084 /*IsAssigmentOperator=*/ isEqualOp);
7085
Douglas Gregor5bee2582012-06-04 00:15:09 +00007086 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7087 VisibleTypeConversionsQuals.hasVolatile();
7088 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007089 // volatile version
7090 ParamTypes[0] =
7091 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7092 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7093 /*IsAssigmentOperator=*/isEqualOp);
7094 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007095
7096 if (!(*Ptr).isRestrictQualified() &&
7097 VisibleTypeConversionsQuals.hasRestrict()) {
7098 // restrict version
7099 ParamTypes[0]
7100 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7101 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7102 /*IsAssigmentOperator=*/isEqualOp);
7103
7104 if (NeedVolatile) {
7105 // volatile restrict version
7106 ParamTypes[0]
7107 = S.Context.getLValueReferenceType(
7108 S.Context.getCVRQualifiedType(*Ptr,
7109 (Qualifiers::Volatile |
7110 Qualifiers::Restrict)));
7111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7112 CandidateSet,
7113 /*IsAssigmentOperator=*/isEqualOp);
7114 }
7115 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007116 }
7117
7118 if (isEqualOp) {
7119 for (BuiltinCandidateTypeSet::iterator
7120 Ptr = CandidateTypes[1].pointer_begin(),
7121 PtrEnd = CandidateTypes[1].pointer_end();
7122 Ptr != PtrEnd; ++Ptr) {
7123 // Make sure we don't add the same candidate twice.
7124 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7125 continue;
7126
Chandler Carruth8e543b32010-12-12 08:17:55 +00007127 QualType ParamTypes[2] = {
7128 S.Context.getLValueReferenceType(*Ptr),
7129 *Ptr,
7130 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007131
7132 // non-volatile version
7133 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7134 /*IsAssigmentOperator=*/true);
7135
Douglas Gregor5bee2582012-06-04 00:15:09 +00007136 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7137 VisibleTypeConversionsQuals.hasVolatile();
7138 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007139 // volatile version
7140 ParamTypes[0] =
7141 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007142 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7143 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007144 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007145
7146 if (!(*Ptr).isRestrictQualified() &&
7147 VisibleTypeConversionsQuals.hasRestrict()) {
7148 // restrict version
7149 ParamTypes[0]
7150 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7151 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7152 CandidateSet, /*IsAssigmentOperator=*/true);
7153
7154 if (NeedVolatile) {
7155 // volatile restrict version
7156 ParamTypes[0]
7157 = S.Context.getLValueReferenceType(
7158 S.Context.getCVRQualifiedType(*Ptr,
7159 (Qualifiers::Volatile |
7160 Qualifiers::Restrict)));
7161 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7162 CandidateSet, /*IsAssigmentOperator=*/true);
7163
7164 }
7165 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007166 }
7167 }
7168 }
7169
7170 // C++ [over.built]p18:
7171 //
7172 // For every triple (L, VQ, R), where L is an arithmetic type,
7173 // VQ is either volatile or empty, and R is a promoted
7174 // arithmetic type, there exist candidate operator functions of
7175 // the form
7176 //
7177 // VQ L& operator=(VQ L&, R);
7178 // VQ L& operator*=(VQ L&, R);
7179 // VQ L& operator/=(VQ L&, R);
7180 // VQ L& operator+=(VQ L&, R);
7181 // VQ L& operator-=(VQ L&, R);
7182 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007183 if (!HasArithmeticOrEnumeralCandidateType)
7184 return;
7185
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007186 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7187 for (unsigned Right = FirstPromotedArithmeticType;
7188 Right < LastPromotedArithmeticType; ++Right) {
7189 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007190 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007191
7192 // Add this built-in operator as a candidate (VQ is empty).
7193 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007194 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7196 /*IsAssigmentOperator=*/isEqualOp);
7197
7198 // Add this built-in operator as a candidate (VQ is 'volatile').
7199 if (VisibleTypeConversionsQuals.hasVolatile()) {
7200 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007201 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007202 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007203 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7204 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007205 /*IsAssigmentOperator=*/isEqualOp);
7206 }
7207 }
7208 }
7209
7210 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7211 for (BuiltinCandidateTypeSet::iterator
7212 Vec1 = CandidateTypes[0].vector_begin(),
7213 Vec1End = CandidateTypes[0].vector_end();
7214 Vec1 != Vec1End; ++Vec1) {
7215 for (BuiltinCandidateTypeSet::iterator
7216 Vec2 = CandidateTypes[1].vector_begin(),
7217 Vec2End = CandidateTypes[1].vector_end();
7218 Vec2 != Vec2End; ++Vec2) {
7219 QualType ParamTypes[2];
7220 ParamTypes[1] = *Vec2;
7221 // Add this built-in operator as a candidate (VQ is empty).
7222 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7223 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7224 /*IsAssigmentOperator=*/isEqualOp);
7225
7226 // Add this built-in operator as a candidate (VQ is 'volatile').
7227 if (VisibleTypeConversionsQuals.hasVolatile()) {
7228 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7229 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7231 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232 /*IsAssigmentOperator=*/isEqualOp);
7233 }
7234 }
7235 }
7236 }
7237
7238 // C++ [over.built]p22:
7239 //
7240 // For every triple (L, VQ, R), where L is an integral type, VQ
7241 // is either volatile or empty, and R is a promoted integral
7242 // type, there exist candidate operator functions of the form
7243 //
7244 // VQ L& operator%=(VQ L&, R);
7245 // VQ L& operator<<=(VQ L&, R);
7246 // VQ L& operator>>=(VQ L&, R);
7247 // VQ L& operator&=(VQ L&, R);
7248 // VQ L& operator^=(VQ L&, R);
7249 // VQ L& operator|=(VQ L&, R);
7250 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007251 if (!HasArithmeticOrEnumeralCandidateType)
7252 return;
7253
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007254 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7255 for (unsigned Right = FirstPromotedIntegralType;
7256 Right < LastPromotedIntegralType; ++Right) {
7257 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007258 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007259
7260 // Add this built-in operator as a candidate (VQ is empty).
7261 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007262 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007263 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7264 if (VisibleTypeConversionsQuals.hasVolatile()) {
7265 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007266 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007267 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7268 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7269 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7270 CandidateSet);
7271 }
7272 }
7273 }
7274 }
7275
7276 // C++ [over.operator]p23:
7277 //
7278 // There also exist candidate operator functions of the form
7279 //
7280 // bool operator!(bool);
7281 // bool operator&&(bool, bool);
7282 // bool operator||(bool, bool);
7283 void addExclaimOverload() {
7284 QualType ParamTy = S.Context.BoolTy;
7285 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7286 /*IsAssignmentOperator=*/false,
7287 /*NumContextualBoolArguments=*/1);
7288 }
7289 void addAmpAmpOrPipePipeOverload() {
7290 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7291 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7292 /*IsAssignmentOperator=*/false,
7293 /*NumContextualBoolArguments=*/2);
7294 }
7295
7296 // C++ [over.built]p13:
7297 //
7298 // For every cv-qualified or cv-unqualified object type T there
7299 // exist candidate operator functions of the form
7300 //
7301 // T* operator+(T*, ptrdiff_t); [ABOVE]
7302 // T& operator[](T*, ptrdiff_t);
7303 // T* operator-(T*, ptrdiff_t); [ABOVE]
7304 // T* operator+(ptrdiff_t, T*); [ABOVE]
7305 // T& operator[](ptrdiff_t, T*);
7306 void addSubscriptOverloads() {
7307 for (BuiltinCandidateTypeSet::iterator
7308 Ptr = CandidateTypes[0].pointer_begin(),
7309 PtrEnd = CandidateTypes[0].pointer_end();
7310 Ptr != PtrEnd; ++Ptr) {
7311 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7312 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007313 if (!PointeeType->isObjectType())
7314 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7317
7318 // T& operator[](T*, ptrdiff_t)
7319 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7320 }
7321
7322 for (BuiltinCandidateTypeSet::iterator
7323 Ptr = CandidateTypes[1].pointer_begin(),
7324 PtrEnd = CandidateTypes[1].pointer_end();
7325 Ptr != PtrEnd; ++Ptr) {
7326 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7327 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007328 if (!PointeeType->isObjectType())
7329 continue;
7330
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7332
7333 // T& operator[](ptrdiff_t, T*)
7334 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7335 }
7336 }
7337
7338 // C++ [over.built]p11:
7339 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7340 // C1 is the same type as C2 or is a derived class of C2, T is an object
7341 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7342 // there exist candidate operator functions of the form
7343 //
7344 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7345 //
7346 // where CV12 is the union of CV1 and CV2.
7347 void addArrowStarOverloads() {
7348 for (BuiltinCandidateTypeSet::iterator
7349 Ptr = CandidateTypes[0].pointer_begin(),
7350 PtrEnd = CandidateTypes[0].pointer_end();
7351 Ptr != PtrEnd; ++Ptr) {
7352 QualType C1Ty = (*Ptr);
7353 QualType C1;
7354 QualifierCollector Q1;
7355 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7356 if (!isa<RecordType>(C1))
7357 continue;
7358 // heuristic to reduce number of builtin candidates in the set.
7359 // Add volatile/restrict version only if there are conversions to a
7360 // volatile/restrict type.
7361 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7362 continue;
7363 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7364 continue;
7365 for (BuiltinCandidateTypeSet::iterator
7366 MemPtr = CandidateTypes[1].member_pointer_begin(),
7367 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7368 MemPtr != MemPtrEnd; ++MemPtr) {
7369 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7370 QualType C2 = QualType(mptr->getClass(), 0);
7371 C2 = C2.getUnqualifiedType();
7372 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7373 break;
7374 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7375 // build CV12 T&
7376 QualType T = mptr->getPointeeType();
7377 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7378 T.isVolatileQualified())
7379 continue;
7380 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7381 T.isRestrictQualified())
7382 continue;
7383 T = Q1.apply(S.Context, T);
7384 QualType ResultTy = S.Context.getLValueReferenceType(T);
7385 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7386 }
7387 }
7388 }
7389
7390 // Note that we don't consider the first argument, since it has been
7391 // contextually converted to bool long ago. The candidates below are
7392 // therefore added as binary.
7393 //
7394 // C++ [over.built]p25:
7395 // For every type T, where T is a pointer, pointer-to-member, or scoped
7396 // enumeration type, there exist candidate operator functions of the form
7397 //
7398 // T operator?(bool, T, T);
7399 //
7400 void addConditionalOperatorOverloads() {
7401 /// Set of (canonical) types that we've already handled.
7402 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7403
7404 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7405 for (BuiltinCandidateTypeSet::iterator
7406 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7407 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7408 Ptr != PtrEnd; ++Ptr) {
7409 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7410 continue;
7411
7412 QualType ParamTypes[2] = { *Ptr, *Ptr };
7413 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7414 }
7415
7416 for (BuiltinCandidateTypeSet::iterator
7417 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7418 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7419 MemPtr != MemPtrEnd; ++MemPtr) {
7420 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7421 continue;
7422
7423 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7424 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7425 }
7426
David Blaikiebbafb8a2012-03-11 07:00:24 +00007427 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 for (BuiltinCandidateTypeSet::iterator
7429 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7430 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7431 Enum != EnumEnd; ++Enum) {
7432 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7433 continue;
7434
7435 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7436 continue;
7437
7438 QualType ParamTypes[2] = { *Enum, *Enum };
7439 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7440 }
7441 }
7442 }
7443 }
7444};
7445
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007446} // end anonymous namespace
7447
7448/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7449/// operator overloads to the candidate set (C++ [over.built]), based
7450/// on the operator @p Op and the arguments given. For example, if the
7451/// operator is a binary '+', this routine might add "int
7452/// operator+(int, int)" to cover integer addition.
7453void
7454Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7455 SourceLocation OpLoc,
7456 Expr **Args, unsigned NumArgs,
7457 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007458 // Find all of the types that the arguments can convert to, but only
7459 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007460 // that make use of these types. Also record whether we encounter non-record
7461 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007462 Qualifiers VisibleTypeConversionsQuals;
7463 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007464 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7465 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007466
7467 bool HasNonRecordCandidateType = false;
7468 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007469 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007470 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7471 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7472 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7473 OpLoc,
7474 true,
7475 (Op == OO_Exclaim ||
7476 Op == OO_AmpAmp ||
7477 Op == OO_PipePipe),
7478 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007479 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7480 CandidateTypes[ArgIdx].hasNonRecordTypes();
7481 HasArithmeticOrEnumeralCandidateType =
7482 HasArithmeticOrEnumeralCandidateType ||
7483 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007484 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007485
Chandler Carruth00a38332010-12-13 01:44:01 +00007486 // Exit early when no non-record types have been added to the candidate set
7487 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007488 //
7489 // We can't exit early for !, ||, or &&, since there we have always have
7490 // 'bool' overloads.
7491 if (!HasNonRecordCandidateType &&
7492 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007493 return;
7494
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007495 // Setup an object to manage the common state for building overloads.
7496 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7497 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007498 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007499 CandidateTypes, CandidateSet);
7500
7501 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007502 switch (Op) {
7503 case OO_None:
7504 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007505 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007506
Chandler Carruth5184de02010-12-12 08:51:33 +00007507 case OO_New:
7508 case OO_Delete:
7509 case OO_Array_New:
7510 case OO_Array_Delete:
7511 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007512 llvm_unreachable(
7513 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007514
7515 case OO_Comma:
7516 case OO_Arrow:
7517 // C++ [over.match.oper]p3:
7518 // -- For the operator ',', the unary operator '&', or the
7519 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007520 break;
7521
7522 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007523 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007525 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007526
7527 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007528 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007529 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007530 } else {
7531 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7532 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7533 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007534 break;
7535
Chandler Carruth5184de02010-12-12 08:51:33 +00007536 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007537 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007538 OpBuilder.addUnaryStarPointerOverloads();
7539 else
7540 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7541 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542
Chandler Carruth5184de02010-12-12 08:51:33 +00007543 case OO_Slash:
7544 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007545 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007546
7547 case OO_PlusPlus:
7548 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7550 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007551 break;
7552
Douglas Gregor84605ae2009-08-24 13:43:27 +00007553 case OO_EqualEqual:
7554 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007555 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007556 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007557
Douglas Gregora11693b2008-11-12 17:17:38 +00007558 case OO_Less:
7559 case OO_Greater:
7560 case OO_LessEqual:
7561 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007562 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007563 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7564 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007565
Douglas Gregora11693b2008-11-12 17:17:38 +00007566 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007567 case OO_Caret:
7568 case OO_Pipe:
7569 case OO_LessLess:
7570 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007572 break;
7573
Chandler Carruth5184de02010-12-12 08:51:33 +00007574 case OO_Amp: // '&' is either unary or binary
7575 if (NumArgs == 1)
7576 // C++ [over.match.oper]p3:
7577 // -- For the operator ',', the unary operator '&', or the
7578 // operator '->', the built-in candidates set is empty.
7579 break;
7580
7581 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7582 break;
7583
7584 case OO_Tilde:
7585 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7586 break;
7587
Douglas Gregora11693b2008-11-12 17:17:38 +00007588 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007589 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007590 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007591
7592 case OO_PlusEqual:
7593 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007594 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007595 // Fall through.
7596
7597 case OO_StarEqual:
7598 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007599 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007600 break;
7601
7602 case OO_PercentEqual:
7603 case OO_LessLessEqual:
7604 case OO_GreaterGreaterEqual:
7605 case OO_AmpEqual:
7606 case OO_CaretEqual:
7607 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007608 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007609 break;
7610
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007611 case OO_Exclaim:
7612 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007613 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007614
Douglas Gregora11693b2008-11-12 17:17:38 +00007615 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007616 case OO_PipePipe:
7617 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007618 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007619
7620 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007622 break;
7623
7624 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007625 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007626 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007627
7628 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007629 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007630 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7631 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007632 }
7633}
7634
Douglas Gregore254f902009-02-04 00:32:51 +00007635/// \brief Add function candidates found via argument-dependent lookup
7636/// to the set of overloading candidates.
7637///
7638/// This routine performs argument-dependent name lookup based on the
7639/// given function name (which may also be an operator name) and adds
7640/// all of the overload candidates found by ADL to the overload
7641/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007642void
Douglas Gregore254f902009-02-04 00:32:51 +00007643Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007644 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007645 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007646 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007647 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007648 bool PartialOverloading,
7649 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007650 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007651
John McCall91f61fc2010-01-26 06:04:06 +00007652 // FIXME: This approach for uniquing ADL results (and removing
7653 // redundant candidates from the set) relies on pointer-equality,
7654 // which means we need to key off the canonical decl. However,
7655 // always going back to the canonical decl might not get us the
7656 // right set of default arguments. What default arguments are
7657 // we supposed to consider on ADL candidates, anyway?
7658
Douglas Gregorcabea402009-09-22 15:41:20 +00007659 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007660 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007661 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007662
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007663 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007664 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7665 CandEnd = CandidateSet.end();
7666 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007667 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007668 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007669 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007670 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007671 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007672
7673 // For each of the ADL candidates we found, add it to the overload
7674 // set.
John McCall8fe68082010-01-26 07:16:45 +00007675 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007676 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007678 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007679 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007680
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007681 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7682 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007683 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007684 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007685 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007686 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007687 }
Douglas Gregore254f902009-02-04 00:32:51 +00007688}
7689
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007690/// isBetterOverloadCandidate - Determines whether the first overload
7691/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007692bool
John McCall5c32be02010-08-24 20:38:10 +00007693isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007694 const OverloadCandidate &Cand1,
7695 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007696 SourceLocation Loc,
7697 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007698 // Define viable functions to be better candidates than non-viable
7699 // functions.
7700 if (!Cand2.Viable)
7701 return Cand1.Viable;
7702 else if (!Cand1.Viable)
7703 return false;
7704
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007705 // C++ [over.match.best]p1:
7706 //
7707 // -- if F is a static member function, ICS1(F) is defined such
7708 // that ICS1(F) is neither better nor worse than ICS1(G) for
7709 // any function G, and, symmetrically, ICS1(G) is neither
7710 // better nor worse than ICS1(F).
7711 unsigned StartArg = 0;
7712 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7713 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007714
Douglas Gregord3cb3562009-07-07 23:38:56 +00007715 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007716 // A viable function F1 is defined to be a better function than another
7717 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007718 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007719 unsigned NumArgs = Cand1.NumConversions;
7720 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007721 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007722 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007723 switch (CompareImplicitConversionSequences(S,
7724 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007725 Cand2.Conversions[ArgIdx])) {
7726 case ImplicitConversionSequence::Better:
7727 // Cand1 has a better conversion sequence.
7728 HasBetterConversion = true;
7729 break;
7730
7731 case ImplicitConversionSequence::Worse:
7732 // Cand1 can't be better than Cand2.
7733 return false;
7734
7735 case ImplicitConversionSequence::Indistinguishable:
7736 // Do nothing.
7737 break;
7738 }
7739 }
7740
Mike Stump11289f42009-09-09 15:08:12 +00007741 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007742 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007743 if (HasBetterConversion)
7744 return true;
7745
Mike Stump11289f42009-09-09 15:08:12 +00007746 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007747 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007748 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007749 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7750 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007751
7752 // -- F1 and F2 are function template specializations, and the function
7753 // template for F1 is more specialized than the template for F2
7754 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007755 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007756 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007757 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007758 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007759 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7760 Cand2.Function->getPrimaryTemplate(),
7761 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007762 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007763 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007764 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007765 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767
Douglas Gregora1f013e2008-11-07 22:36:19 +00007768 // -- the context is an initialization by user-defined conversion
7769 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7770 // from the return type of F1 to the destination type (i.e.,
7771 // the type of the entity being initialized) is a better
7772 // conversion sequence than the standard conversion sequence
7773 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007774 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007775 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007776 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007777 // First check whether we prefer one of the conversion functions over the
7778 // other. This only distinguishes the results in non-standard, extension
7779 // cases such as the conversion from a lambda closure type to a function
7780 // pointer or block.
7781 ImplicitConversionSequence::CompareKind FuncResult
7782 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7783 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7784 return FuncResult;
7785
John McCall5c32be02010-08-24 20:38:10 +00007786 switch (CompareStandardConversionSequences(S,
7787 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007788 Cand2.FinalConversion)) {
7789 case ImplicitConversionSequence::Better:
7790 // Cand1 has a better conversion sequence.
7791 return true;
7792
7793 case ImplicitConversionSequence::Worse:
7794 // Cand1 can't be better than Cand2.
7795 return false;
7796
7797 case ImplicitConversionSequence::Indistinguishable:
7798 // Do nothing
7799 break;
7800 }
7801 }
7802
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007803 return false;
7804}
7805
Mike Stump11289f42009-09-09 15:08:12 +00007806/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007807/// within an overload candidate set.
7808///
James Dennettffad8b72012-06-22 08:10:18 +00007809/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007810/// which overload resolution occurs.
7811///
James Dennettffad8b72012-06-22 08:10:18 +00007812/// \param Best If overload resolution was successful or found a deleted
7813/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007814///
7815/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007816OverloadingResult
7817OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007818 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007819 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007820 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007821 Best = end();
7822 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7823 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007824 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007825 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007826 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007827 }
7828
7829 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007830 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007831 return OR_No_Viable_Function;
7832
7833 // Make sure that this function is better than every other viable
7834 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007835 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007836 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007837 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007838 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007839 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007840 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007841 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007842 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007843 }
Mike Stump11289f42009-09-09 15:08:12 +00007844
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007845 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007846 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007847 (Best->Function->isDeleted() ||
7848 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007849 return OR_Deleted;
7850
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007851 return OR_Success;
7852}
7853
John McCall53262c92010-01-12 02:15:36 +00007854namespace {
7855
7856enum OverloadCandidateKind {
7857 oc_function,
7858 oc_method,
7859 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007860 oc_function_template,
7861 oc_method_template,
7862 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007863 oc_implicit_default_constructor,
7864 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007865 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007866 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007867 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007868 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007869};
7870
John McCalle1ac8d12010-01-13 00:25:19 +00007871OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7872 FunctionDecl *Fn,
7873 std::string &Description) {
7874 bool isTemplate = false;
7875
7876 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7877 isTemplate = true;
7878 Description = S.getTemplateArgumentBindingsText(
7879 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7880 }
John McCallfd0b2f82010-01-06 09:43:14 +00007881
7882 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007883 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007884 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007885
Sebastian Redl08905022011-02-05 19:23:19 +00007886 if (Ctor->getInheritedConstructor())
7887 return oc_implicit_inherited_constructor;
7888
Alexis Hunt119c10e2011-05-25 23:16:36 +00007889 if (Ctor->isDefaultConstructor())
7890 return oc_implicit_default_constructor;
7891
7892 if (Ctor->isMoveConstructor())
7893 return oc_implicit_move_constructor;
7894
7895 assert(Ctor->isCopyConstructor() &&
7896 "unexpected sort of implicit constructor");
7897 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007898 }
7899
7900 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7901 // This actually gets spelled 'candidate function' for now, but
7902 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007903 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007904 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007905
Alexis Hunt119c10e2011-05-25 23:16:36 +00007906 if (Meth->isMoveAssignmentOperator())
7907 return oc_implicit_move_assignment;
7908
Douglas Gregor12695102012-02-10 08:36:38 +00007909 if (Meth->isCopyAssignmentOperator())
7910 return oc_implicit_copy_assignment;
7911
7912 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7913 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007914 }
7915
John McCalle1ac8d12010-01-13 00:25:19 +00007916 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007917}
7918
Sebastian Redl08905022011-02-05 19:23:19 +00007919void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7920 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7921 if (!Ctor) return;
7922
7923 Ctor = Ctor->getInheritedConstructor();
7924 if (!Ctor) return;
7925
7926 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7927}
7928
John McCall53262c92010-01-12 02:15:36 +00007929} // end anonymous namespace
7930
7931// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007932void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007933 std::string FnDesc;
7934 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007935 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7936 << (unsigned) K << FnDesc;
7937 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7938 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007939 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007940}
7941
Douglas Gregorb491ed32011-02-19 21:32:49 +00007942//Notes the location of all overload candidates designated through
7943// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007944void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007945 assert(OverloadedExpr->getType() == Context.OverloadTy);
7946
7947 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7948 OverloadExpr *OvlExpr = Ovl.Expression;
7949
7950 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7951 IEnd = OvlExpr->decls_end();
7952 I != IEnd; ++I) {
7953 if (FunctionTemplateDecl *FunTmpl =
7954 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007955 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007956 } else if (FunctionDecl *Fun
7957 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007958 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007959 }
7960 }
7961}
7962
John McCall0d1da222010-01-12 00:44:57 +00007963/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7964/// "lead" diagnostic; it will be given two arguments, the source and
7965/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007966void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7967 Sema &S,
7968 SourceLocation CaretLoc,
7969 const PartialDiagnostic &PDiag) const {
7970 S.Diag(CaretLoc, PDiag)
7971 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007972 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007973 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7974 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007975 }
John McCall12f97bc2010-01-08 04:41:39 +00007976}
7977
John McCall0d1da222010-01-12 00:44:57 +00007978namespace {
7979
John McCall6a61b522010-01-13 09:16:55 +00007980void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7981 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7982 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007983 assert(Cand->Function && "for now, candidate must be a function");
7984 FunctionDecl *Fn = Cand->Function;
7985
7986 // There's a conversion slot for the object argument if this is a
7987 // non-constructor method. Note that 'I' corresponds the
7988 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007989 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007990 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007991 if (I == 0)
7992 isObjectArgument = true;
7993 else
7994 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007995 }
7996
John McCalle1ac8d12010-01-13 00:25:19 +00007997 std::string FnDesc;
7998 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7999
John McCall6a61b522010-01-13 09:16:55 +00008000 Expr *FromExpr = Conv.Bad.FromExpr;
8001 QualType FromTy = Conv.Bad.getFromType();
8002 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008003
John McCallfb7ad0f2010-02-02 02:42:52 +00008004 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008005 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008006 Expr *E = FromExpr->IgnoreParens();
8007 if (isa<UnaryOperator>(E))
8008 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008009 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008010
8011 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8012 << (unsigned) FnKind << FnDesc
8013 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8014 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008015 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008016 return;
8017 }
8018
John McCall6d174642010-01-23 08:10:49 +00008019 // Do some hand-waving analysis to see if the non-viability is due
8020 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008021 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8022 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8023 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8024 CToTy = RT->getPointeeType();
8025 else {
8026 // TODO: detect and diagnose the full richness of const mismatches.
8027 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8028 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8029 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8030 }
8031
8032 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8033 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008034 Qualifiers FromQs = CFromTy.getQualifiers();
8035 Qualifiers ToQs = CToTy.getQualifiers();
8036
8037 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8038 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8039 << (unsigned) FnKind << FnDesc
8040 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8041 << FromTy
8042 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8043 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008044 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008045 return;
8046 }
8047
John McCall31168b02011-06-15 23:02:42 +00008048 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008050 << (unsigned) FnKind << FnDesc
8051 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8052 << FromTy
8053 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8054 << (unsigned) isObjectArgument << I+1;
8055 MaybeEmitInheritedConstructorNote(S, Fn);
8056 return;
8057 }
8058
Douglas Gregoraec25842011-04-26 23:16:46 +00008059 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8061 << (unsigned) FnKind << FnDesc
8062 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8063 << FromTy
8064 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8065 << (unsigned) isObjectArgument << I+1;
8066 MaybeEmitInheritedConstructorNote(S, Fn);
8067 return;
8068 }
8069
John McCall47000992010-01-14 03:28:57 +00008070 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8071 assert(CVR && "unexpected qualifiers mismatch");
8072
8073 if (isObjectArgument) {
8074 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8075 << (unsigned) FnKind << FnDesc
8076 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8077 << FromTy << (CVR - 1);
8078 } else {
8079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8080 << (unsigned) FnKind << FnDesc
8081 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8082 << FromTy << (CVR - 1) << I+1;
8083 }
Sebastian Redl08905022011-02-05 19:23:19 +00008084 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008085 return;
8086 }
8087
Sebastian Redla72462c2011-09-24 17:48:32 +00008088 // Special diagnostic for failure to convert an initializer list, since
8089 // telling the user that it has type void is not useful.
8090 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8091 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8092 << (unsigned) FnKind << FnDesc
8093 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8094 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8095 MaybeEmitInheritedConstructorNote(S, Fn);
8096 return;
8097 }
8098
John McCall6d174642010-01-23 08:10:49 +00008099 // Diagnose references or pointers to incomplete types differently,
8100 // since it's far from impossible that the incompleteness triggered
8101 // the failure.
8102 QualType TempFromTy = FromTy.getNonReferenceType();
8103 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8104 TempFromTy = PTy->getPointeeType();
8105 if (TempFromTy->isIncompleteType()) {
8106 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8107 << (unsigned) FnKind << FnDesc
8108 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8109 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008110 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008111 return;
8112 }
8113
Douglas Gregor56f2e342010-06-30 23:01:39 +00008114 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008115 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008116 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8117 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8118 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8119 FromPtrTy->getPointeeType()) &&
8120 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8121 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008123 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008124 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008125 }
8126 } else if (const ObjCObjectPointerType *FromPtrTy
8127 = FromTy->getAs<ObjCObjectPointerType>()) {
8128 if (const ObjCObjectPointerType *ToPtrTy
8129 = ToTy->getAs<ObjCObjectPointerType>())
8130 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8131 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8132 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8133 FromPtrTy->getPointeeType()) &&
8134 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008135 BaseToDerivedConversion = 2;
8136 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008137 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8138 !FromTy->isIncompleteType() &&
8139 !ToRefTy->getPointeeType()->isIncompleteType() &&
8140 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8141 BaseToDerivedConversion = 3;
8142 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8143 ToTy.getNonReferenceType().getCanonicalType() ==
8144 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8146 << (unsigned) FnKind << FnDesc
8147 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8148 << (unsigned) isObjectArgument << I + 1;
8149 MaybeEmitInheritedConstructorNote(S, Fn);
8150 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008151 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008154 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008155 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008156 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008157 << (unsigned) FnKind << FnDesc
8158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008159 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008161 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008162 return;
8163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008165 if (isa<ObjCObjectPointerType>(CFromTy) &&
8166 isa<PointerType>(CToTy)) {
8167 Qualifiers FromQs = CFromTy.getQualifiers();
8168 Qualifiers ToQs = CToTy.getQualifiers();
8169 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8170 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8171 << (unsigned) FnKind << FnDesc
8172 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8173 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8174 MaybeEmitInheritedConstructorNote(S, Fn);
8175 return;
8176 }
8177 }
8178
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008179 // Emit the generic diagnostic and, optionally, add the hints to it.
8180 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8181 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008182 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008183 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8184 << (unsigned) (Cand->Fix.Kind);
8185
8186 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008187 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8188 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008189 FDiag << *HI;
8190 S.Diag(Fn->getLocation(), FDiag);
8191
Sebastian Redl08905022011-02-05 19:23:19 +00008192 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008193}
8194
8195void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8196 unsigned NumFormalArgs) {
8197 // TODO: treat calls to a missing default constructor as a special case
8198
8199 FunctionDecl *Fn = Cand->Function;
8200 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8201
8202 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008203
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008204 // With invalid overloaded operators, it's possible that we think we
8205 // have an arity mismatch when it fact it looks like we have the
8206 // right number of arguments, because only overloaded operators have
8207 // the weird behavior of overloading member and non-member functions.
8208 // Just don't report anything.
8209 if (Fn->isInvalidDecl() &&
8210 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8211 return;
8212
John McCall6a61b522010-01-13 09:16:55 +00008213 // at least / at most / exactly
8214 unsigned mode, modeCount;
8215 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008216 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8217 (Cand->FailureKind == ovl_fail_bad_deduction &&
8218 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008219 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008220 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008221 mode = 0; // "at least"
8222 else
8223 mode = 2; // "exactly"
8224 modeCount = MinParams;
8225 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008226 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8227 (Cand->FailureKind == ovl_fail_bad_deduction &&
8228 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008229 if (MinParams != FnTy->getNumArgs())
8230 mode = 1; // "at most"
8231 else
8232 mode = 2; // "exactly"
8233 modeCount = FnTy->getNumArgs();
8234 }
8235
8236 std::string Description;
8237 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8238
Richard Smith10ff50d2012-05-11 05:16:41 +00008239 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8241 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8242 << Fn->getParamDecl(0) << NumFormalArgs;
8243 else
8244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8245 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8246 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008247 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008248}
8249
John McCall8b9ed552010-02-01 18:53:26 +00008250/// Diagnose a failed template-argument deduction.
8251void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008252 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008253 FunctionDecl *Fn = Cand->Function; // pattern
8254
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008255 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008256 NamedDecl *ParamD;
8257 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8258 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8259 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008260 switch (Cand->DeductionFailure.Result) {
8261 case Sema::TDK_Success:
8262 llvm_unreachable("TDK_success while diagnosing bad deduction");
8263
8264 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008265 assert(ParamD && "no parameter found for incomplete deduction result");
8266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8267 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008268 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008269 return;
8270 }
8271
John McCall42d7d192010-08-05 09:05:08 +00008272 case Sema::TDK_Underqualified: {
8273 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8274 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8275
8276 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8277
8278 // Param will have been canonicalized, but it should just be a
8279 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008280 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008281 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008282 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008283 assert(S.Context.hasSameType(Param, NonCanonParam));
8284
8285 // Arg has also been canonicalized, but there's nothing we can do
8286 // about that. It also doesn't matter as much, because it won't
8287 // have any template parameters in it (because deduction isn't
8288 // done on dependent types).
8289 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8290
8291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8292 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008293 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008294 return;
8295 }
8296
8297 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008298 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008299 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008300 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008301 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008302 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008303 which = 1;
8304 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008305 which = 2;
8306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008307
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008309 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008310 << *Cand->DeductionFailure.getFirstArg()
8311 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008312 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008313 return;
8314 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008315
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008316 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008317 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008318 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008319 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008320 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8321 << ParamD->getDeclName();
8322 else {
8323 int index = 0;
8324 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8325 index = TTP->getIndex();
8326 else if (NonTypeTemplateParmDecl *NTTP
8327 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8328 index = NTTP->getIndex();
8329 else
8330 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008331 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008332 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8333 << (index + 1);
8334 }
Sebastian Redl08905022011-02-05 19:23:19 +00008335 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008336 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008337
Douglas Gregor02eb4832010-05-08 18:13:28 +00008338 case Sema::TDK_TooManyArguments:
8339 case Sema::TDK_TooFewArguments:
8340 DiagnoseArityMismatch(S, Cand, NumArgs);
8341 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008342
8343 case Sema::TDK_InstantiationDepth:
8344 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008345 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008346 return;
8347
8348 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008349 // Format the template argument list into the argument string.
8350 llvm::SmallString<128> TemplateArgString;
8351 if (TemplateArgumentList *Args =
8352 Cand->DeductionFailure.getTemplateArgumentList()) {
8353 TemplateArgString = " ";
8354 TemplateArgString += S.getTemplateArgumentBindingsText(
8355 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8356 }
8357
Richard Smith6f8d2c62012-05-09 05:17:00 +00008358 // If this candidate was disabled by enable_if, say so.
8359 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8360 if (PDiag && PDiag->second.getDiagID() ==
8361 diag::err_typename_nested_not_found_enable_if) {
8362 // FIXME: Use the source range of the condition, and the fully-qualified
8363 // name of the enable_if template. These are both present in PDiag.
8364 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8365 << "'enable_if'" << TemplateArgString;
8366 return;
8367 }
8368
Richard Smith9ca64612012-05-07 09:03:25 +00008369 // Format the SFINAE diagnostic into the argument string.
8370 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8371 // formatted message in another diagnostic.
8372 llvm::SmallString<128> SFINAEArgString;
8373 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008374 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008375 SFINAEArgString = ": ";
8376 R = SourceRange(PDiag->first, PDiag->first);
8377 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8378 }
8379
Douglas Gregord09efd42010-05-08 20:07:26 +00008380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008381 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008382 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008383 return;
8384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008385
John McCall8b9ed552010-02-01 18:53:26 +00008386 // TODO: diagnose these individually, then kill off
8387 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008388 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008389 case Sema::TDK_FailedOverloadResolution:
8390 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008391 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008392 return;
8393 }
8394}
8395
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008396/// CUDA: diagnose an invalid call across targets.
8397void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8398 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8399 FunctionDecl *Callee = Cand->Function;
8400
8401 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8402 CalleeTarget = S.IdentifyCUDATarget(Callee);
8403
8404 std::string FnDesc;
8405 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8406
8407 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8408 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8409}
8410
John McCall8b9ed552010-02-01 18:53:26 +00008411/// Generates a 'note' diagnostic for an overload candidate. We've
8412/// already generated a primary error at the call site.
8413///
8414/// It really does need to be a single diagnostic with its caret
8415/// pointed at the candidate declaration. Yes, this creates some
8416/// major challenges of technical writing. Yes, this makes pointing
8417/// out problems with specific arguments quite awkward. It's still
8418/// better than generating twenty screens of text for every failed
8419/// overload.
8420///
8421/// It would be great to be able to express per-candidate problems
8422/// more richly for those diagnostic clients that cared, but we'd
8423/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008424void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008425 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008426 FunctionDecl *Fn = Cand->Function;
8427
John McCall12f97bc2010-01-08 04:41:39 +00008428 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008429 if (Cand->Viable && (Fn->isDeleted() ||
8430 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008431 std::string FnDesc;
8432 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008433
8434 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008435 << FnKind << FnDesc
8436 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008437 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008438 return;
John McCall12f97bc2010-01-08 04:41:39 +00008439 }
8440
John McCalle1ac8d12010-01-13 00:25:19 +00008441 // We don't really have anything else to say about viable candidates.
8442 if (Cand->Viable) {
8443 S.NoteOverloadCandidate(Fn);
8444 return;
8445 }
John McCall0d1da222010-01-12 00:44:57 +00008446
John McCall6a61b522010-01-13 09:16:55 +00008447 switch (Cand->FailureKind) {
8448 case ovl_fail_too_many_arguments:
8449 case ovl_fail_too_few_arguments:
8450 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008451
John McCall6a61b522010-01-13 09:16:55 +00008452 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008453 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008454
John McCallfe796dd2010-01-23 05:17:32 +00008455 case ovl_fail_trivial_conversion:
8456 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008457 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008458 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008459
John McCall65eb8792010-02-25 01:37:24 +00008460 case ovl_fail_bad_conversion: {
8461 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008462 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008463 if (Cand->Conversions[I].isBad())
8464 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008465
John McCall6a61b522010-01-13 09:16:55 +00008466 // FIXME: this currently happens when we're called from SemaInit
8467 // when user-conversion overload fails. Figure out how to handle
8468 // those conditions and diagnose them well.
8469 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008470 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008471
8472 case ovl_fail_bad_target:
8473 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008474 }
John McCalld3224162010-01-08 00:58:21 +00008475}
8476
8477void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8478 // Desugar the type of the surrogate down to a function type,
8479 // retaining as many typedefs as possible while still showing
8480 // the function type (and, therefore, its parameter types).
8481 QualType FnType = Cand->Surrogate->getConversionType();
8482 bool isLValueReference = false;
8483 bool isRValueReference = false;
8484 bool isPointer = false;
8485 if (const LValueReferenceType *FnTypeRef =
8486 FnType->getAs<LValueReferenceType>()) {
8487 FnType = FnTypeRef->getPointeeType();
8488 isLValueReference = true;
8489 } else if (const RValueReferenceType *FnTypeRef =
8490 FnType->getAs<RValueReferenceType>()) {
8491 FnType = FnTypeRef->getPointeeType();
8492 isRValueReference = true;
8493 }
8494 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8495 FnType = FnTypePtr->getPointeeType();
8496 isPointer = true;
8497 }
8498 // Desugar down to a function type.
8499 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8500 // Reconstruct the pointer/reference as appropriate.
8501 if (isPointer) FnType = S.Context.getPointerType(FnType);
8502 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8503 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8504
8505 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8506 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008507 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008508}
8509
8510void NoteBuiltinOperatorCandidate(Sema &S,
8511 const char *Opc,
8512 SourceLocation OpLoc,
8513 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008514 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008515 std::string TypeStr("operator");
8516 TypeStr += Opc;
8517 TypeStr += "(";
8518 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008519 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008520 TypeStr += ")";
8521 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8522 } else {
8523 TypeStr += ", ";
8524 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8525 TypeStr += ")";
8526 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8527 }
8528}
8529
8530void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8531 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008532 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008533 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8534 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008535 if (ICS.isBad()) break; // all meaningless after first invalid
8536 if (!ICS.isAmbiguous()) continue;
8537
John McCall5c32be02010-08-24 20:38:10 +00008538 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008539 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008540 }
8541}
8542
John McCall3712d9e2010-01-15 23:32:50 +00008543SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8544 if (Cand->Function)
8545 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008546 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008547 return Cand->Surrogate->getLocation();
8548 return SourceLocation();
8549}
8550
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008551static unsigned
8552RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008553 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008554 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008555 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008556
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008557 case Sema::TDK_Incomplete:
8558 return 1;
8559
8560 case Sema::TDK_Underqualified:
8561 case Sema::TDK_Inconsistent:
8562 return 2;
8563
8564 case Sema::TDK_SubstitutionFailure:
8565 case Sema::TDK_NonDeducedMismatch:
8566 return 3;
8567
8568 case Sema::TDK_InstantiationDepth:
8569 case Sema::TDK_FailedOverloadResolution:
8570 return 4;
8571
8572 case Sema::TDK_InvalidExplicitArguments:
8573 return 5;
8574
8575 case Sema::TDK_TooManyArguments:
8576 case Sema::TDK_TooFewArguments:
8577 return 6;
8578 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008579 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008580}
8581
John McCallad2587a2010-01-12 00:48:53 +00008582struct CompareOverloadCandidatesForDisplay {
8583 Sema &S;
8584 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008585
8586 bool operator()(const OverloadCandidate *L,
8587 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008588 // Fast-path this check.
8589 if (L == R) return false;
8590
John McCall12f97bc2010-01-08 04:41:39 +00008591 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008592 if (L->Viable) {
8593 if (!R->Viable) return true;
8594
8595 // TODO: introduce a tri-valued comparison for overload
8596 // candidates. Would be more worthwhile if we had a sort
8597 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008598 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8599 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008600 } else if (R->Viable)
8601 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008602
John McCall3712d9e2010-01-15 23:32:50 +00008603 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008604
John McCall3712d9e2010-01-15 23:32:50 +00008605 // Criteria by which we can sort non-viable candidates:
8606 if (!L->Viable) {
8607 // 1. Arity mismatches come after other candidates.
8608 if (L->FailureKind == ovl_fail_too_many_arguments ||
8609 L->FailureKind == ovl_fail_too_few_arguments)
8610 return false;
8611 if (R->FailureKind == ovl_fail_too_many_arguments ||
8612 R->FailureKind == ovl_fail_too_few_arguments)
8613 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008614
John McCallfe796dd2010-01-23 05:17:32 +00008615 // 2. Bad conversions come first and are ordered by the number
8616 // of bad conversions and quality of good conversions.
8617 if (L->FailureKind == ovl_fail_bad_conversion) {
8618 if (R->FailureKind != ovl_fail_bad_conversion)
8619 return true;
8620
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008621 // The conversion that can be fixed with a smaller number of changes,
8622 // comes first.
8623 unsigned numLFixes = L->Fix.NumConversionsFixed;
8624 unsigned numRFixes = R->Fix.NumConversionsFixed;
8625 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8626 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008627 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008628 if (numLFixes < numRFixes)
8629 return true;
8630 else
8631 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008632 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008633
John McCallfe796dd2010-01-23 05:17:32 +00008634 // If there's any ordering between the defined conversions...
8635 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008636 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008637
8638 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008639 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008640 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008641 switch (CompareImplicitConversionSequences(S,
8642 L->Conversions[I],
8643 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008644 case ImplicitConversionSequence::Better:
8645 leftBetter++;
8646 break;
8647
8648 case ImplicitConversionSequence::Worse:
8649 leftBetter--;
8650 break;
8651
8652 case ImplicitConversionSequence::Indistinguishable:
8653 break;
8654 }
8655 }
8656 if (leftBetter > 0) return true;
8657 if (leftBetter < 0) return false;
8658
8659 } else if (R->FailureKind == ovl_fail_bad_conversion)
8660 return false;
8661
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008662 if (L->FailureKind == ovl_fail_bad_deduction) {
8663 if (R->FailureKind != ovl_fail_bad_deduction)
8664 return true;
8665
8666 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8667 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008668 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008669 } else if (R->FailureKind == ovl_fail_bad_deduction)
8670 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008671
John McCall3712d9e2010-01-15 23:32:50 +00008672 // TODO: others?
8673 }
8674
8675 // Sort everything else by location.
8676 SourceLocation LLoc = GetLocationForCandidate(L);
8677 SourceLocation RLoc = GetLocationForCandidate(R);
8678
8679 // Put candidates without locations (e.g. builtins) at the end.
8680 if (LLoc.isInvalid()) return false;
8681 if (RLoc.isInvalid()) return true;
8682
8683 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008684 }
8685};
8686
John McCallfe796dd2010-01-23 05:17:32 +00008687/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008688/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008689void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008690 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008691 assert(!Cand->Viable);
8692
8693 // Don't do anything on failures other than bad conversion.
8694 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8695
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008696 // We only want the FixIts if all the arguments can be corrected.
8697 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008698 // Use a implicit copy initialization to check conversion fixes.
8699 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008700
John McCallfe796dd2010-01-23 05:17:32 +00008701 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008702 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008703 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008704 while (true) {
8705 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8706 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008707 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008708 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008709 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008710 }
John McCallfe796dd2010-01-23 05:17:32 +00008711 }
8712
8713 if (ConvIdx == ConvCount)
8714 return;
8715
John McCall65eb8792010-02-25 01:37:24 +00008716 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8717 "remaining conversion is initialized?");
8718
Douglas Gregoradc7a702010-04-16 17:45:54 +00008719 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008720 // operation somehow.
8721 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008722
8723 const FunctionProtoType* Proto;
8724 unsigned ArgIdx = ConvIdx;
8725
8726 if (Cand->IsSurrogate) {
8727 QualType ConvType
8728 = Cand->Surrogate->getConversionType().getNonReferenceType();
8729 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8730 ConvType = ConvPtrType->getPointeeType();
8731 Proto = ConvType->getAs<FunctionProtoType>();
8732 ArgIdx--;
8733 } else if (Cand->Function) {
8734 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8735 if (isa<CXXMethodDecl>(Cand->Function) &&
8736 !isa<CXXConstructorDecl>(Cand->Function))
8737 ArgIdx--;
8738 } else {
8739 // Builtin binary operator with a bad first conversion.
8740 assert(ConvCount <= 3);
8741 for (; ConvIdx != ConvCount; ++ConvIdx)
8742 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008743 = TryCopyInitialization(S, Args[ConvIdx],
8744 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008745 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008746 /*InOverloadResolution*/ true,
8747 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008748 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008749 return;
8750 }
8751
8752 // Fill in the rest of the conversions.
8753 unsigned NumArgsInProto = Proto->getNumArgs();
8754 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008755 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008756 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008757 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008758 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008759 /*InOverloadResolution=*/true,
8760 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008761 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008762 // Store the FixIt in the candidate if it exists.
8763 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008764 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008765 }
John McCallfe796dd2010-01-23 05:17:32 +00008766 else
8767 Cand->Conversions[ConvIdx].setEllipsis();
8768 }
8769}
8770
John McCalld3224162010-01-08 00:58:21 +00008771} // end anonymous namespace
8772
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008773/// PrintOverloadCandidates - When overload resolution fails, prints
8774/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008775/// set.
John McCall5c32be02010-08-24 20:38:10 +00008776void OverloadCandidateSet::NoteCandidates(Sema &S,
8777 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008778 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008779 const char *Opc,
8780 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008781 // Sort the candidates by viability and position. Sorting directly would
8782 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008783 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008784 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8785 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008786 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008787 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008788 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008789 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008790 if (Cand->Function || Cand->IsSurrogate)
8791 Cands.push_back(Cand);
8792 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8793 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008794 }
8795 }
8796
John McCallad2587a2010-01-12 00:48:53 +00008797 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008798 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008799
John McCall0d1da222010-01-12 00:44:57 +00008800 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008801
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008802 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008803 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8804 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008805 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008806 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8807 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008808
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008809 // Set an arbitrary limit on the number of candidate functions we'll spam
8810 // the user with. FIXME: This limit should depend on details of the
8811 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008812 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008813 break;
8814 }
8815 ++CandsShown;
8816
John McCalld3224162010-01-08 00:58:21 +00008817 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008818 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008819 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008820 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008821 else {
8822 assert(Cand->Viable &&
8823 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008824 // Generally we only see ambiguities including viable builtin
8825 // operators if overload resolution got screwed up by an
8826 // ambiguous user-defined conversion.
8827 //
8828 // FIXME: It's quite possible for different conversions to see
8829 // different ambiguities, though.
8830 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008831 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008832 ReportedAmbiguousConversions = true;
8833 }
John McCalld3224162010-01-08 00:58:21 +00008834
John McCall0d1da222010-01-12 00:44:57 +00008835 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008836 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008837 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008838 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008839
8840 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008841 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008842}
8843
Douglas Gregorb491ed32011-02-19 21:32:49 +00008844// [PossiblyAFunctionType] --> [Return]
8845// NonFunctionType --> NonFunctionType
8846// R (A) --> R(A)
8847// R (*)(A) --> R (A)
8848// R (&)(A) --> R (A)
8849// R (S::*)(A) --> R (A)
8850QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8851 QualType Ret = PossiblyAFunctionType;
8852 if (const PointerType *ToTypePtr =
8853 PossiblyAFunctionType->getAs<PointerType>())
8854 Ret = ToTypePtr->getPointeeType();
8855 else if (const ReferenceType *ToTypeRef =
8856 PossiblyAFunctionType->getAs<ReferenceType>())
8857 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008858 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008859 PossiblyAFunctionType->getAs<MemberPointerType>())
8860 Ret = MemTypePtr->getPointeeType();
8861 Ret =
8862 Context.getCanonicalType(Ret).getUnqualifiedType();
8863 return Ret;
8864}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008865
Douglas Gregorb491ed32011-02-19 21:32:49 +00008866// A helper class to help with address of function resolution
8867// - allows us to avoid passing around all those ugly parameters
8868class AddressOfFunctionResolver
8869{
8870 Sema& S;
8871 Expr* SourceExpr;
8872 const QualType& TargetType;
8873 QualType TargetFunctionType; // Extracted function type from target type
8874
8875 bool Complain;
8876 //DeclAccessPair& ResultFunctionAccessPair;
8877 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008878
Douglas Gregorb491ed32011-02-19 21:32:49 +00008879 bool TargetTypeIsNonStaticMemberFunction;
8880 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008881
Douglas Gregorb491ed32011-02-19 21:32:49 +00008882 OverloadExpr::FindResult OvlExprInfo;
8883 OverloadExpr *OvlExpr;
8884 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008885 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008886
Douglas Gregorb491ed32011-02-19 21:32:49 +00008887public:
8888 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8889 const QualType& TargetType, bool Complain)
8890 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8891 Complain(Complain), Context(S.getASTContext()),
8892 TargetTypeIsNonStaticMemberFunction(
8893 !!TargetType->getAs<MemberPointerType>()),
8894 FoundNonTemplateFunction(false),
8895 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8896 OvlExpr(OvlExprInfo.Expression)
8897 {
8898 ExtractUnqualifiedFunctionTypeFromTargetType();
8899
8900 if (!TargetFunctionType->isFunctionType()) {
8901 if (OvlExpr->hasExplicitTemplateArgs()) {
8902 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008903 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008904 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008905
8906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8907 if (!Method->isStatic()) {
8908 // If the target type is a non-function type and the function
8909 // found is a non-static member function, pretend as if that was
8910 // the target, it's the only possible type to end up with.
8911 TargetTypeIsNonStaticMemberFunction = true;
8912
8913 // And skip adding the function if its not in the proper form.
8914 // We'll diagnose this due to an empty set of functions.
8915 if (!OvlExprInfo.HasFormOfMemberPointer)
8916 return;
8917 }
8918 }
8919
Douglas Gregorb491ed32011-02-19 21:32:49 +00008920 Matches.push_back(std::make_pair(dap,Fn));
8921 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008922 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008923 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008924 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008925
8926 if (OvlExpr->hasExplicitTemplateArgs())
8927 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008928
Douglas Gregorb491ed32011-02-19 21:32:49 +00008929 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8930 // C++ [over.over]p4:
8931 // If more than one function is selected, [...]
8932 if (Matches.size() > 1) {
8933 if (FoundNonTemplateFunction)
8934 EliminateAllTemplateMatches();
8935 else
8936 EliminateAllExceptMostSpecializedTemplate();
8937 }
8938 }
8939 }
8940
8941private:
8942 bool isTargetTypeAFunction() const {
8943 return TargetFunctionType->isFunctionType();
8944 }
8945
8946 // [ToType] [Return]
8947
8948 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8949 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8950 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8951 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8952 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8953 }
8954
8955 // return true if any matching specializations were found
8956 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8957 const DeclAccessPair& CurAccessFunPair) {
8958 if (CXXMethodDecl *Method
8959 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8960 // Skip non-static function templates when converting to pointer, and
8961 // static when converting to member pointer.
8962 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8963 return false;
8964 }
8965 else if (TargetTypeIsNonStaticMemberFunction)
8966 return false;
8967
8968 // C++ [over.over]p2:
8969 // If the name is a function template, template argument deduction is
8970 // done (14.8.2.2), and if the argument deduction succeeds, the
8971 // resulting template argument list is used to generate a single
8972 // function template specialization, which is added to the set of
8973 // overloaded functions considered.
8974 FunctionDecl *Specialization = 0;
8975 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8976 if (Sema::TemplateDeductionResult Result
8977 = S.DeduceTemplateArguments(FunctionTemplate,
8978 &OvlExplicitTemplateArgs,
8979 TargetFunctionType, Specialization,
8980 Info)) {
8981 // FIXME: make a note of the failed deduction for diagnostics.
8982 (void)Result;
8983 return false;
8984 }
8985
8986 // Template argument deduction ensures that we have an exact match.
8987 // This function template specicalization works.
8988 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8989 assert(TargetFunctionType
8990 == Context.getCanonicalType(Specialization->getType()));
8991 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8992 return true;
8993 }
8994
8995 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8996 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008997 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008998 // Skip non-static functions when converting to pointer, and static
8999 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009000 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9001 return false;
9002 }
9003 else if (TargetTypeIsNonStaticMemberFunction)
9004 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009005
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009006 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009007 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009008 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9009 if (S.CheckCUDATarget(Caller, FunDecl))
9010 return false;
9011
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009012 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009013 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9014 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009015 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9016 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009017 Matches.push_back(std::make_pair(CurAccessFunPair,
9018 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009019 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009020 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009021 }
Mike Stump11289f42009-09-09 15:08:12 +00009022 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009023
9024 return false;
9025 }
9026
9027 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9028 bool Ret = false;
9029
9030 // If the overload expression doesn't have the form of a pointer to
9031 // member, don't try to convert it to a pointer-to-member type.
9032 if (IsInvalidFormOfPointerToMemberFunction())
9033 return false;
9034
9035 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9036 E = OvlExpr->decls_end();
9037 I != E; ++I) {
9038 // Look through any using declarations to find the underlying function.
9039 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9040
9041 // C++ [over.over]p3:
9042 // Non-member functions and static member functions match
9043 // targets of type "pointer-to-function" or "reference-to-function."
9044 // Nonstatic member functions match targets of
9045 // type "pointer-to-member-function."
9046 // Note that according to DR 247, the containing class does not matter.
9047 if (FunctionTemplateDecl *FunctionTemplate
9048 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9049 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9050 Ret = true;
9051 }
9052 // If we have explicit template arguments supplied, skip non-templates.
9053 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9054 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9055 Ret = true;
9056 }
9057 assert(Ret || Matches.empty());
9058 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009059 }
9060
Douglas Gregorb491ed32011-02-19 21:32:49 +00009061 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009062 // [...] and any given function template specialization F1 is
9063 // eliminated if the set contains a second function template
9064 // specialization whose function template is more specialized
9065 // than the function template of F1 according to the partial
9066 // ordering rules of 14.5.5.2.
9067
9068 // The algorithm specified above is quadratic. We instead use a
9069 // two-pass algorithm (similar to the one used to identify the
9070 // best viable function in an overload set) that identifies the
9071 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009072
9073 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9074 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9075 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009076
John McCall58cc69d2010-01-27 01:50:18 +00009077 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009078 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9079 TPOC_Other, 0, SourceExpr->getLocStart(),
9080 S.PDiag(),
9081 S.PDiag(diag::err_addr_ovl_ambiguous)
9082 << Matches[0].second->getDeclName(),
9083 S.PDiag(diag::note_ovl_candidate)
9084 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009085 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009086
Douglas Gregorb491ed32011-02-19 21:32:49 +00009087 if (Result != MatchesCopy.end()) {
9088 // Make it the first and only element
9089 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9090 Matches[0].second = cast<FunctionDecl>(*Result);
9091 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009092 }
9093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009094
Douglas Gregorb491ed32011-02-19 21:32:49 +00009095 void EliminateAllTemplateMatches() {
9096 // [...] any function template specializations in the set are
9097 // eliminated if the set also contains a non-template function, [...]
9098 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9099 if (Matches[I].second->getPrimaryTemplate() == 0)
9100 ++I;
9101 else {
9102 Matches[I] = Matches[--N];
9103 Matches.set_size(N);
9104 }
9105 }
9106 }
9107
9108public:
9109 void ComplainNoMatchesFound() const {
9110 assert(Matches.empty());
9111 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9112 << OvlExpr->getName() << TargetFunctionType
9113 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009114 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009115 }
9116
9117 bool IsInvalidFormOfPointerToMemberFunction() const {
9118 return TargetTypeIsNonStaticMemberFunction &&
9119 !OvlExprInfo.HasFormOfMemberPointer;
9120 }
9121
9122 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9123 // TODO: Should we condition this on whether any functions might
9124 // have matched, or is it more appropriate to do that in callers?
9125 // TODO: a fixit wouldn't hurt.
9126 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9127 << TargetType << OvlExpr->getSourceRange();
9128 }
9129
9130 void ComplainOfInvalidConversion() const {
9131 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9132 << OvlExpr->getName() << TargetType;
9133 }
9134
9135 void ComplainMultipleMatchesFound() const {
9136 assert(Matches.size() > 1);
9137 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9138 << OvlExpr->getName()
9139 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009140 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009141 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009142
9143 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9144
Douglas Gregorb491ed32011-02-19 21:32:49 +00009145 int getNumMatches() const { return Matches.size(); }
9146
9147 FunctionDecl* getMatchingFunctionDecl() const {
9148 if (Matches.size() != 1) return 0;
9149 return Matches[0].second;
9150 }
9151
9152 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9153 if (Matches.size() != 1) return 0;
9154 return &Matches[0].first;
9155 }
9156};
9157
9158/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9159/// an overloaded function (C++ [over.over]), where @p From is an
9160/// expression with overloaded function type and @p ToType is the type
9161/// we're trying to resolve to. For example:
9162///
9163/// @code
9164/// int f(double);
9165/// int f(int);
9166///
9167/// int (*pfd)(double) = f; // selects f(double)
9168/// @endcode
9169///
9170/// This routine returns the resulting FunctionDecl if it could be
9171/// resolved, and NULL otherwise. When @p Complain is true, this
9172/// routine will emit diagnostics if there is an error.
9173FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009174Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9175 QualType TargetType,
9176 bool Complain,
9177 DeclAccessPair &FoundResult,
9178 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009179 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009180
9181 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9182 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009183 int NumMatches = Resolver.getNumMatches();
9184 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009185 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009186 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9187 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9188 else
9189 Resolver.ComplainNoMatchesFound();
9190 }
9191 else if (NumMatches > 1 && Complain)
9192 Resolver.ComplainMultipleMatchesFound();
9193 else if (NumMatches == 1) {
9194 Fn = Resolver.getMatchingFunctionDecl();
9195 assert(Fn);
9196 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009197 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009198 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009199 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009200 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009201
9202 if (pHadMultipleCandidates)
9203 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009204 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009205}
9206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009207/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009208/// resolve that overloaded function expression down to a single function.
9209///
9210/// This routine can only resolve template-ids that refer to a single function
9211/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009212/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009213/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009214FunctionDecl *
9215Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9216 bool Complain,
9217 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009218 // C++ [over.over]p1:
9219 // [...] [Note: any redundant set of parentheses surrounding the
9220 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009221 // C++ [over.over]p1:
9222 // [...] The overloaded function name can be preceded by the &
9223 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009224
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009225 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009226 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009227 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009228
9229 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009230 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009231
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009232 // Look through all of the overloaded functions, searching for one
9233 // whose type matches exactly.
9234 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009235 for (UnresolvedSetIterator I = ovl->decls_begin(),
9236 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009237 // C++0x [temp.arg.explicit]p3:
9238 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009239 // where deduction is not done, if a template argument list is
9240 // specified and it, along with any default template arguments,
9241 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009242 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009243 FunctionTemplateDecl *FunctionTemplate
9244 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009245
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009246 // C++ [over.over]p2:
9247 // If the name is a function template, template argument deduction is
9248 // done (14.8.2.2), and if the argument deduction succeeds, the
9249 // resulting template argument list is used to generate a single
9250 // function template specialization, which is added to the set of
9251 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009252 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009253 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009254 if (TemplateDeductionResult Result
9255 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9256 Specialization, Info)) {
9257 // FIXME: make a note of the failed deduction for diagnostics.
9258 (void)Result;
9259 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260 }
9261
John McCall0009fcc2011-04-26 20:42:42 +00009262 assert(Specialization && "no specialization and no error?");
9263
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009264 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009265 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009266 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009267 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9268 << ovl->getName();
9269 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009270 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009271 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009272 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009273
John McCall0009fcc2011-04-26 20:42:42 +00009274 Matched = Specialization;
9275 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009277
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009278 return Matched;
9279}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009280
Douglas Gregor1beec452011-03-12 01:48:56 +00009281
9282
9283
John McCall50a2c2c2011-10-11 23:14:30 +00009284// Resolve and fix an overloaded expression that can be resolved
9285// because it identifies a single function template specialization.
9286//
Douglas Gregor1beec452011-03-12 01:48:56 +00009287// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009288//
9289// Return true if it was logically possible to so resolve the
9290// expression, regardless of whether or not it succeeded. Always
9291// returns true if 'complain' is set.
9292bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9293 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9294 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009295 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009296 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009297 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009298
John McCall50a2c2c2011-10-11 23:14:30 +00009299 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009300
John McCall0009fcc2011-04-26 20:42:42 +00009301 DeclAccessPair found;
9302 ExprResult SingleFunctionExpression;
9303 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9304 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009305 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009306 SrcExpr = ExprError();
9307 return true;
9308 }
John McCall0009fcc2011-04-26 20:42:42 +00009309
9310 // It is only correct to resolve to an instance method if we're
9311 // resolving a form that's permitted to be a pointer to member.
9312 // Otherwise we'll end up making a bound member expression, which
9313 // is illegal in all the contexts we resolve like this.
9314 if (!ovl.HasFormOfMemberPointer &&
9315 isa<CXXMethodDecl>(fn) &&
9316 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009317 if (!complain) return false;
9318
9319 Diag(ovl.Expression->getExprLoc(),
9320 diag::err_bound_member_function)
9321 << 0 << ovl.Expression->getSourceRange();
9322
9323 // TODO: I believe we only end up here if there's a mix of
9324 // static and non-static candidates (otherwise the expression
9325 // would have 'bound member' type, not 'overload' type).
9326 // Ideally we would note which candidate was chosen and why
9327 // the static candidates were rejected.
9328 SrcExpr = ExprError();
9329 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009330 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009331
John McCall0009fcc2011-04-26 20:42:42 +00009332 // Fix the expresion to refer to 'fn'.
9333 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009334 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009335
9336 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009337 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009338 SingleFunctionExpression =
9339 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009340 if (SingleFunctionExpression.isInvalid()) {
9341 SrcExpr = ExprError();
9342 return true;
9343 }
9344 }
John McCall0009fcc2011-04-26 20:42:42 +00009345 }
9346
9347 if (!SingleFunctionExpression.isUsable()) {
9348 if (complain) {
9349 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9350 << ovl.Expression->getName()
9351 << DestTypeForComplaining
9352 << OpRangeForComplaining
9353 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009354 NoteAllOverloadCandidates(SrcExpr.get());
9355
9356 SrcExpr = ExprError();
9357 return true;
9358 }
9359
9360 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009361 }
9362
John McCall50a2c2c2011-10-11 23:14:30 +00009363 SrcExpr = SingleFunctionExpression;
9364 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009365}
9366
Douglas Gregorcabea402009-09-22 15:41:20 +00009367/// \brief Add a single candidate to the overload set.
9368static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009369 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009370 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009371 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009372 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009373 bool PartialOverloading,
9374 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009375 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009376 if (isa<UsingShadowDecl>(Callee))
9377 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9378
Douglas Gregorcabea402009-09-22 15:41:20 +00009379 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009380 if (ExplicitTemplateArgs) {
9381 assert(!KnownValid && "Explicit template arguments?");
9382 return;
9383 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009384 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9385 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009386 return;
John McCalld14a8642009-11-21 08:51:07 +00009387 }
9388
9389 if (FunctionTemplateDecl *FuncTemplate
9390 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009391 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009392 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009393 return;
9394 }
9395
Richard Smith95ce4f62011-06-26 22:19:54 +00009396 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009397}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009398
Douglas Gregorcabea402009-09-22 15:41:20 +00009399/// \brief Add the overload candidates named by callee and/or found by argument
9400/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009401void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009402 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009403 OverloadCandidateSet &CandidateSet,
9404 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009405
9406#ifndef NDEBUG
9407 // Verify that ArgumentDependentLookup is consistent with the rules
9408 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009409 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009410 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9411 // and let Y be the lookup set produced by argument dependent
9412 // lookup (defined as follows). If X contains
9413 //
9414 // -- a declaration of a class member, or
9415 //
9416 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009417 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009418 //
9419 // -- a declaration that is neither a function or a function
9420 // template
9421 //
9422 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009423
John McCall57500772009-12-16 12:17:52 +00009424 if (ULE->requiresADL()) {
9425 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9426 E = ULE->decls_end(); I != E; ++I) {
9427 assert(!(*I)->getDeclContext()->isRecord());
9428 assert(isa<UsingShadowDecl>(*I) ||
9429 !(*I)->getDeclContext()->isFunctionOrMethod());
9430 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009431 }
9432 }
9433#endif
9434
John McCall57500772009-12-16 12:17:52 +00009435 // It would be nice to avoid this copy.
9436 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009437 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009438 if (ULE->hasExplicitTemplateArgs()) {
9439 ULE->copyTemplateArgumentsInto(TABuffer);
9440 ExplicitTemplateArgs = &TABuffer;
9441 }
9442
9443 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9444 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009445 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9446 CandidateSet, PartialOverloading,
9447 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009448
John McCall57500772009-12-16 12:17:52 +00009449 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009450 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009451 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009452 Args, ExplicitTemplateArgs,
9453 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009454 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009455}
John McCalld681c392009-12-16 08:11:27 +00009456
Richard Smith998a5912011-06-05 22:42:48 +00009457/// Attempt to recover from an ill-formed use of a non-dependent name in a
9458/// template, where the non-dependent name was declared after the template
9459/// was defined. This is common in code written for a compilers which do not
9460/// correctly implement two-stage name lookup.
9461///
9462/// Returns true if a viable candidate was found and a diagnostic was issued.
9463static bool
9464DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9465 const CXXScopeSpec &SS, LookupResult &R,
9466 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009467 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009468 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9469 return false;
9470
9471 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009472 if (DC->isTransparentContext())
9473 continue;
9474
Richard Smith998a5912011-06-05 22:42:48 +00009475 SemaRef.LookupQualifiedName(R, DC);
9476
9477 if (!R.empty()) {
9478 R.suppressDiagnostics();
9479
9480 if (isa<CXXRecordDecl>(DC)) {
9481 // Don't diagnose names we find in classes; we get much better
9482 // diagnostics for these from DiagnoseEmptyLookup.
9483 R.clear();
9484 return false;
9485 }
9486
9487 OverloadCandidateSet Candidates(FnLoc);
9488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9489 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009490 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009491 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009492
9493 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009494 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009495 // No viable functions. Don't bother the user with notes for functions
9496 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009497 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009498 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009499 }
Richard Smith998a5912011-06-05 22:42:48 +00009500
9501 // Find the namespaces where ADL would have looked, and suggest
9502 // declaring the function there instead.
9503 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9504 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009505 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009506 AssociatedNamespaces,
9507 AssociatedClasses);
9508 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009509 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009510 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009511 for (Sema::AssociatedNamespaceSet::iterator
9512 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009513 end = AssociatedNamespaces.end(); it != end; ++it) {
9514 if (!Std->Encloses(*it))
9515 SuggestedNamespaces.insert(*it);
9516 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009517 } else {
9518 // Lacking the 'std::' namespace, use all of the associated namespaces.
9519 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009520 }
9521
9522 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9523 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009524 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009525 SemaRef.Diag(Best->Function->getLocation(),
9526 diag::note_not_found_by_two_phase_lookup)
9527 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009528 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009529 SemaRef.Diag(Best->Function->getLocation(),
9530 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009531 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009532 } else {
9533 // FIXME: It would be useful to list the associated namespaces here,
9534 // but the diagnostics infrastructure doesn't provide a way to produce
9535 // a localized representation of a list of items.
9536 SemaRef.Diag(Best->Function->getLocation(),
9537 diag::note_not_found_by_two_phase_lookup)
9538 << R.getLookupName() << 2;
9539 }
9540
9541 // Try to recover by calling this function.
9542 return true;
9543 }
9544
9545 R.clear();
9546 }
9547
9548 return false;
9549}
9550
9551/// Attempt to recover from ill-formed use of a non-dependent operator in a
9552/// template, where the non-dependent operator was declared after the template
9553/// was defined.
9554///
9555/// Returns true if a viable candidate was found and a diagnostic was issued.
9556static bool
9557DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9558 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009559 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009560 DeclarationName OpName =
9561 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9562 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9563 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009564 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009565}
9566
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009567namespace {
9568// Callback to limit the allowed keywords and to only accept typo corrections
9569// that are keywords or whose decls refer to functions (or template functions)
9570// that accept the given number of arguments.
9571class RecoveryCallCCC : public CorrectionCandidateCallback {
9572 public:
9573 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9574 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009575 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009576 WantRemainingKeywords = false;
9577 }
9578
9579 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9580 if (!candidate.getCorrectionDecl())
9581 return candidate.isKeyword();
9582
9583 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9584 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9585 FunctionDecl *FD = 0;
9586 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9587 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9588 FD = FTD->getTemplatedDecl();
9589 if (!HasExplicitTemplateArgs && !FD) {
9590 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9591 // If the Decl is neither a function nor a template function,
9592 // determine if it is a pointer or reference to a function. If so,
9593 // check against the number of arguments expected for the pointee.
9594 QualType ValType = cast<ValueDecl>(ND)->getType();
9595 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9596 ValType = ValType->getPointeeType();
9597 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9598 if (FPT->getNumArgs() == NumArgs)
9599 return true;
9600 }
9601 }
9602 if (FD && FD->getNumParams() >= NumArgs &&
9603 FD->getMinRequiredArguments() <= NumArgs)
9604 return true;
9605 }
9606 return false;
9607 }
9608
9609 private:
9610 unsigned NumArgs;
9611 bool HasExplicitTemplateArgs;
9612};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009613
9614// Callback that effectively disabled typo correction
9615class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9616 public:
9617 NoTypoCorrectionCCC() {
9618 WantTypeSpecifiers = false;
9619 WantExpressionKeywords = false;
9620 WantCXXNamedCasts = false;
9621 WantRemainingKeywords = false;
9622 }
9623
9624 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9625 return false;
9626 }
9627};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009628}
9629
John McCalld681c392009-12-16 08:11:27 +00009630/// Attempts to recover from a call where no functions were found.
9631///
9632/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009633static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009634BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009635 UnresolvedLookupExpr *ULE,
9636 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009637 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009638 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009639 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009640
9641 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009642 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009643 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009644
John McCall57500772009-12-16 12:17:52 +00009645 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009646 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009647 if (ULE->hasExplicitTemplateArgs()) {
9648 ULE->copyTemplateArgumentsInto(TABuffer);
9649 ExplicitTemplateArgs = &TABuffer;
9650 }
9651
John McCalld681c392009-12-16 08:11:27 +00009652 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9653 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009654 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009655 NoTypoCorrectionCCC RejectAll;
9656 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9657 (CorrectionCandidateCallback*)&Validator :
9658 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009659 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009660 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009661 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009662 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009663 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009664 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009665
John McCall57500772009-12-16 12:17:52 +00009666 assert(!R.empty() && "lookup results empty despite recovery");
9667
9668 // Build an implicit member call if appropriate. Just drop the
9669 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009670 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009671 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009672 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9673 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009674 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009675 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009676 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009677 else
9678 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9679
9680 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009681 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009682
9683 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009684 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009685 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009686 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009687 MultiExprArg(Args.data(), Args.size()),
9688 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009689}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009690
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009691/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009692/// (which eventually refers to the declaration Func) and the call
9693/// arguments Args/NumArgs, attempt to resolve the function call down
9694/// to a specific function. If overload resolution succeeds, returns
9695/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009696/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009697/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009698ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009699Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009700 SourceLocation LParenLoc,
9701 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009702 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009703 Expr *ExecConfig,
9704 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009705#ifndef NDEBUG
9706 if (ULE->requiresADL()) {
9707 // To do ADL, we must have found an unqualified name.
9708 assert(!ULE->getQualifier() && "qualified name with ADL");
9709
9710 // We don't perform ADL for implicit declarations of builtins.
9711 // Verify that this was correctly set up.
9712 FunctionDecl *F;
9713 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9714 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9715 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009716 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009717
John McCall57500772009-12-16 12:17:52 +00009718 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009719 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009720 } else
9721 assert(!ULE->isStdAssociatedNamespace() &&
9722 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009723#endif
9724
John McCall4124c492011-10-17 18:40:02 +00009725 UnbridgedCastsSet UnbridgedCasts;
9726 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9727 return ExprError();
9728
John McCallbc077cf2010-02-08 23:07:23 +00009729 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009730
John McCall57500772009-12-16 12:17:52 +00009731 // Add the functions denoted by the callee to the set of candidate
9732 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009733 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9734 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009735
9736 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009737 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9738 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009739 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009740 // In Microsoft mode, if we are inside a template class member function then
9741 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009742 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009743 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009744 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009745 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009746 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9747 Context.DependentTy, VK_RValue,
9748 RParenLoc);
9749 CE->setTypeDependent(true);
9750 return Owned(CE);
9751 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009752 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9753 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009754 RParenLoc, /*EmptyLookup=*/true,
9755 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009756 }
John McCalld681c392009-12-16 08:11:27 +00009757
John McCall4124c492011-10-17 18:40:02 +00009758 UnbridgedCasts.restore();
9759
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009760 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009761 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009762 case OR_Success: {
9763 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009764 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009765 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009766 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009767 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009768 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9769 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009770 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009771
Richard Smith998a5912011-06-05 22:42:48 +00009772 case OR_No_Viable_Function: {
9773 // Try to recover by looking for viable functions which the user might
9774 // have meant to call.
9775 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009776 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9777 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009778 /*EmptyLookup=*/false,
9779 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009780 if (!Recovery.isInvalid())
9781 return Recovery;
9782
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009783 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009784 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009785 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009786 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9787 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009788 break;
Richard Smith998a5912011-06-05 22:42:48 +00009789 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009790
9791 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009792 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009793 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009794 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9795 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009796 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009797
9798 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009799 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009800 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009801 << Best->Function->isDeleted()
9802 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009803 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009804 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009805 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9806 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009807
9808 // We emitted an error for the unvailable/deleted function call but keep
9809 // the call in the AST.
9810 FunctionDecl *FDecl = Best->Function;
9811 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9812 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9813 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009814 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009815 }
9816
Douglas Gregorb412e172010-07-25 18:17:45 +00009817 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009818 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009819}
9820
John McCall4c4c1df2010-01-26 03:27:55 +00009821static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009822 return Functions.size() > 1 ||
9823 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9824}
9825
Douglas Gregor084d8552009-03-13 23:49:33 +00009826/// \brief Create a unary operation that may resolve to an overloaded
9827/// operator.
9828///
9829/// \param OpLoc The location of the operator itself (e.g., '*').
9830///
9831/// \param OpcIn The UnaryOperator::Opcode that describes this
9832/// operator.
9833///
James Dennett18348b62012-06-22 08:52:37 +00009834/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009835/// considered by overload resolution. The caller needs to build this
9836/// set based on the context using, e.g.,
9837/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9838/// set should not contain any member functions; those will be added
9839/// by CreateOverloadedUnaryOp().
9840///
James Dennett91738ff2012-06-22 10:32:46 +00009841/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009842ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009843Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9844 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009845 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009846 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009847
9848 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9849 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9850 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009851 // TODO: provide better source location info.
9852 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009853
John McCall4124c492011-10-17 18:40:02 +00009854 if (checkPlaceholderForOverload(*this, Input))
9855 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009856
Douglas Gregor084d8552009-03-13 23:49:33 +00009857 Expr *Args[2] = { Input, 0 };
9858 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009859
Douglas Gregor084d8552009-03-13 23:49:33 +00009860 // For post-increment and post-decrement, add the implicit '0' as
9861 // the second argument, so that we know this is a post-increment or
9862 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009863 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009864 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009865 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9866 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009867 NumArgs = 2;
9868 }
9869
9870 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009871 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009872 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009873 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009874 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009875 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009876 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009877
John McCall58cc69d2010-01-27 01:50:18 +00009878 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009879 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009880 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009881 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009882 /*ADL*/ true, IsOverloaded(Fns),
9883 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009884 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009885 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009886 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009887 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009888 OpLoc));
9889 }
9890
9891 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009892 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009893
9894 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009895 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9896 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009897
9898 // Add operator candidates that are member functions.
9899 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9900
John McCall4c4c1df2010-01-26 03:27:55 +00009901 // Add candidates from ADL.
9902 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009903 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009904 /*ExplicitTemplateArgs*/ 0,
9905 CandidateSet);
9906
Douglas Gregor084d8552009-03-13 23:49:33 +00009907 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009908 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009909
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009910 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9911
Douglas Gregor084d8552009-03-13 23:49:33 +00009912 // Perform overload resolution.
9913 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009914 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009915 case OR_Success: {
9916 // We found a built-in operator or an overloaded operator.
9917 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009918
Douglas Gregor084d8552009-03-13 23:49:33 +00009919 if (FnDecl) {
9920 // We matched an overloaded operator. Build a call to that
9921 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009922
Eli Friedmanfa0df832012-02-02 03:46:19 +00009923 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009924
Douglas Gregor084d8552009-03-13 23:49:33 +00009925 // Convert the arguments.
9926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009927 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009928
John Wiegley01296292011-04-08 18:41:53 +00009929 ExprResult InputRes =
9930 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9931 Best->FoundDecl, Method);
9932 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009933 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009934 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009935 } else {
9936 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009937 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009938 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009939 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009940 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009941 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009942 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009943 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009944 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009945 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009946 }
9947
John McCall4fa0d5f2010-05-06 18:15:07 +00009948 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9949
John McCall7decc9e2010-11-18 06:31:45 +00009950 // Determine the result type.
9951 QualType ResultTy = FnDecl->getResultType();
9952 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9953 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009954
Douglas Gregor084d8552009-03-13 23:49:33 +00009955 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009956 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009957 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009958 if (FnExpr.isInvalid())
9959 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009960
Eli Friedman030eee42009-11-18 03:58:17 +00009961 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009962 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009963 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009964 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009966 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009967 FnDecl))
9968 return ExprError();
9969
John McCallb268a282010-08-23 23:25:46 +00009970 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009971 } else {
9972 // We matched a built-in operator. Convert the arguments, then
9973 // break out so that we will build the appropriate built-in
9974 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009975 ExprResult InputRes =
9976 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9977 Best->Conversions[0], AA_Passing);
9978 if (InputRes.isInvalid())
9979 return ExprError();
9980 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009981 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009982 }
John Wiegley01296292011-04-08 18:41:53 +00009983 }
9984
9985 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009986 // This is an erroneous use of an operator which can be overloaded by
9987 // a non-member function. Check for non-member operators which were
9988 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009989 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9990 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009991 // FIXME: Recover by calling the found function.
9992 return ExprError();
9993
John Wiegley01296292011-04-08 18:41:53 +00009994 // No viable function; fall through to handling this as a
9995 // built-in operator, which will produce an error message for us.
9996 break;
9997
9998 case OR_Ambiguous:
9999 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10000 << UnaryOperator::getOpcodeStr(Opc)
10001 << Input->getType()
10002 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010003 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10004 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010005 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10006 return ExprError();
10007
10008 case OR_Deleted:
10009 Diag(OpLoc, diag::err_ovl_deleted_oper)
10010 << Best->Function->isDeleted()
10011 << UnaryOperator::getOpcodeStr(Opc)
10012 << getDeletedOrUnavailableSuffix(Best->Function)
10013 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010014 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10015 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010016 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010017 return ExprError();
10018 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010019
10020 // Either we found no viable overloaded operator or we matched a
10021 // built-in operator. In either case, fall through to trying to
10022 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010023 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010024}
10025
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010026/// \brief Create a binary operation that may resolve to an overloaded
10027/// operator.
10028///
10029/// \param OpLoc The location of the operator itself (e.g., '+').
10030///
10031/// \param OpcIn The BinaryOperator::Opcode that describes this
10032/// operator.
10033///
James Dennett18348b62012-06-22 08:52:37 +000010034/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010035/// considered by overload resolution. The caller needs to build this
10036/// set based on the context using, e.g.,
10037/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10038/// set should not contain any member functions; those will be added
10039/// by CreateOverloadedBinOp().
10040///
10041/// \param LHS Left-hand argument.
10042/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010043ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010044Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010045 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010046 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010047 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010048 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010049 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010050
10051 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10052 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10053 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10054
10055 // If either side is type-dependent, create an appropriate dependent
10056 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010057 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010058 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010059 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010060 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010061 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010062 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010063 Context.DependentTy,
10064 VK_RValue, OK_Ordinary,
10065 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010066
Douglas Gregor5287f092009-11-05 00:51:44 +000010067 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10068 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010069 VK_LValue,
10070 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010071 Context.DependentTy,
10072 Context.DependentTy,
10073 OpLoc));
10074 }
John McCall4c4c1df2010-01-26 03:27:55 +000010075
10076 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010077 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010078 // TODO: provide better source location info in DNLoc component.
10079 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010080 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010081 = UnresolvedLookupExpr::Create(Context, NamingClass,
10082 NestedNameSpecifierLoc(), OpNameInfo,
10083 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010084 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010085 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +000010086 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010087 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010088 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010089 OpLoc));
10090 }
10091
John McCall4124c492011-10-17 18:40:02 +000010092 // Always do placeholder-like conversions on the RHS.
10093 if (checkPlaceholderForOverload(*this, Args[1]))
10094 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010095
John McCall526ab472011-10-25 17:37:35 +000010096 // Do placeholder-like conversion on the LHS; note that we should
10097 // not get here with a PseudoObject LHS.
10098 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010099 if (checkPlaceholderForOverload(*this, Args[0]))
10100 return ExprError();
10101
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010102 // If this is the assignment operator, we only perform overload resolution
10103 // if the left-hand side is a class or enumeration type. This is actually
10104 // a hack. The standard requires that we do overload resolution between the
10105 // various built-in candidates, but as DR507 points out, this can lead to
10106 // problems. So we do it this way, which pretty much follows what GCC does.
10107 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010108 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010109 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010110
John McCalle26a8722010-12-04 08:14:53 +000010111 // If this is the .* operator, which is not overloadable, just
10112 // create a built-in binary operator.
10113 if (Opc == BO_PtrMemD)
10114 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10115
Douglas Gregor084d8552009-03-13 23:49:33 +000010116 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010117 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010118
10119 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010120 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010121
10122 // Add operator candidates that are member functions.
10123 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10124
John McCall4c4c1df2010-01-26 03:27:55 +000010125 // Add candidates from ADL.
10126 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010127 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010128 /*ExplicitTemplateArgs*/ 0,
10129 CandidateSet);
10130
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010131 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010132 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010133
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010134 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10135
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010136 // Perform overload resolution.
10137 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010138 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010139 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010140 // We found a built-in operator or an overloaded operator.
10141 FunctionDecl *FnDecl = Best->Function;
10142
10143 if (FnDecl) {
10144 // We matched an overloaded operator. Build a call to that
10145 // operator.
10146
Eli Friedmanfa0df832012-02-02 03:46:19 +000010147 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010148
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010149 // Convert the arguments.
10150 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010151 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010152 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010153
Chandler Carruth8e543b32010-12-12 08:17:55 +000010154 ExprResult Arg1 =
10155 PerformCopyInitialization(
10156 InitializedEntity::InitializeParameter(Context,
10157 FnDecl->getParamDecl(0)),
10158 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010159 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010160 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010161
John Wiegley01296292011-04-08 18:41:53 +000010162 ExprResult Arg0 =
10163 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10164 Best->FoundDecl, Method);
10165 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010166 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010167 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010168 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010169 } else {
10170 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010171 ExprResult Arg0 = PerformCopyInitialization(
10172 InitializedEntity::InitializeParameter(Context,
10173 FnDecl->getParamDecl(0)),
10174 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010175 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010176 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010177
Chandler Carruth8e543b32010-12-12 08:17:55 +000010178 ExprResult Arg1 =
10179 PerformCopyInitialization(
10180 InitializedEntity::InitializeParameter(Context,
10181 FnDecl->getParamDecl(1)),
10182 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010183 if (Arg1.isInvalid())
10184 return ExprError();
10185 Args[0] = LHS = Arg0.takeAs<Expr>();
10186 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010187 }
10188
John McCall4fa0d5f2010-05-06 18:15:07 +000010189 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10190
John McCall7decc9e2010-11-18 06:31:45 +000010191 // Determine the result type.
10192 QualType ResultTy = FnDecl->getResultType();
10193 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10194 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010195
10196 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010197 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10198 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010199 if (FnExpr.isInvalid())
10200 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010201
John McCallb268a282010-08-23 23:25:46 +000010202 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010203 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010204 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010205
10206 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010207 FnDecl))
10208 return ExprError();
10209
John McCallb268a282010-08-23 23:25:46 +000010210 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010211 } else {
10212 // We matched a built-in operator. Convert the arguments, then
10213 // break out so that we will build the appropriate built-in
10214 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010215 ExprResult ArgsRes0 =
10216 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10217 Best->Conversions[0], AA_Passing);
10218 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010219 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010220 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010221
John Wiegley01296292011-04-08 18:41:53 +000010222 ExprResult ArgsRes1 =
10223 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10224 Best->Conversions[1], AA_Passing);
10225 if (ArgsRes1.isInvalid())
10226 return ExprError();
10227 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010228 break;
10229 }
10230 }
10231
Douglas Gregor66950a32009-09-30 21:46:01 +000010232 case OR_No_Viable_Function: {
10233 // C++ [over.match.oper]p9:
10234 // If the operator is the operator , [...] and there are no
10235 // viable functions, then the operator is assumed to be the
10236 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010237 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010238 break;
10239
Chandler Carruth8e543b32010-12-12 08:17:55 +000010240 // For class as left operand for assignment or compound assigment
10241 // operator do not fall through to handling in built-in, but report that
10242 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010243 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010244 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010245 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010246 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10247 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010248 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010249 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010250 // This is an erroneous use of an operator which can be overloaded by
10251 // a non-member function. Check for non-member operators which were
10252 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010253 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010254 // FIXME: Recover by calling the found function.
10255 return ExprError();
10256
Douglas Gregor66950a32009-09-30 21:46:01 +000010257 // No viable function; try to create a built-in operation, which will
10258 // produce an error. Then, show the non-viable candidates.
10259 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010261 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010262 "C++ binary operator overloading is missing candidates!");
10263 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010265 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010266 return move(Result);
10267 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010268
10269 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010270 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010271 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010272 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010273 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010274 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010275 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010276 return ExprError();
10277
10278 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010279 if (isImplicitlyDeleted(Best->Function)) {
10280 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10281 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10282 << getSpecialMember(Method)
10283 << BinaryOperator::getOpcodeStr(Opc)
10284 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010285
10286 if (getSpecialMember(Method) != CXXInvalid) {
10287 // The user probably meant to call this special member. Just
10288 // explain why it's deleted.
10289 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010290 return ExprError();
10291 }
10292 } else {
10293 Diag(OpLoc, diag::err_ovl_deleted_oper)
10294 << Best->Function->isDeleted()
10295 << BinaryOperator::getOpcodeStr(Opc)
10296 << getDeletedOrUnavailableSuffix(Best->Function)
10297 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10298 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010299 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010300 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010301 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010302 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010303
Douglas Gregor66950a32009-09-30 21:46:01 +000010304 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010305 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010306}
10307
John McCalldadc5752010-08-24 06:29:42 +000010308ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010309Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10310 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010311 Expr *Base, Expr *Idx) {
10312 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010313 DeclarationName OpName =
10314 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10315
10316 // If either side is type-dependent, create an appropriate dependent
10317 // expression.
10318 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10319
John McCall58cc69d2010-01-27 01:50:18 +000010320 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010321 // CHECKME: no 'operator' keyword?
10322 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10323 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010324 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010325 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010326 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010327 /*ADL*/ true, /*Overloaded*/ false,
10328 UnresolvedSetIterator(),
10329 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010330 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010331
Sebastian Redladba46e2009-10-29 20:17:01 +000010332 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10333 Args, 2,
10334 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010335 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010336 RLoc));
10337 }
10338
John McCall4124c492011-10-17 18:40:02 +000010339 // Handle placeholders on both operands.
10340 if (checkPlaceholderForOverload(*this, Args[0]))
10341 return ExprError();
10342 if (checkPlaceholderForOverload(*this, Args[1]))
10343 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010344
Sebastian Redladba46e2009-10-29 20:17:01 +000010345 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010346 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010347
10348 // Subscript can only be overloaded as a member function.
10349
10350 // Add operator candidates that are member functions.
10351 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10352
10353 // Add builtin operator candidates.
10354 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10355
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010356 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10357
Sebastian Redladba46e2009-10-29 20:17:01 +000010358 // Perform overload resolution.
10359 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010360 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010361 case OR_Success: {
10362 // We found a built-in operator or an overloaded operator.
10363 FunctionDecl *FnDecl = Best->Function;
10364
10365 if (FnDecl) {
10366 // We matched an overloaded operator. Build a call to that
10367 // operator.
10368
Eli Friedmanfa0df832012-02-02 03:46:19 +000010369 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010370
John McCalla0296f72010-03-19 07:35:19 +000010371 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010372 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010373
Sebastian Redladba46e2009-10-29 20:17:01 +000010374 // Convert the arguments.
10375 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010376 ExprResult Arg0 =
10377 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10378 Best->FoundDecl, Method);
10379 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010380 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010381 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010382
Anders Carlssona68e51e2010-01-29 18:37:50 +000010383 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010384 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010385 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010386 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010387 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010388 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010389 Owned(Args[1]));
10390 if (InputInit.isInvalid())
10391 return ExprError();
10392
10393 Args[1] = InputInit.takeAs<Expr>();
10394
Sebastian Redladba46e2009-10-29 20:17:01 +000010395 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010396 QualType ResultTy = FnDecl->getResultType();
10397 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10398 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010399
10400 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010401 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10402 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010403 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10404 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010405 OpLocInfo.getLoc(),
10406 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010407 if (FnExpr.isInvalid())
10408 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010409
John McCallb268a282010-08-23 23:25:46 +000010410 CXXOperatorCallExpr *TheCall =
10411 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010412 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010413 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010414
John McCallb268a282010-08-23 23:25:46 +000010415 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010416 FnDecl))
10417 return ExprError();
10418
John McCallb268a282010-08-23 23:25:46 +000010419 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010420 } else {
10421 // We matched a built-in operator. Convert the arguments, then
10422 // break out so that we will build the appropriate built-in
10423 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010424 ExprResult ArgsRes0 =
10425 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10426 Best->Conversions[0], AA_Passing);
10427 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010428 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010429 Args[0] = ArgsRes0.take();
10430
10431 ExprResult ArgsRes1 =
10432 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10433 Best->Conversions[1], AA_Passing);
10434 if (ArgsRes1.isInvalid())
10435 return ExprError();
10436 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010437
10438 break;
10439 }
10440 }
10441
10442 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010443 if (CandidateSet.empty())
10444 Diag(LLoc, diag::err_ovl_no_oper)
10445 << Args[0]->getType() << /*subscript*/ 0
10446 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10447 else
10448 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10449 << Args[0]->getType()
10450 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010452 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010453 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010454 }
10455
10456 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010457 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010458 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010459 << Args[0]->getType() << Args[1]->getType()
10460 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010461 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010462 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010463 return ExprError();
10464
10465 case OR_Deleted:
10466 Diag(LLoc, diag::err_ovl_deleted_oper)
10467 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010468 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010469 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010470 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010471 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010472 return ExprError();
10473 }
10474
10475 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010476 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010477}
10478
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010479/// BuildCallToMemberFunction - Build a call to a member
10480/// function. MemExpr is the expression that refers to the member
10481/// function (and includes the object parameter), Args/NumArgs are the
10482/// arguments to the function call (not including the object
10483/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010484/// expression refers to a non-static member function or an overloaded
10485/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010486ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010487Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10488 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010489 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010490 assert(MemExprE->getType() == Context.BoundMemberTy ||
10491 MemExprE->getType() == Context.OverloadTy);
10492
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010493 // Dig out the member expression. This holds both the object
10494 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010495 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010496
John McCall0009fcc2011-04-26 20:42:42 +000010497 // Determine whether this is a call to a pointer-to-member function.
10498 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10499 assert(op->getType() == Context.BoundMemberTy);
10500 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10501
10502 QualType fnType =
10503 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10504
10505 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10506 QualType resultType = proto->getCallResultType(Context);
10507 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10508
10509 // Check that the object type isn't more qualified than the
10510 // member function we're calling.
10511 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10512
10513 QualType objectType = op->getLHS()->getType();
10514 if (op->getOpcode() == BO_PtrMemI)
10515 objectType = objectType->castAs<PointerType>()->getPointeeType();
10516 Qualifiers objectQuals = objectType.getQualifiers();
10517
10518 Qualifiers difference = objectQuals - funcQuals;
10519 difference.removeObjCGCAttr();
10520 difference.removeAddressSpace();
10521 if (difference) {
10522 std::string qualsString = difference.getAsString();
10523 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10524 << fnType.getUnqualifiedType()
10525 << qualsString
10526 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10527 }
10528
10529 CXXMemberCallExpr *call
10530 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10531 resultType, valueKind, RParenLoc);
10532
10533 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010534 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010535 call, 0))
10536 return ExprError();
10537
10538 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10539 return ExprError();
10540
10541 return MaybeBindToTemporary(call);
10542 }
10543
John McCall4124c492011-10-17 18:40:02 +000010544 UnbridgedCastsSet UnbridgedCasts;
10545 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10546 return ExprError();
10547
John McCall10eae182009-11-30 22:42:35 +000010548 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010549 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010550 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010551 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010552 if (isa<MemberExpr>(NakedMemExpr)) {
10553 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010554 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010555 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010556 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010557 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010558 } else {
10559 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010560 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010561
John McCall6e9f8f62009-12-03 04:06:58 +000010562 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010563 Expr::Classification ObjectClassification
10564 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10565 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010566
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010567 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010568 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010569
John McCall2d74de92009-12-01 22:10:20 +000010570 // FIXME: avoid copy.
10571 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10572 if (UnresExpr->hasExplicitTemplateArgs()) {
10573 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10574 TemplateArgs = &TemplateArgsBuffer;
10575 }
10576
John McCall10eae182009-11-30 22:42:35 +000010577 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10578 E = UnresExpr->decls_end(); I != E; ++I) {
10579
John McCall6e9f8f62009-12-03 04:06:58 +000010580 NamedDecl *Func = *I;
10581 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10582 if (isa<UsingShadowDecl>(Func))
10583 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10584
Douglas Gregor02824322011-01-26 19:30:28 +000010585
Francois Pichet64225792011-01-18 05:04:39 +000010586 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010587 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010588 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10589 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010590 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010591 // If explicit template arguments were provided, we can't call a
10592 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010593 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010594 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010595
John McCalla0296f72010-03-19 07:35:19 +000010596 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010597 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010598 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010599 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010600 } else {
John McCall10eae182009-11-30 22:42:35 +000010601 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010602 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010603 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010604 llvm::makeArrayRef(Args, NumArgs),
10605 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010606 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010607 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010608 }
Mike Stump11289f42009-09-09 15:08:12 +000010609
John McCall10eae182009-11-30 22:42:35 +000010610 DeclarationName DeclName = UnresExpr->getMemberName();
10611
John McCall4124c492011-10-17 18:40:02 +000010612 UnbridgedCasts.restore();
10613
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010614 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010615 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010616 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010617 case OR_Success:
10618 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010619 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010620 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010621 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010622 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010623 break;
10624
10625 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010626 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010627 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010628 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010629 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10630 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010631 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010632 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010633
10634 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010635 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010636 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010637 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10638 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010639 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010640 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010641
10642 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010643 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010644 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010645 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010646 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010647 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010648 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10649 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010650 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010651 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010652 }
10653
John McCall16df1e52010-03-30 21:47:33 +000010654 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010655
John McCall2d74de92009-12-01 22:10:20 +000010656 // If overload resolution picked a static member, build a
10657 // non-member call based on that function.
10658 if (Method->isStatic()) {
10659 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10660 Args, NumArgs, RParenLoc);
10661 }
10662
John McCall10eae182009-11-30 22:42:35 +000010663 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010664 }
10665
John McCall7decc9e2010-11-18 06:31:45 +000010666 QualType ResultType = Method->getResultType();
10667 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10668 ResultType = ResultType.getNonLValueExprType(Context);
10669
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010670 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010671 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010672 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010673 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010674
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010675 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010676 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010677 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010678 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010679
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010680 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010681 // We only need to do this if there was actually an overload; otherwise
10682 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010683 if (!Method->isStatic()) {
10684 ExprResult ObjectArg =
10685 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10686 FoundDecl, Method);
10687 if (ObjectArg.isInvalid())
10688 return ExprError();
10689 MemExpr->setBase(ObjectArg.take());
10690 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010691
10692 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010693 const FunctionProtoType *Proto =
10694 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010695 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010696 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010697 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010698
Eli Friedmanff4b4072012-02-18 04:48:30 +000010699 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10700
Rafael Espindolac3688172012-06-21 23:44:21 +000010701 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010702 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010703
Anders Carlsson47061ee2011-05-06 14:25:31 +000010704 if ((isa<CXXConstructorDecl>(CurContext) ||
10705 isa<CXXDestructorDecl>(CurContext)) &&
10706 TheCall->getMethodDecl()->isPure()) {
10707 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10708
Chandler Carruth59259262011-06-27 08:31:58 +000010709 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010710 Diag(MemExpr->getLocStart(),
10711 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10712 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10713 << MD->getParent()->getDeclName();
10714
10715 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010716 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010717 }
John McCallb268a282010-08-23 23:25:46 +000010718 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010719}
10720
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010721/// BuildCallToObjectOfClassType - Build a call to an object of class
10722/// type (C++ [over.call.object]), which can end up invoking an
10723/// overloaded function call operator (@c operator()) or performing a
10724/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010725ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010726Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010727 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010728 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010729 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010730 if (checkPlaceholderForOverload(*this, Obj))
10731 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010732 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010733
10734 UnbridgedCastsSet UnbridgedCasts;
10735 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10736 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010737
John Wiegley01296292011-04-08 18:41:53 +000010738 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10739 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010740
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010741 // C++ [over.call.object]p1:
10742 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010743 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010744 // candidate functions includes at least the function call
10745 // operators of T. The function call operators of T are obtained by
10746 // ordinary lookup of the name operator() in the context of
10747 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010748 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010749 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010750
John Wiegley01296292011-04-08 18:41:53 +000010751 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010752 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010753 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010754
John McCall27b18f82009-11-17 02:14:36 +000010755 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10756 LookupQualifiedName(R, Record->getDecl());
10757 R.suppressDiagnostics();
10758
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010759 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010760 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010761 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10762 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010763 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010765
Douglas Gregorab7897a2008-11-19 22:57:39 +000010766 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010767 // In addition, for each (non-explicit in C++0x) conversion function
10768 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010769 //
10770 // operator conversion-type-id () cv-qualifier;
10771 //
10772 // where cv-qualifier is the same cv-qualification as, or a
10773 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010774 // denotes the type "pointer to function of (P1,...,Pn) returning
10775 // R", or the type "reference to pointer to function of
10776 // (P1,...,Pn) returning R", or the type "reference to function
10777 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010778 // is also considered as a candidate function. Similarly,
10779 // surrogate call functions are added to the set of candidate
10780 // functions for each conversion function declared in an
10781 // accessible base class provided the function is not hidden
10782 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010783 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010784 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010785 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010786 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010787 NamedDecl *D = *I;
10788 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10789 if (isa<UsingShadowDecl>(D))
10790 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010791
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010792 // Skip over templated conversion functions; they aren't
10793 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010794 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010795 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010796
John McCall6e9f8f62009-12-03 04:06:58 +000010797 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010798 if (!Conv->isExplicit()) {
10799 // Strip the reference type (if any) and then the pointer type (if
10800 // any) to get down to what might be a function type.
10801 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10802 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10803 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010804
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010805 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10806 {
10807 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010808 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10809 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010810 }
10811 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010812 }
Mike Stump11289f42009-09-09 15:08:12 +000010813
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010814 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10815
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010816 // Perform overload resolution.
10817 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010818 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010819 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010820 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010821 // Overload resolution succeeded; we'll build the appropriate call
10822 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010823 break;
10824
10825 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010826 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010827 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010828 << Object.get()->getType() << /*call*/ 1
10829 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010830 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010831 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010832 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010833 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10835 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010836 break;
10837
10838 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010839 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010840 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010841 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010842 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10843 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010844 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010845
10846 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010847 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010848 diag::err_ovl_deleted_object_call)
10849 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010850 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010851 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010852 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010853 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10854 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010855 break;
Mike Stump11289f42009-09-09 15:08:12 +000010856 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010857
Douglas Gregorb412e172010-07-25 18:17:45 +000010858 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010859 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010860
John McCall4124c492011-10-17 18:40:02 +000010861 UnbridgedCasts.restore();
10862
Douglas Gregorab7897a2008-11-19 22:57:39 +000010863 if (Best->Function == 0) {
10864 // Since there is no function declaration, this is one of the
10865 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010866 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010867 = cast<CXXConversionDecl>(
10868 Best->Conversions[0].UserDefined.ConversionFunction);
10869
John Wiegley01296292011-04-08 18:41:53 +000010870 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010871 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010872
Douglas Gregorab7897a2008-11-19 22:57:39 +000010873 // We selected one of the surrogate functions that converts the
10874 // object parameter to a function pointer. Perform the conversion
10875 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010876
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010877 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010878 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010879 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10880 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010881 if (Call.isInvalid())
10882 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010883 // Record usage of conversion in an implicit cast.
10884 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10885 CK_UserDefinedConversion,
10886 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010887
Douglas Gregor668443e2011-01-20 00:18:04 +000010888 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010889 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010890 }
10891
Eli Friedmanfa0df832012-02-02 03:46:19 +000010892 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010893 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010894 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010895
Douglas Gregorab7897a2008-11-19 22:57:39 +000010896 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10897 // that calls this method, using Object for the implicit object
10898 // parameter and passing along the remaining arguments.
10899 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010900 const FunctionProtoType *Proto =
10901 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010902
10903 unsigned NumArgsInProto = Proto->getNumArgs();
10904 unsigned NumArgsToCheck = NumArgs;
10905
10906 // Build the full argument list for the method call (the
10907 // implicit object parameter is placed at the beginning of the
10908 // list).
10909 Expr **MethodArgs;
10910 if (NumArgs < NumArgsInProto) {
10911 NumArgsToCheck = NumArgsInProto;
10912 MethodArgs = new Expr*[NumArgsInProto + 1];
10913 } else {
10914 MethodArgs = new Expr*[NumArgs + 1];
10915 }
John Wiegley01296292011-04-08 18:41:53 +000010916 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010917 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10918 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010919
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010920 DeclarationNameInfo OpLocInfo(
10921 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10922 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010923 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010924 HadMultipleCandidates,
10925 OpLocInfo.getLoc(),
10926 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010927 if (NewFn.isInvalid())
10928 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010929
10930 // Once we've built TheCall, all of the expressions are properly
10931 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010932 QualType ResultTy = Method->getResultType();
10933 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10934 ResultTy = ResultTy.getNonLValueExprType(Context);
10935
John McCallb268a282010-08-23 23:25:46 +000010936 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010937 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010938 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010939 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010940 delete [] MethodArgs;
10941
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010942 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010943 Method))
10944 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010945
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010946 // We may have default arguments. If so, we need to allocate more
10947 // slots in the call for them.
10948 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010949 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010950 else if (NumArgs > NumArgsInProto)
10951 NumArgsToCheck = NumArgsInProto;
10952
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010953 bool IsError = false;
10954
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010955 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010956 ExprResult ObjRes =
10957 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10958 Best->FoundDecl, Method);
10959 if (ObjRes.isInvalid())
10960 IsError = true;
10961 else
10962 Object = move(ObjRes);
10963 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010964
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010965 // Check the argument types.
10966 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010967 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010968 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010969 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010970
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010971 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010972
John McCalldadc5752010-08-24 06:29:42 +000010973 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010974 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010975 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010976 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010977 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010978
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010979 IsError |= InputInit.isInvalid();
10980 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010981 } else {
John McCalldadc5752010-08-24 06:29:42 +000010982 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010983 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10984 if (DefArg.isInvalid()) {
10985 IsError = true;
10986 break;
10987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010988
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010989 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010990 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010991
10992 TheCall->setArg(i + 1, Arg);
10993 }
10994
10995 // If this is a variadic call, handle args passed through "...".
10996 if (Proto->isVariadic()) {
10997 // Promote the arguments (C99 6.5.2.2p7).
10998 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010999 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11000 IsError |= Arg.isInvalid();
11001 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011002 }
11003 }
11004
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011005 if (IsError) return true;
11006
Eli Friedmanff4b4072012-02-18 04:48:30 +000011007 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11008
Rafael Espindolac3688172012-06-21 23:44:21 +000011009 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011010 return true;
11011
John McCalle172be52010-08-24 06:09:16 +000011012 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011013}
11014
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011015/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011016/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011017/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011018ExprResult
John McCallb268a282010-08-23 23:25:46 +000011019Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011020 assert(Base->getType()->isRecordType() &&
11021 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011022
John McCall4124c492011-10-17 18:40:02 +000011023 if (checkPlaceholderForOverload(*this, Base))
11024 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011025
John McCallbc077cf2010-02-08 23:07:23 +000011026 SourceLocation Loc = Base->getExprLoc();
11027
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011028 // C++ [over.ref]p1:
11029 //
11030 // [...] An expression x->m is interpreted as (x.operator->())->m
11031 // for a class object x of type T if T::operator->() exists and if
11032 // the operator is selected as the best match function by the
11033 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011034 DeclarationName OpName =
11035 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011036 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011037 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011038
John McCallbc077cf2010-02-08 23:07:23 +000011039 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011040 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011041 return ExprError();
11042
John McCall27b18f82009-11-17 02:14:36 +000011043 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11044 LookupQualifiedName(R, BaseRecord->getDecl());
11045 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011046
11047 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011048 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011049 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11050 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011051 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011052
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011053 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11054
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011055 // Perform overload resolution.
11056 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011057 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011058 case OR_Success:
11059 // Overload resolution succeeded; we'll build the call below.
11060 break;
11061
11062 case OR_No_Viable_Function:
11063 if (CandidateSet.empty())
11064 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011065 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011066 else
11067 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011068 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011069 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011070 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011071
11072 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011073 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11074 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011075 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011076 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011077
11078 case OR_Deleted:
11079 Diag(OpLoc, diag::err_ovl_deleted_oper)
11080 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011081 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011082 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011083 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011084 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011085 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011086 }
11087
Eli Friedmanfa0df832012-02-02 03:46:19 +000011088 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011089 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011090 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011091
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011092 // Convert the object parameter.
11093 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011094 ExprResult BaseResult =
11095 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11096 Best->FoundDecl, Method);
11097 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011098 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011099 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011100
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011101 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011102 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011103 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011104 if (FnExpr.isInvalid())
11105 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011106
John McCall7decc9e2010-11-18 06:31:45 +000011107 QualType ResultTy = Method->getResultType();
11108 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11109 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011110 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011111 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000011112 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011113
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011114 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011115 Method))
11116 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011117
11118 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011119}
11120
Richard Smithbcc22fc2012-03-09 08:00:36 +000011121/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11122/// a literal operator described by the provided lookup results.
11123ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11124 DeclarationNameInfo &SuffixInfo,
11125 ArrayRef<Expr*> Args,
11126 SourceLocation LitEndLoc,
11127 TemplateArgumentListInfo *TemplateArgs) {
11128 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011129
Richard Smithbcc22fc2012-03-09 08:00:36 +000011130 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11131 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11132 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011133
Richard Smithbcc22fc2012-03-09 08:00:36 +000011134 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11135
Richard Smithbcc22fc2012-03-09 08:00:36 +000011136 // Perform overload resolution. This will usually be trivial, but might need
11137 // to perform substitutions for a literal operator template.
11138 OverloadCandidateSet::iterator Best;
11139 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11140 case OR_Success:
11141 case OR_Deleted:
11142 break;
11143
11144 case OR_No_Viable_Function:
11145 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11146 << R.getLookupName();
11147 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11148 return ExprError();
11149
11150 case OR_Ambiguous:
11151 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11152 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11153 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011154 }
11155
Richard Smithbcc22fc2012-03-09 08:00:36 +000011156 FunctionDecl *FD = Best->Function;
11157 MarkFunctionReferenced(UDSuffixLoc, FD);
11158 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011159
Richard Smithbcc22fc2012-03-09 08:00:36 +000011160 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11161 SuffixInfo.getLoc(),
11162 SuffixInfo.getInfo());
11163 if (Fn.isInvalid())
11164 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011165
11166 // Check the argument types. This should almost always be a no-op, except
11167 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011168 Expr *ConvArgs[2];
11169 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11170 ExprResult InputInit = PerformCopyInitialization(
11171 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11172 SourceLocation(), Args[ArgIdx]);
11173 if (InputInit.isInvalid())
11174 return true;
11175 ConvArgs[ArgIdx] = InputInit.take();
11176 }
11177
Richard Smithc67fdd42012-03-07 08:35:16 +000011178 QualType ResultTy = FD->getResultType();
11179 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11180 ResultTy = ResultTy.getNonLValueExprType(Context);
11181
Richard Smithc67fdd42012-03-07 08:35:16 +000011182 UserDefinedLiteral *UDL =
11183 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11184 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11185
11186 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11187 return ExprError();
11188
Rafael Espindolac3688172012-06-21 23:44:21 +000011189 if (CheckFunctionCall(FD, UDL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011190 return ExprError();
11191
11192 return MaybeBindToTemporary(UDL);
11193}
11194
Douglas Gregorcd695e52008-11-10 20:40:00 +000011195/// FixOverloadedFunctionReference - E is an expression that refers to
11196/// a C++ overloaded function (possibly with some parentheses and
11197/// perhaps a '&' around it). We have resolved the overloaded function
11198/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011199/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011200Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011201 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011202 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011203 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11204 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011205 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011206 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011207
Douglas Gregor51c538b2009-11-20 19:42:02 +000011208 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011209 }
11210
Douglas Gregor51c538b2009-11-20 19:42:02 +000011211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011212 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11213 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011214 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011215 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011216 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011217 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011218 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011219 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011220
11221 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011222 ICE->getCastKind(),
11223 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011224 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011225 }
11226
Douglas Gregor51c538b2009-11-20 19:42:02 +000011227 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011228 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011229 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011230 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11231 if (Method->isStatic()) {
11232 // Do nothing: static member functions aren't any different
11233 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011234 } else {
John McCalle66edc12009-11-24 19:00:30 +000011235 // Fix the sub expression, which really has to be an
11236 // UnresolvedLookupExpr holding an overloaded member function
11237 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011238 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11239 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011240 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011241 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011242
John McCalld14a8642009-11-21 08:51:07 +000011243 assert(isa<DeclRefExpr>(SubExpr)
11244 && "fixed to something other than a decl ref");
11245 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11246 && "fixed to a member ref with no nested name qualifier");
11247
11248 // We have taken the address of a pointer to member
11249 // function. Perform the computation here so that we get the
11250 // appropriate pointer to member type.
11251 QualType ClassType
11252 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11253 QualType MemPtrType
11254 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11255
John McCall7decc9e2010-11-18 06:31:45 +000011256 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11257 VK_RValue, OK_Ordinary,
11258 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011259 }
11260 }
John McCall16df1e52010-03-30 21:47:33 +000011261 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11262 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011263 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011264 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011265
John McCalle3027922010-08-25 11:45:40 +000011266 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011267 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011268 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011269 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011270 }
John McCalld14a8642009-11-21 08:51:07 +000011271
11272 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011273 // FIXME: avoid copy.
11274 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011275 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011276 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11277 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011278 }
11279
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011280 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11281 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011282 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011283 Fn,
John McCall113bee02012-03-10 09:33:50 +000011284 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011285 ULE->getNameLoc(),
11286 Fn->getType(),
11287 VK_LValue,
11288 Found.getDecl(),
11289 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011290 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011291 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11292 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011293 }
11294
John McCall10eae182009-11-30 22:42:35 +000011295 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011296 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011297 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11298 if (MemExpr->hasExplicitTemplateArgs()) {
11299 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11300 TemplateArgs = &TemplateArgsBuffer;
11301 }
John McCall6b51f282009-11-23 01:53:49 +000011302
John McCall2d74de92009-12-01 22:10:20 +000011303 Expr *Base;
11304
John McCall7decc9e2010-11-18 06:31:45 +000011305 // If we're filling in a static method where we used to have an
11306 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011307 if (MemExpr->isImplicitAccess()) {
11308 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011309 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11310 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011311 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011312 Fn,
John McCall113bee02012-03-10 09:33:50 +000011313 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011314 MemExpr->getMemberLoc(),
11315 Fn->getType(),
11316 VK_LValue,
11317 Found.getDecl(),
11318 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011319 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011320 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11321 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011322 } else {
11323 SourceLocation Loc = MemExpr->getMemberLoc();
11324 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011325 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011326 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011327 Base = new (Context) CXXThisExpr(Loc,
11328 MemExpr->getBaseType(),
11329 /*isImplicit=*/true);
11330 }
John McCall2d74de92009-12-01 22:10:20 +000011331 } else
John McCallc3007a22010-10-26 07:05:15 +000011332 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011333
John McCall4adb38c2011-04-27 00:36:17 +000011334 ExprValueKind valueKind;
11335 QualType type;
11336 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11337 valueKind = VK_LValue;
11338 type = Fn->getType();
11339 } else {
11340 valueKind = VK_RValue;
11341 type = Context.BoundMemberTy;
11342 }
11343
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011344 MemberExpr *ME = MemberExpr::Create(Context, Base,
11345 MemExpr->isArrow(),
11346 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011347 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011348 Fn,
11349 Found,
11350 MemExpr->getMemberNameInfo(),
11351 TemplateArgs,
11352 type, valueKind, OK_Ordinary);
11353 ME->setHadMultipleCandidates(true);
11354 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011356
John McCallc3007a22010-10-26 07:05:15 +000011357 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011358}
11359
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011360ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011361 DeclAccessPair Found,
11362 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011363 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011364}
11365
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011366} // end namespace clang