blob: 6e62af5bfe40d8ceaa8e3d246eab652d66fadbff [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;
400 } else if (FromWidth < ToWidth) {
401 // Negative -> unsigned is narrowing. Otherwise, more bits is never
402 // narrowing.
403 if (InitializerValue.isSigned() && InitializerValue.isNegative())
404 return NK_Constant_Narrowing;
405 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000406 ConstantValue = APValue(InitializerValue);
407
408 // 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 Smith5614ca72012-03-23 23:55:39 +0000419 if (ConvertedValue != InitializerValue) {
420 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000421 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000422 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000423 }
424 }
425 return NK_Not_Narrowing;
426 }
427
428 default:
429 // Other kinds of conversions are not narrowings.
430 return NK_Not_Narrowing;
431 }
432}
433
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434/// DebugPrint - Print this standard conversion sequence to standard
435/// error. Useful for debugging overloading issues.
436void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438 bool PrintedSomething = false;
439 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 PrintedSomething = true;
442 }
443
444 if (Second != ICK_Identity) {
445 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449
450 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (Third != ICK_Identity) {
461 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 }
471}
472
473/// DebugPrint - Print this user-defined conversion sequence to standard
474/// error. Useful for debugging overloading issues.
475void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (Before.First || Before.Second || Before.Third) {
478 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000481 if (ConversionFunction)
482 OS << '\'' << *ConversionFunction << '\'';
483 else
484 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 After.DebugPrint();
488 }
489}
490
491/// DebugPrint - Print this implicit conversion sequence to standard
492/// error. Useful for debugging overloading issues.
493void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 switch (ConversionKind) {
496 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 Standard.DebugPrint();
499 break;
500 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 UserDefined.DebugPrint();
503 break;
504 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
John McCall0d1da222010-01-12 00:44:57 +0000507 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000509 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 break;
513 }
514
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516}
517
John McCall0d1da222010-01-12 00:44:57 +0000518void AmbiguousConversionSequence::construct() {
519 new (&conversions()) ConversionSet();
520}
521
522void AmbiguousConversionSequence::destruct() {
523 conversions().~ConversionSet();
524}
525
526void
527AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
528 FromTypePtr = O.FromTypePtr;
529 ToTypePtr = O.ToTypePtr;
530 new (&conversions()) ConversionSet(O.conversions());
531}
532
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533namespace {
534 // Structure used by OverloadCandidate::DeductionFailureInfo to store
535 // template parameter and template argument information.
536 struct DFIParamWithArguments {
537 TemplateParameter Param;
538 TemplateArgument FirstArg;
539 TemplateArgument SecondArg;
540 };
541}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000543/// \brief Convert from Sema's representation of template deduction information
544/// to the form used in overload-candidate information.
545OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000546static MakeDeductionFailureInfo(ASTContext &Context,
547 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000548 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 OverloadCandidate::DeductionFailureInfo Result;
550 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000551 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 Result.Data = 0;
553 switch (TDK) {
554 case Sema::TDK_Success:
555 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000556 case Sema::TDK_TooManyArguments:
557 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000561 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562 Result.Data = Info.Param.getOpaqueValue();
563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000566 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000567 // FIXME: Should allocate from normal heap so that we can free this later.
568 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569 Saved->Param = Info.Param;
570 Saved->FirstArg = Info.FirstArg;
571 Saved->SecondArg = Info.SecondArg;
572 Result.Data = Saved;
573 break;
574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000577 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000578 if (Info.hasSFINAEDiagnostic()) {
579 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
580 SourceLocation(), PartialDiagnostic::NullDiagnostic());
581 Info.takeSFINAEDiagnostic(*Diag);
582 Result.HasDiagnostic = true;
583 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 return Result;
592}
John McCall0d1da222010-01-12 00:44:57 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594void OverloadCandidate::DeductionFailureInfo::Destroy() {
595 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
596 case Sema::TDK_Success:
597 case Sema::TDK_InstantiationDepth:
598 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000601 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000605 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000606 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 Data = 0;
608 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000609
610 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000611 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000612 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000613 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
614 Diag->~PartialDiagnosticAt();
615 HasDiagnostic = false;
616 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor461761d2010-05-08 18:20:53 +0000619 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000621 case Sema::TDK_FailedOverloadResolution:
622 break;
623 }
624}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Richard Smith9ca64612012-05-07 09:03:25 +0000626PartialDiagnosticAt *
627OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
628 if (HasDiagnostic)
629 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
630 return 0;
631}
632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000634OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
635 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
636 case Sema::TDK_Success:
637 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000638 case Sema::TDK_TooManyArguments:
639 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000644 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646
647 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000648 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 case Sema::TDK_FailedOverloadResolution:
654 break;
655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 return TemplateParameter();
658}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregord09efd42010-05-08 20:07:26 +0000660TemplateArgumentList *
661OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663 case Sema::TDK_Success:
664 case Sema::TDK_InstantiationDepth:
665 case Sema::TDK_TooManyArguments:
666 case Sema::TDK_TooFewArguments:
667 case Sema::TDK_Incomplete:
668 case Sema::TDK_InvalidExplicitArguments:
669 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000670 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000671 return 0;
672
673 case Sema::TDK_SubstitutionFailure:
674 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Douglas Gregord09efd42010-05-08 20:07:26 +0000676 // Unhandled
677 case Sema::TDK_NonDeducedMismatch:
678 case Sema::TDK_FailedOverloadResolution:
679 break;
680 }
681
682 return 0;
683}
684
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
687 case Sema::TDK_Success:
688 case Sema::TDK_InstantiationDepth:
689 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000690 case Sema::TDK_TooManyArguments:
691 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000692 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000693 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 return 0;
695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699
Douglas Gregor461761d2010-05-08 18:20:53 +0000700 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 case Sema::TDK_FailedOverloadResolution:
703 break;
704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708
709const TemplateArgument *
710OverloadCandidate::DeductionFailureInfo::getSecondArg() {
711 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
712 case Sema::TDK_Success:
713 case Sema::TDK_InstantiationDepth:
714 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000715 case Sema::TDK_TooManyArguments:
716 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000717 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000718 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 return 0;
720
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000722 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
724
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 case Sema::TDK_FailedOverloadResolution:
728 break;
729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 return 0;
732}
733
734void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000735 for (iterator i = begin(), e = end(); i != e; ++i)
736 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
737 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000738 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000739 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 Functions.clear();
741}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742
John McCall4124c492011-10-17 18:40:02 +0000743namespace {
744 class UnbridgedCastsSet {
745 struct Entry {
746 Expr **Addr;
747 Expr *Saved;
748 };
749 SmallVector<Entry, 2> Entries;
750
751 public:
752 void save(Sema &S, Expr *&E) {
753 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
754 Entry entry = { &E, E };
755 Entries.push_back(entry);
756 E = S.stripARCUnbridgedCast(E);
757 }
758
759 void restore() {
760 for (SmallVectorImpl<Entry>::iterator
761 i = Entries.begin(), e = Entries.end(); i != e; ++i)
762 *i->Addr = i->Saved;
763 }
764 };
765}
766
767/// checkPlaceholderForOverload - Do any interesting placeholder-like
768/// preprocessing on the given expression.
769///
770/// \param unbridgedCasts a collection to which to add unbridged casts;
771/// without this, they will be immediately diagnosed as errors
772///
773/// Return true on unrecoverable error.
774static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
775 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000776 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
777 // We can't handle overloaded expressions here because overload
778 // resolution might reasonably tweak them.
779 if (placeholder->getKind() == BuiltinType::Overload) return false;
780
781 // If the context potentially accepts unbridged ARC casts, strip
782 // the unbridged cast and add it to the collection for later restoration.
783 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
784 unbridgedCasts) {
785 unbridgedCasts->save(S, E);
786 return false;
787 }
788
789 // Go ahead and check everything else.
790 ExprResult result = S.CheckPlaceholderExpr(E);
791 if (result.isInvalid())
792 return true;
793
794 E = result.take();
795 return false;
796 }
797
798 // Nothing to do.
799 return false;
800}
801
802/// checkArgPlaceholdersForOverload - Check a set of call operands for
803/// placeholders.
804static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
805 unsigned numArgs,
806 UnbridgedCastsSet &unbridged) {
807 for (unsigned i = 0; i != numArgs; ++i)
808 if (checkPlaceholderForOverload(S, args[i], &unbridged))
809 return true;
810
811 return false;
812}
813
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000814// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000815// overload of the declarations in Old. This routine returns false if
816// New and Old cannot be overloaded, e.g., if New has the same
817// signature as some function in Old (C++ 1.3.10) or if the Old
818// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000819// it does return false, MatchedDecl will point to the decl that New
820// cannot be overloaded with. This decl may be a UsingShadowDecl on
821// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000822//
823// Example: Given the following input:
824//
825// void f(int, float); // #1
826// void f(int, int); // #2
827// int f(int, int); // #3
828//
829// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000830// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831//
John McCall3d988d92009-12-02 08:47:38 +0000832// When we process #2, Old contains only the FunctionDecl for #1. By
833// comparing the parameter types, we see that #1 and #2 are overloaded
834// (since they have different signatures), so this routine returns
835// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000836//
John McCall3d988d92009-12-02 08:47:38 +0000837// When we process #3, Old is an overload set containing #1 and #2. We
838// compare the signatures of #3 to #1 (they're overloaded, so we do
839// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
840// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841// signature), IsOverload returns false and MatchedDecl will be set to
842// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000843//
844// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
845// into a class by a using declaration. The rules for whether to hide
846// shadow declarations ignore some properties which otherwise figure
847// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000848Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000849Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
850 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000851 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000852 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000853 NamedDecl *OldD = *I;
854
855 bool OldIsUsingDecl = false;
856 if (isa<UsingShadowDecl>(OldD)) {
857 OldIsUsingDecl = true;
858
859 // We can always introduce two using declarations into the same
860 // context, even if they have identical signatures.
861 if (NewIsUsingDecl) continue;
862
863 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
864 }
865
866 // If either declaration was introduced by a using declaration,
867 // we'll need to use slightly different rules for matching.
868 // Essentially, these rules are the normal rules, except that
869 // function templates hide function templates with different
870 // return types or template parameter lists.
871 bool UseMemberUsingDeclRules =
872 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
873
John McCall3d988d92009-12-02 08:47:38 +0000874 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000875 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
876 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
877 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
878 continue;
879 }
880
John McCalldaa3d6b2009-12-09 03:35:25 +0000881 Match = *I;
882 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000883 }
John McCall3d988d92009-12-02 08:47:38 +0000884 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000885 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
886 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
887 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
888 continue;
889 }
890
John McCalldaa3d6b2009-12-09 03:35:25 +0000891 Match = *I;
892 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000893 }
John McCalla8987a2942010-11-10 03:01:53 +0000894 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000895 // We can overload with these, which can show up when doing
896 // redeclaration checks for UsingDecls.
897 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000898 } else if (isa<TagDecl>(OldD)) {
899 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000900 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
901 // Optimistically assume that an unresolved using decl will
902 // overload; if it doesn't, we'll have to diagnose during
903 // template instantiation.
904 } else {
John McCall1f82f242009-11-18 22:49:29 +0000905 // (C++ 13p1):
906 // Only function declarations can be overloaded; object and type
907 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000910 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911 }
John McCall1f82f242009-11-18 22:49:29 +0000912
John McCalldaa3d6b2009-12-09 03:35:25 +0000913 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000914}
915
John McCalle9cccd82010-06-16 08:42:20 +0000916bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
917 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000918 // If both of the functions are extern "C", then they are not
919 // overloads.
920 if (Old->isExternC() && New->isExternC())
921 return false;
922
John McCall1f82f242009-11-18 22:49:29 +0000923 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
924 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
925
926 // C++ [temp.fct]p2:
927 // A function template can be overloaded with other function templates
928 // and with normal (non-template) functions.
929 if ((OldTemplate == 0) != (NewTemplate == 0))
930 return true;
931
932 // Is the function New an overload of the function Old?
933 QualType OldQType = Context.getCanonicalType(Old->getType());
934 QualType NewQType = Context.getCanonicalType(New->getType());
935
936 // Compare the signatures (C++ 1.3.10) of the two functions to
937 // determine whether they are overloads. If we find any mismatch
938 // in the signature, they are overloads.
939
940 // If either of these functions is a K&R-style function (no
941 // prototype), then we consider them to have matching signatures.
942 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
943 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
944 return false;
945
John McCall424cec92011-01-19 06:33:43 +0000946 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
947 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000948
949 // The signature of a function includes the types of its
950 // parameters (C++ 1.3.10), which includes the presence or absence
951 // of the ellipsis; see C++ DR 357).
952 if (OldQType != NewQType &&
953 (OldType->getNumArgs() != NewType->getNumArgs() ||
954 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000955 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000956 return true;
957
958 // C++ [temp.over.link]p4:
959 // The signature of a function template consists of its function
960 // signature, its return type and its template parameter list. The names
961 // of the template parameters are significant only for establishing the
962 // relationship between the template parameters and the rest of the
963 // signature.
964 //
965 // We check the return type and template parameter lists for function
966 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000967 //
968 // However, we don't consider either of these when deciding whether
969 // a member introduced by a shadow declaration is hidden.
970 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000971 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
972 OldTemplate->getTemplateParameters(),
973 false, TPL_TemplateMatch) ||
974 OldType->getResultType() != NewType->getResultType()))
975 return true;
976
977 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000978 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000979 //
980 // As part of this, also check whether one of the member functions
981 // is static, in which case they are not overloads (C++
982 // 13.1p2). While not part of the definition of the signature,
983 // this check is important to determine whether these functions
984 // can be overloaded.
985 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
986 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
987 if (OldMethod && NewMethod &&
988 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000989 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000990 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
991 if (!UseUsingDeclRules &&
992 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
993 (OldMethod->getRefQualifier() == RQ_None ||
994 NewMethod->getRefQualifier() == RQ_None)) {
995 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996 // - Member function declarations with the same name and the same
997 // parameter-type-list as well as member function template
998 // declarations with the same name, the same parameter-type-list, and
999 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001000 // them, but not all, have a ref-qualifier (8.3.5).
1001 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1002 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1003 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
John McCall1f82f242009-11-18 22:49:29 +00001006 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008
John McCall1f82f242009-11-18 22:49:29 +00001009 // The signatures match; this is not an overload.
1010 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001011}
1012
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001013/// \brief Checks availability of the function depending on the current
1014/// function context. Inside an unavailable function, unavailability is ignored.
1015///
1016/// \returns true if \arg FD is unavailable and current context is inside
1017/// an available function, false otherwise.
1018bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1019 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1020}
1021
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001022/// \brief Tries a user-defined conversion from From to ToType.
1023///
1024/// Produces an implicit conversion sequence for when a standard conversion
1025/// is not an option. See TryImplicitConversion for more information.
1026static ImplicitConversionSequence
1027TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1028 bool SuppressUserConversions,
1029 bool AllowExplicit,
1030 bool InOverloadResolution,
1031 bool CStyle,
1032 bool AllowObjCWritebackConversion) {
1033 ImplicitConversionSequence ICS;
1034
1035 if (SuppressUserConversions) {
1036 // We're not in the case above, so there is no conversion that
1037 // we can perform.
1038 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1039 return ICS;
1040 }
1041
1042 // Attempt user-defined conversion.
1043 OverloadCandidateSet Conversions(From->getExprLoc());
1044 OverloadingResult UserDefResult
1045 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1046 AllowExplicit);
1047
1048 if (UserDefResult == OR_Success) {
1049 ICS.setUserDefined();
1050 // C++ [over.ics.user]p4:
1051 // A conversion of an expression of class type to the same class
1052 // type is given Exact Match rank, and a conversion of an
1053 // expression of class type to a base class of that type is
1054 // given Conversion rank, in spite of the fact that a copy
1055 // constructor (i.e., a user-defined conversion function) is
1056 // called for those cases.
1057 if (CXXConstructorDecl *Constructor
1058 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1059 QualType FromCanon
1060 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1061 QualType ToCanon
1062 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1063 if (Constructor->isCopyConstructor() &&
1064 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1065 // Turn this into a "standard" conversion sequence, so that it
1066 // gets ranked with standard conversion sequences.
1067 ICS.setStandard();
1068 ICS.Standard.setAsIdentityConversion();
1069 ICS.Standard.setFromType(From->getType());
1070 ICS.Standard.setAllToTypes(ToType);
1071 ICS.Standard.CopyConstructor = Constructor;
1072 if (ToCanon != FromCanon)
1073 ICS.Standard.Second = ICK_Derived_To_Base;
1074 }
1075 }
1076
1077 // C++ [over.best.ics]p4:
1078 // However, when considering the argument of a user-defined
1079 // conversion function that is a candidate by 13.3.1.3 when
1080 // invoked for the copying of the temporary in the second step
1081 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1082 // 13.3.1.6 in all cases, only standard conversion sequences and
1083 // ellipsis conversion sequences are allowed.
1084 if (SuppressUserConversions && ICS.isUserDefined()) {
1085 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1086 }
1087 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1088 ICS.setAmbiguous();
1089 ICS.Ambiguous.setFromType(From->getType());
1090 ICS.Ambiguous.setToType(ToType);
1091 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1092 Cand != Conversions.end(); ++Cand)
1093 if (Cand->Viable)
1094 ICS.Ambiguous.addConversion(Cand->Function);
1095 } else {
1096 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1097 }
1098
1099 return ICS;
1100}
1101
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001102/// TryImplicitConversion - Attempt to perform an implicit conversion
1103/// from the given expression (Expr) to the given type (ToType). This
1104/// function returns an implicit conversion sequence that can be used
1105/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106///
1107/// void f(float f);
1108/// void g(int i) { f(i); }
1109///
1110/// this routine would produce an implicit conversion sequence to
1111/// describe the initialization of f from i, which will be a standard
1112/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1113/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1114//
1115/// Note that this routine only determines how the conversion can be
1116/// performed; it does not actually perform the conversion. As such,
1117/// it will not produce any diagnostics if no conversion is available,
1118/// but will instead return an implicit conversion sequence of kind
1119/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001120///
1121/// If @p SuppressUserConversions, then user-defined conversions are
1122/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001123/// If @p AllowExplicit, then explicit user-defined conversions are
1124/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001125///
1126/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1127/// writeback conversion, which allows __autoreleasing id* parameters to
1128/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001129static ImplicitConversionSequence
1130TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1131 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001133 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001134 bool CStyle,
1135 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001136 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001137 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001138 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001139 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001140 return ICS;
1141 }
1142
David Blaikiebbafb8a2012-03-11 07:00:24 +00001143 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001144 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001145 return ICS;
1146 }
1147
Douglas Gregor836a7e82010-08-11 02:15:33 +00001148 // C++ [over.ics.user]p4:
1149 // A conversion of an expression of class type to the same class
1150 // type is given Exact Match rank, and a conversion of an
1151 // expression of class type to a base class of that type is
1152 // given Conversion rank, in spite of the fact that a copy/move
1153 // constructor (i.e., a user-defined conversion function) is
1154 // called for those cases.
1155 QualType FromType = From->getType();
1156 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001157 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1158 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001159 ICS.setStandard();
1160 ICS.Standard.setAsIdentityConversion();
1161 ICS.Standard.setFromType(FromType);
1162 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163
Douglas Gregor5ab11652010-04-17 22:01:05 +00001164 // We don't actually check at this point whether there is a valid
1165 // copy/move constructor, since overloading just assumes that it
1166 // exists. When we actually perform initialization, we'll find the
1167 // appropriate constructor to copy the returned object, if needed.
1168 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
Douglas Gregor5ab11652010-04-17 22:01:05 +00001170 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001171 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001172 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173
Douglas Gregor836a7e82010-08-11 02:15:33 +00001174 return ICS;
1175 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001177 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1178 AllowExplicit, InOverloadResolution, CStyle,
1179 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001180}
1181
John McCall31168b02011-06-15 23:02:42 +00001182ImplicitConversionSequence
1183Sema::TryImplicitConversion(Expr *From, QualType ToType,
1184 bool SuppressUserConversions,
1185 bool AllowExplicit,
1186 bool InOverloadResolution,
1187 bool CStyle,
1188 bool AllowObjCWritebackConversion) {
1189 return clang::TryImplicitConversion(*this, From, ToType,
1190 SuppressUserConversions, AllowExplicit,
1191 InOverloadResolution, CStyle,
1192 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001193}
1194
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001195/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001196/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001197/// converted expression. Flavor is the kind of conversion we're
1198/// performing, used in the error message. If @p AllowExplicit,
1199/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001200ExprResult
1201Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001202 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001203 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001204 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001205}
1206
John Wiegley01296292011-04-08 18:41:53 +00001207ExprResult
1208Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001209 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001210 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001211 if (checkPlaceholderForOverload(*this, From))
1212 return ExprError();
1213
John McCall31168b02011-06-15 23:02:42 +00001214 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1215 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001216 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001217 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001218
John McCall5c32be02010-08-24 20:38:10 +00001219 ICS = clang::TryImplicitConversion(*this, From, ToType,
1220 /*SuppressUserConversions=*/false,
1221 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001222 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001223 /*CStyle=*/false,
1224 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001225 return PerformImplicitConversion(From, ToType, ICS, Action);
1226}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227
1228/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001229/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001230bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1231 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001232 if (Context.hasSameUnqualifiedType(FromType, ToType))
1233 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
John McCall991eb4b2010-12-21 00:44:39 +00001235 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1236 // where F adds one of the following at most once:
1237 // - a pointer
1238 // - a member pointer
1239 // - a block pointer
1240 CanQualType CanTo = Context.getCanonicalType(ToType);
1241 CanQualType CanFrom = Context.getCanonicalType(FromType);
1242 Type::TypeClass TyClass = CanTo->getTypeClass();
1243 if (TyClass != CanFrom->getTypeClass()) return false;
1244 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1245 if (TyClass == Type::Pointer) {
1246 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1247 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1248 } else if (TyClass == Type::BlockPointer) {
1249 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1250 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1251 } else if (TyClass == Type::MemberPointer) {
1252 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1253 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1254 } else {
1255 return false;
1256 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001257
John McCall991eb4b2010-12-21 00:44:39 +00001258 TyClass = CanTo->getTypeClass();
1259 if (TyClass != CanFrom->getTypeClass()) return false;
1260 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1261 return false;
1262 }
1263
1264 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1265 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1266 if (!EInfo.getNoReturn()) return false;
1267
1268 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1269 assert(QualType(FromFn, 0).isCanonical());
1270 if (QualType(FromFn, 0) != CanTo) return false;
1271
1272 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001273 return true;
1274}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
Douglas Gregor46188682010-05-18 22:42:18 +00001276/// \brief Determine whether the conversion from FromType to ToType is a valid
1277/// vector conversion.
1278///
1279/// \param ICK Will be set to the vector conversion kind, if this is a vector
1280/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1282 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001283 // We need at least one of these types to be a vector type to have a vector
1284 // conversion.
1285 if (!ToType->isVectorType() && !FromType->isVectorType())
1286 return false;
1287
1288 // Identical types require no conversions.
1289 if (Context.hasSameUnqualifiedType(FromType, ToType))
1290 return false;
1291
1292 // There are no conversions between extended vector types, only identity.
1293 if (ToType->isExtVectorType()) {
1294 // There are no conversions between extended vector types other than the
1295 // identity conversion.
1296 if (FromType->isExtVectorType())
1297 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298
Douglas Gregor46188682010-05-18 22:42:18 +00001299 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001300 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001301 ICK = ICK_Vector_Splat;
1302 return true;
1303 }
1304 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001305
1306 // We can perform the conversion between vector types in the following cases:
1307 // 1)vector types are equivalent AltiVec and GCC vector types
1308 // 2)lax vector conversions are permitted and the vector types are of the
1309 // same size
1310 if (ToType->isVectorType() && FromType->isVectorType()) {
1311 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001312 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001313 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001314 ICK = ICK_Vector_Conversion;
1315 return true;
1316 }
Douglas Gregor46188682010-05-18 22:42:18 +00001317 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001318
Douglas Gregor46188682010-05-18 22:42:18 +00001319 return false;
1320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001322static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1323 bool InOverloadResolution,
1324 StandardConversionSequence &SCS,
1325 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001326
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001327/// IsStandardConversion - Determines whether there is a standard
1328/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1329/// expression From to the type ToType. Standard conversion sequences
1330/// only consider non-class types; for conversions that involve class
1331/// types, use TryImplicitConversion. If a conversion exists, SCS will
1332/// contain the standard conversion sequence required to perform this
1333/// conversion and this routine will return true. Otherwise, this
1334/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001335static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1336 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001337 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001338 bool CStyle,
1339 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001340 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001342 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001343 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001344 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001345 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001346 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001347 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001348
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001349 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001350 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001351 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001352 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001353 return false;
1354
Mike Stump11289f42009-09-09 15:08:12 +00001355 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001356 }
1357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358 // The first conversion can be an lvalue-to-rvalue conversion,
1359 // array-to-pointer conversion, or function-to-pointer conversion
1360 // (C++ 4p1).
1361
John McCall5c32be02010-08-24 20:38:10 +00001362 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001363 DeclAccessPair AccessPair;
1364 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001366 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001367 // We were able to resolve the address of the overloaded function,
1368 // so we can convert to the type of that function.
1369 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001370
1371 // we can sometimes resolve &foo<int> regardless of ToType, so check
1372 // if the type matches (identity) or we are converting to bool
1373 if (!S.Context.hasSameUnqualifiedType(
1374 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1375 QualType resultTy;
1376 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001377 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001378 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1379 // otherwise, only a boolean conversion is standard
1380 if (!ToType->isBooleanType())
1381 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383
Chandler Carruthffce2452011-03-29 08:08:18 +00001384 // Check if the "from" expression is taking the address of an overloaded
1385 // function and recompute the FromType accordingly. Take advantage of the
1386 // fact that non-static member functions *must* have such an address-of
1387 // expression.
1388 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1389 if (Method && !Method->isStatic()) {
1390 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1391 "Non-unary operator on non-static member address");
1392 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1393 == UO_AddrOf &&
1394 "Non-address-of operator on non-static member address");
1395 const Type *ClassType
1396 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1397 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001398 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1399 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1400 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001401 "Non-address-of operator for overloaded function expression");
1402 FromType = S.Context.getPointerType(FromType);
1403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001404
Douglas Gregor980fb162010-04-29 18:24:40 +00001405 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001406 assert(S.Context.hasSameType(
1407 FromType,
1408 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001409 } else {
1410 return false;
1411 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001412 }
John McCall154a2fd2011-08-30 00:57:29 +00001413 // Lvalue-to-rvalue conversion (C++11 4.1):
1414 // A glvalue (3.10) of a non-function, non-array type T can
1415 // be converted to a prvalue.
1416 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001417 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001418 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001419 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001420 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421
Douglas Gregorc79862f2012-04-12 17:51:55 +00001422 // C11 6.3.2.1p2:
1423 // ... if the lvalue has atomic type, the value has the non-atomic version
1424 // of the type of the lvalue ...
1425 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1426 FromType = Atomic->getValueType();
1427
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428 // If T is a non-class type, the type of the rvalue is the
1429 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001430 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1431 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001432 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001433 } else if (FromType->isArrayType()) {
1434 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001435 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001436
1437 // An lvalue or rvalue of type "array of N T" or "array of unknown
1438 // bound of T" can be converted to an rvalue of type "pointer to
1439 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001440 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001441
John McCall5c32be02010-08-24 20:38:10 +00001442 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001444 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445
1446 // For the purpose of ranking in overload resolution
1447 // (13.3.3.1.1), this conversion is considered an
1448 // array-to-pointer conversion followed by a qualification
1449 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001450 SCS.Second = ICK_Identity;
1451 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001452 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001453 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001454 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001455 }
John McCall086a4642010-11-24 05:12:34 +00001456 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001457 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001458 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459
1460 // An lvalue of function type T can be converted to an rvalue of
1461 // type "pointer to T." The result is a pointer to the
1462 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001463 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001464 } else {
1465 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001466 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001467 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001468 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001469
1470 // The second conversion can be an integral promotion, floating
1471 // point promotion, integral conversion, floating point conversion,
1472 // floating-integral conversion, pointer conversion,
1473 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001474 // For overloading in C, this can also be a "compatible-type"
1475 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001476 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001477 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001478 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479 // The unqualified versions of the types are the same: there's no
1480 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001481 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001482 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001483 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001486 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001487 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001489 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001490 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001491 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001492 SCS.Second = ICK_Complex_Promotion;
1493 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001494 } else if (ToType->isBooleanType() &&
1495 (FromType->isArithmeticType() ||
1496 FromType->isAnyPointerType() ||
1497 FromType->isBlockPointerType() ||
1498 FromType->isMemberPointerType() ||
1499 FromType->isNullPtrType())) {
1500 // Boolean conversions (C++ 4.12).
1501 SCS.Second = ICK_Boolean_Conversion;
1502 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001503 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001504 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001505 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001506 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001508 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001509 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001510 SCS.Second = ICK_Complex_Conversion;
1511 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001512 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1513 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001514 // Complex-real conversions (C99 6.3.1.7)
1515 SCS.Second = ICK_Complex_Real;
1516 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001517 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001518 // Floating point conversions (C++ 4.8).
1519 SCS.Second = ICK_Floating_Conversion;
1520 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001522 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001523 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001524 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001528 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001529 SCS.Second = ICK_Block_Pointer_Conversion;
1530 } else if (AllowObjCWritebackConversion &&
1531 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1532 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001533 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1534 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001535 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001537 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001538 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001540 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001541 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001542 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001543 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001544 SCS.Second = SecondICK;
1545 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001546 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001547 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001548 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001549 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001550 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001551 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001552 // Treat a conversion that strips "noreturn" as an identity conversion.
1553 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001554 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1555 InOverloadResolution,
1556 SCS, CStyle)) {
1557 SCS.Second = ICK_TransparentUnionConversion;
1558 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001559 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1560 CStyle)) {
1561 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001562 // appropriately.
1563 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 } else {
1565 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001568 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001569
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001570 QualType CanonFrom;
1571 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001573 bool ObjCLifetimeConversion;
1574 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1575 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001577 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001578 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001579 CanonFrom = S.Context.getCanonicalType(FromType);
1580 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 } else {
1582 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 SCS.Third = ICK_Identity;
1584
Mike Stump11289f42009-09-09 15:08:12 +00001585 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 // [...] Any difference in top-level cv-qualification is
1587 // subsumed by the initialization itself and does not constitute
1588 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001589 CanonFrom = S.Context.getCanonicalType(FromType);
1590 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001592 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001593 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001594 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1595 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001596 FromType = ToType;
1597 CanonFrom = CanonTo;
1598 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001600 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001601
1602 // If we have not converted the argument type to the parameter type,
1603 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001604 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001606
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001609
1610static bool
1611IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1612 QualType &ToType,
1613 bool InOverloadResolution,
1614 StandardConversionSequence &SCS,
1615 bool CStyle) {
1616
1617 const RecordType *UT = ToType->getAsUnionType();
1618 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1619 return false;
1620 // The field to initialize within the transparent union.
1621 RecordDecl *UD = UT->getDecl();
1622 // It's compatible if the expression matches any of the fields.
1623 for (RecordDecl::field_iterator it = UD->field_begin(),
1624 itend = UD->field_end();
1625 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001626 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1627 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001628 ToType = it->getType();
1629 return true;
1630 }
1631 }
1632 return false;
1633}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634
1635/// IsIntegralPromotion - Determines whether the conversion from the
1636/// expression From (whose potentially-adjusted type is FromType) to
1637/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1638/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001639bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001640 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001641 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001642 if (!To) {
1643 return false;
1644 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001645
1646 // An rvalue of type char, signed char, unsigned char, short int, or
1647 // unsigned short int can be converted to an rvalue of type int if
1648 // int can represent all the values of the source type; otherwise,
1649 // the source rvalue can be converted to an rvalue of type unsigned
1650 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001651 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1652 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653 if (// We can promote any signed, promotable integer type to an int
1654 (FromType->isSignedIntegerType() ||
1655 // We can promote any unsigned integer type whose size is
1656 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001657 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001658 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001660 }
1661
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 return To->getKind() == BuiltinType::UInt;
1663 }
1664
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665 // C++0x [conv.prom]p3:
1666 // A prvalue of an unscoped enumeration type whose underlying type is not
1667 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1668 // following types that can represent all the values of the enumeration
1669 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1670 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001671 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001673 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674 // with lowest integer conversion rank (4.13) greater than the rank of long
1675 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001676 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001677 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1678 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1679 // provided for a scoped enumeration.
1680 if (FromEnumType->getDecl()->isScoped())
1681 return false;
1682
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001683 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001685 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001686 return Context.hasSameUnqualifiedType(ToType,
1687 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001688 }
John McCall56774992009-12-09 09:09:27 +00001689
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001690 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1692 // to an rvalue a prvalue of the first of the following types that can
1693 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001694 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001695 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001696 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001698 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001700 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701 // Determine whether the type we're converting from is signed or
1702 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001703 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 // The types we'll try to promote to, in the appropriate
1707 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001708 QualType PromoteTypes[6] = {
1709 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001710 Context.LongTy, Context.UnsignedLongTy ,
1711 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001713 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1715 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001716 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1718 // We found the type that we can promote to. If this is the
1719 // type we wanted, we have a promotion. Otherwise, no
1720 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001721 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 }
1723 }
1724 }
1725
1726 // An rvalue for an integral bit-field (9.6) can be converted to an
1727 // rvalue of type int if int can represent all the values of the
1728 // bit-field; otherwise, it can be converted to unsigned int if
1729 // unsigned int can represent all the values of the bit-field. If
1730 // the bit-field is larger yet, no integral promotion applies to
1731 // it. If the bit-field has an enumerated type, it is treated as any
1732 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001733 // FIXME: We should delay checking of bit-fields until we actually perform the
1734 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001735 using llvm::APSInt;
1736 if (From)
1737 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001738 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001739 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001740 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1741 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1742 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001744 // Are we promoting to an int from a bitfield that fits in an int?
1745 if (BitWidth < ToSize ||
1746 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1747 return To->getKind() == BuiltinType::Int;
1748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001750 // Are we promoting to an unsigned int from an unsigned bitfield
1751 // that fits into an unsigned int?
1752 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1753 return To->getKind() == BuiltinType::UInt;
1754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001756 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001757 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760 // An rvalue of type bool can be converted to an rvalue of type int,
1761 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001762 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001763 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001764 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765
1766 return false;
1767}
1768
1769/// IsFloatingPointPromotion - Determines whether the conversion from
1770/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1771/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001772bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001773 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1774 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001775 /// An rvalue of type float can be converted to an rvalue of type
1776 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777 if (FromBuiltin->getKind() == BuiltinType::Float &&
1778 ToBuiltin->getKind() == BuiltinType::Double)
1779 return true;
1780
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001781 // C99 6.3.1.5p1:
1782 // When a float is promoted to double or long double, or a
1783 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001784 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001785 (FromBuiltin->getKind() == BuiltinType::Float ||
1786 FromBuiltin->getKind() == BuiltinType::Double) &&
1787 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1788 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001789
1790 // Half can be promoted to float.
1791 if (FromBuiltin->getKind() == BuiltinType::Half &&
1792 ToBuiltin->getKind() == BuiltinType::Float)
1793 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001794 }
1795
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001796 return false;
1797}
1798
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001799/// \brief Determine if a conversion is a complex promotion.
1800///
1801/// A complex promotion is defined as a complex -> complex conversion
1802/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001803/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001804bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001805 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001806 if (!FromComplex)
1807 return false;
1808
John McCall9dd450b2009-09-21 23:43:11 +00001809 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001810 if (!ToComplex)
1811 return false;
1812
1813 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001814 ToComplex->getElementType()) ||
1815 IsIntegralPromotion(0, FromComplex->getElementType(),
1816 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001817}
1818
Douglas Gregor237f96c2008-11-26 23:31:11 +00001819/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1820/// the pointer type FromPtr to a pointer to type ToPointee, with the
1821/// same type qualifiers as FromPtr has on its pointee type. ToType,
1822/// if non-empty, will be a pointer to ToType that may or may not have
1823/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001824///
Mike Stump11289f42009-09-09 15:08:12 +00001825static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001826BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001827 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001828 ASTContext &Context,
1829 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001830 assert((FromPtr->getTypeClass() == Type::Pointer ||
1831 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1832 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001833
John McCall31168b02011-06-15 23:02:42 +00001834 /// Conversions to 'id' subsume cv-qualifier conversions.
1835 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001836 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
1838 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001839 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001840 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001841 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001842
John McCall31168b02011-06-15 23:02:42 +00001843 if (StripObjCLifetime)
1844 Quals.removeObjCLifetime();
1845
Mike Stump11289f42009-09-09 15:08:12 +00001846 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001847 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001848 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001849 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001850 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001851
1852 // Build a pointer to ToPointee. It has the right qualifiers
1853 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001854 if (isa<ObjCObjectPointerType>(ToType))
1855 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001856 return Context.getPointerType(ToPointee);
1857 }
1858
1859 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001860 QualType QualifiedCanonToPointee
1861 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001863 if (isa<ObjCObjectPointerType>(ToType))
1864 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1865 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001866}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
Mike Stump11289f42009-09-09 15:08:12 +00001868static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001869 bool InOverloadResolution,
1870 ASTContext &Context) {
1871 // Handle value-dependent integral null pointer constants correctly.
1872 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1873 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001874 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001875 return !InOverloadResolution;
1876
Douglas Gregor56751b52009-09-25 04:25:58 +00001877 return Expr->isNullPointerConstant(Context,
1878 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1879 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001880}
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882/// IsPointerConversion - Determines whether the conversion of the
1883/// expression From, which has the (possibly adjusted) type FromType,
1884/// can be converted to the type ToType via a pointer conversion (C++
1885/// 4.10). If so, returns true and places the converted type (that
1886/// might differ from ToType in its cv-qualifiers at some level) into
1887/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001888///
Douglas Gregora29dc052008-11-27 01:19:21 +00001889/// This routine also supports conversions to and from block pointers
1890/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1891/// pointers to interfaces. FIXME: Once we've determined the
1892/// appropriate overloading rules for Objective-C, we may want to
1893/// split the Objective-C checks into a different routine; however,
1894/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001895/// conversions, so for now they live here. IncompatibleObjC will be
1896/// set if the conversion is an allowed Objective-C conversion that
1897/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001898bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001899 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001900 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001901 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001902 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001903 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1904 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001905 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001906
Mike Stump11289f42009-09-09 15:08:12 +00001907 // Conversion from a null pointer constant to any Objective-C pointer type.
1908 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001909 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001910 ConvertedType = ToType;
1911 return true;
1912 }
1913
Douglas Gregor231d1c62008-11-27 00:15:41 +00001914 // Blocks: Block pointers can be converted to void*.
1915 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001916 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001917 ConvertedType = ToType;
1918 return true;
1919 }
1920 // Blocks: A null pointer constant can be converted to a block
1921 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001922 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001923 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001924 ConvertedType = ToType;
1925 return true;
1926 }
1927
Sebastian Redl576fd422009-05-10 18:38:11 +00001928 // If the left-hand-side is nullptr_t, the right side can be a null
1929 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001930 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001931 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001932 ConvertedType = ToType;
1933 return true;
1934 }
1935
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001936 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001937 if (!ToTypePtr)
1938 return false;
1939
1940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001941 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942 ConvertedType = ToType;
1943 return true;
1944 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001945
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001947 // , including objective-c pointers.
1948 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001949 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001951 ConvertedType = BuildSimilarlyQualifiedPointerType(
1952 FromType->getAs<ObjCObjectPointerType>(),
1953 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001954 ToType, Context);
1955 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001956 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001957 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001958 if (!FromTypePtr)
1959 return false;
1960
1961 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001962
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001964 // pointer conversion, so don't do all of the work below.
1965 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1966 return false;
1967
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 // An rvalue of type "pointer to cv T," where T is an object type,
1969 // can be converted to an rvalue of type "pointer to cv void" (C++
1970 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001971 if (FromPointeeType->isIncompleteOrObjectType() &&
1972 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001974 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001975 ToType, Context,
1976 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001977 return true;
1978 }
1979
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001980 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001981 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001982 ToPointeeType->isVoidType()) {
1983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1984 ToPointeeType,
1985 ToType, Context);
1986 return true;
1987 }
1988
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001989 // When we're overloading in C, we allow a special kind of pointer
1990 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001991 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001992 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001993 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001994 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001995 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001996 return true;
1997 }
1998
Douglas Gregor5c407d92008-10-23 00:40:37 +00001999 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002000 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002001 // An rvalue of type "pointer to cv D," where D is a class type,
2002 // can be converted to an rvalue of type "pointer to cv B," where
2003 // B is a base class (clause 10) of D. If B is an inaccessible
2004 // (clause 11) or ambiguous (10.2) base class of D, a program that
2005 // necessitates this conversion is ill-formed. The result of the
2006 // conversion is a pointer to the base class sub-object of the
2007 // derived class object. The null pointer value is converted to
2008 // the null pointer value of the destination type.
2009 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002010 // Note that we do not check for ambiguity or inaccessibility
2011 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002013 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002014 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002015 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002016 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002018 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002019 ToType, Context);
2020 return true;
2021 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002022
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002023 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2024 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2026 ToPointeeType,
2027 ToType, Context);
2028 return true;
2029 }
2030
Douglas Gregora119f102008-12-19 19:13:09 +00002031 return false;
2032}
Douglas Gregoraec25842011-04-26 23:16:46 +00002033
2034/// \brief Adopt the given qualifiers for the given type.
2035static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2036 Qualifiers TQs = T.getQualifiers();
2037
2038 // Check whether qualifiers already match.
2039 if (TQs == Qs)
2040 return T;
2041
2042 if (Qs.compatiblyIncludes(TQs))
2043 return Context.getQualifiedType(T, Qs);
2044
2045 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2046}
Douglas Gregora119f102008-12-19 19:13:09 +00002047
2048/// isObjCPointerConversion - Determines whether this is an
2049/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2050/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002051bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002052 QualType& ConvertedType,
2053 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002054 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002055 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
Douglas Gregoraec25842011-04-26 23:16:46 +00002057 // The set of qualifiers on the type we're converting from.
2058 Qualifiers FromQualifiers = FromType.getQualifiers();
2059
Steve Naroff7cae42b2009-07-10 23:34:53 +00002060 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002061 const ObjCObjectPointerType* ToObjCPtr =
2062 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002063 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002064 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002065
Steve Naroff7cae42b2009-07-10 23:34:53 +00002066 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002067 // If the pointee types are the same (ignoring qualifications),
2068 // then this is not a pointer conversion.
2069 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2070 FromObjCPtr->getPointeeType()))
2071 return false;
2072
Douglas Gregoraec25842011-04-26 23:16:46 +00002073 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002074 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002075 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002076 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002077 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002078 return true;
2079 }
2080 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002081 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002082 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002083 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002084 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002085 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002086 return true;
2087 }
2088 // Objective C++: We're able to convert from a pointer to an
2089 // interface to a pointer to a different interface.
2090 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002091 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2092 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002093 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002094 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2095 FromObjCPtr->getPointeeType()))
2096 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002098 ToObjCPtr->getPointeeType(),
2099 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002100 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002101 return true;
2102 }
2103
2104 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2105 // Okay: this is some kind of implicit downcast of Objective-C
2106 // interfaces, which is permitted. However, we're going to
2107 // complain about it.
2108 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002110 ToObjCPtr->getPointeeType(),
2111 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002112 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002113 return true;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002116 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002117 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002118 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002119 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002120 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002121 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002122 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002123 // to a block pointer type.
2124 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002125 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002126 return true;
2127 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002128 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002131 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002133 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002134 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002135 return true;
2136 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002137 else
Douglas Gregora119f102008-12-19 19:13:09 +00002138 return false;
2139
Douglas Gregor033f56d2008-12-23 00:53:59 +00002140 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002141 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002142 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002143 else if (const BlockPointerType *FromBlockPtr =
2144 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002145 FromPointeeType = FromBlockPtr->getPointeeType();
2146 else
Douglas Gregora119f102008-12-19 19:13:09 +00002147 return false;
2148
Douglas Gregora119f102008-12-19 19:13:09 +00002149 // If we have pointers to pointers, recursively check whether this
2150 // is an Objective-C conversion.
2151 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2152 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2153 IncompatibleObjC)) {
2154 // We always complain about this conversion.
2155 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002156 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002157 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002158 return true;
2159 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002160 // Allow conversion of pointee being objective-c pointer to another one;
2161 // as in I* to id.
2162 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2163 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2164 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2165 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002166
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002167 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002169 return true;
2170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171
Douglas Gregor033f56d2008-12-23 00:53:59 +00002172 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002173 // differences in the argument and result types are in Objective-C
2174 // pointer conversions. If so, we permit the conversion (but
2175 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002176 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002177 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002178 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002179 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002180 if (FromFunctionType && ToFunctionType) {
2181 // If the function types are exactly the same, this isn't an
2182 // Objective-C pointer conversion.
2183 if (Context.getCanonicalType(FromPointeeType)
2184 == Context.getCanonicalType(ToPointeeType))
2185 return false;
2186
2187 // Perform the quick checks that will tell us whether these
2188 // function types are obviously different.
2189 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2190 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2191 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2192 return false;
2193
2194 bool HasObjCConversion = false;
2195 if (Context.getCanonicalType(FromFunctionType->getResultType())
2196 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2197 // Okay, the types match exactly. Nothing to do.
2198 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2199 ToFunctionType->getResultType(),
2200 ConvertedType, IncompatibleObjC)) {
2201 // Okay, we have an Objective-C pointer conversion.
2202 HasObjCConversion = true;
2203 } else {
2204 // Function types are too different. Abort.
2205 return false;
2206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Douglas Gregora119f102008-12-19 19:13:09 +00002208 // Check argument types.
2209 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2210 ArgIdx != NumArgs; ++ArgIdx) {
2211 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2212 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2213 if (Context.getCanonicalType(FromArgType)
2214 == Context.getCanonicalType(ToArgType)) {
2215 // Okay, the types match exactly. Nothing to do.
2216 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2217 ConvertedType, IncompatibleObjC)) {
2218 // Okay, we have an Objective-C pointer conversion.
2219 HasObjCConversion = true;
2220 } else {
2221 // Argument types are too different. Abort.
2222 return false;
2223 }
2224 }
2225
2226 if (HasObjCConversion) {
2227 // We had an Objective-C conversion. Allow this pointer
2228 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002229 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002230 IncompatibleObjC = true;
2231 return true;
2232 }
2233 }
2234
Sebastian Redl72b597d2009-01-25 19:43:20 +00002235 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002236}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
John McCall31168b02011-06-15 23:02:42 +00002238/// \brief Determine whether this is an Objective-C writeback conversion,
2239/// used for parameter passing when performing automatic reference counting.
2240///
2241/// \param FromType The type we're converting form.
2242///
2243/// \param ToType The type we're converting to.
2244///
2245/// \param ConvertedType The type that will be produced after applying
2246/// this conversion.
2247bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2248 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002249 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002250 Context.hasSameUnqualifiedType(FromType, ToType))
2251 return false;
2252
2253 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2254 QualType ToPointee;
2255 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2256 ToPointee = ToPointer->getPointeeType();
2257 else
2258 return false;
2259
2260 Qualifiers ToQuals = ToPointee.getQualifiers();
2261 if (!ToPointee->isObjCLifetimeType() ||
2262 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002263 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002264 return false;
2265
2266 // Argument must be a pointer to __strong to __weak.
2267 QualType FromPointee;
2268 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2269 FromPointee = FromPointer->getPointeeType();
2270 else
2271 return false;
2272
2273 Qualifiers FromQuals = FromPointee.getQualifiers();
2274 if (!FromPointee->isObjCLifetimeType() ||
2275 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2276 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2277 return false;
2278
2279 // Make sure that we have compatible qualifiers.
2280 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2281 if (!ToQuals.compatiblyIncludes(FromQuals))
2282 return false;
2283
2284 // Remove qualifiers from the pointee type we're converting from; they
2285 // aren't used in the compatibility check belong, and we'll be adding back
2286 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2287 FromPointee = FromPointee.getUnqualifiedType();
2288
2289 // The unqualified form of the pointee types must be compatible.
2290 ToPointee = ToPointee.getUnqualifiedType();
2291 bool IncompatibleObjC;
2292 if (Context.typesAreCompatible(FromPointee, ToPointee))
2293 FromPointee = ToPointee;
2294 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2295 IncompatibleObjC))
2296 return false;
2297
2298 /// \brief Construct the type we're converting to, which is a pointer to
2299 /// __autoreleasing pointee.
2300 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2301 ConvertedType = Context.getPointerType(FromPointee);
2302 return true;
2303}
2304
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002305bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2306 QualType& ConvertedType) {
2307 QualType ToPointeeType;
2308 if (const BlockPointerType *ToBlockPtr =
2309 ToType->getAs<BlockPointerType>())
2310 ToPointeeType = ToBlockPtr->getPointeeType();
2311 else
2312 return false;
2313
2314 QualType FromPointeeType;
2315 if (const BlockPointerType *FromBlockPtr =
2316 FromType->getAs<BlockPointerType>())
2317 FromPointeeType = FromBlockPtr->getPointeeType();
2318 else
2319 return false;
2320 // We have pointer to blocks, check whether the only
2321 // differences in the argument and result types are in Objective-C
2322 // pointer conversions. If so, we permit the conversion.
2323
2324 const FunctionProtoType *FromFunctionType
2325 = FromPointeeType->getAs<FunctionProtoType>();
2326 const FunctionProtoType *ToFunctionType
2327 = ToPointeeType->getAs<FunctionProtoType>();
2328
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002329 if (!FromFunctionType || !ToFunctionType)
2330 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002331
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002332 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002333 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002334
2335 // Perform the quick checks that will tell us whether these
2336 // function types are obviously different.
2337 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2338 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2339 return false;
2340
2341 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2342 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2343 if (FromEInfo != ToEInfo)
2344 return false;
2345
2346 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002347 if (Context.hasSameType(FromFunctionType->getResultType(),
2348 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002349 // Okay, the types match exactly. Nothing to do.
2350 } else {
2351 QualType RHS = FromFunctionType->getResultType();
2352 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002353 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002354 !RHS.hasQualifiers() && LHS.hasQualifiers())
2355 LHS = LHS.getUnqualifiedType();
2356
2357 if (Context.hasSameType(RHS,LHS)) {
2358 // OK exact match.
2359 } else if (isObjCPointerConversion(RHS, LHS,
2360 ConvertedType, IncompatibleObjC)) {
2361 if (IncompatibleObjC)
2362 return false;
2363 // Okay, we have an Objective-C pointer conversion.
2364 }
2365 else
2366 return false;
2367 }
2368
2369 // Check argument types.
2370 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2371 ArgIdx != NumArgs; ++ArgIdx) {
2372 IncompatibleObjC = false;
2373 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2374 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2375 if (Context.hasSameType(FromArgType, ToArgType)) {
2376 // Okay, the types match exactly. Nothing to do.
2377 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2378 ConvertedType, IncompatibleObjC)) {
2379 if (IncompatibleObjC)
2380 return false;
2381 // Okay, we have an Objective-C pointer conversion.
2382 } else
2383 // Argument types are too different. Abort.
2384 return false;
2385 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002386 if (LangOpts.ObjCAutoRefCount &&
2387 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2388 ToFunctionType))
2389 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002390
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002391 ConvertedType = ToType;
2392 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002393}
2394
Richard Trieucaff2472011-11-23 22:32:32 +00002395enum {
2396 ft_default,
2397 ft_different_class,
2398 ft_parameter_arity,
2399 ft_parameter_mismatch,
2400 ft_return_type,
2401 ft_qualifer_mismatch
2402};
2403
2404/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2405/// function types. Catches different number of parameter, mismatch in
2406/// parameter types, and different return types.
2407void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2408 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002409 // If either type is not valid, include no extra info.
2410 if (FromType.isNull() || ToType.isNull()) {
2411 PDiag << ft_default;
2412 return;
2413 }
2414
Richard Trieucaff2472011-11-23 22:32:32 +00002415 // Get the function type from the pointers.
2416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2417 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2418 *ToMember = ToType->getAs<MemberPointerType>();
2419 if (FromMember->getClass() != ToMember->getClass()) {
2420 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2421 << QualType(FromMember->getClass(), 0);
2422 return;
2423 }
2424 FromType = FromMember->getPointeeType();
2425 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002426 }
2427
Richard Trieu96ed5b62011-12-13 23:19:45 +00002428 if (FromType->isPointerType())
2429 FromType = FromType->getPointeeType();
2430 if (ToType->isPointerType())
2431 ToType = ToType->getPointeeType();
2432
2433 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002434 FromType = FromType.getNonReferenceType();
2435 ToType = ToType.getNonReferenceType();
2436
Richard Trieucaff2472011-11-23 22:32:32 +00002437 // Don't print extra info for non-specialized template functions.
2438 if (FromType->isInstantiationDependentType() &&
2439 !FromType->getAs<TemplateSpecializationType>()) {
2440 PDiag << ft_default;
2441 return;
2442 }
2443
Richard Trieu96ed5b62011-12-13 23:19:45 +00002444 // No extra info for same types.
2445 if (Context.hasSameType(FromType, ToType)) {
2446 PDiag << ft_default;
2447 return;
2448 }
2449
Richard Trieucaff2472011-11-23 22:32:32 +00002450 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2451 *ToFunction = ToType->getAs<FunctionProtoType>();
2452
2453 // Both types need to be function types.
2454 if (!FromFunction || !ToFunction) {
2455 PDiag << ft_default;
2456 return;
2457 }
2458
2459 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2460 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2461 << FromFunction->getNumArgs();
2462 return;
2463 }
2464
2465 // Handle different parameter types.
2466 unsigned ArgPos;
2467 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2468 PDiag << ft_parameter_mismatch << ArgPos + 1
2469 << ToFunction->getArgType(ArgPos)
2470 << FromFunction->getArgType(ArgPos);
2471 return;
2472 }
2473
2474 // Handle different return type.
2475 if (!Context.hasSameType(FromFunction->getResultType(),
2476 ToFunction->getResultType())) {
2477 PDiag << ft_return_type << ToFunction->getResultType()
2478 << FromFunction->getResultType();
2479 return;
2480 }
2481
2482 unsigned FromQuals = FromFunction->getTypeQuals(),
2483 ToQuals = ToFunction->getTypeQuals();
2484 if (FromQuals != ToQuals) {
2485 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2486 return;
2487 }
2488
2489 // Unable to find a difference, so add no extra info.
2490 PDiag << ft_default;
2491}
2492
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002493/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002494/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002495/// they have same number of arguments. This routine assumes that Objective-C
2496/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002497/// If the parameters are different, ArgPos will have the the parameter index
2498/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002500 const FunctionProtoType *NewType,
2501 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002502 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002503 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2504 N = NewType->arg_type_begin(),
2505 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2506 if (!Context.hasSameType(*O, *N)) {
2507 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2508 return false;
2509 }
2510 }
2511 return true;
2512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002513
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002514 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2515 N = NewType->arg_type_begin(),
2516 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2517 QualType ToType = (*O);
2518 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002519 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002520 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2521 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002522 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2523 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2524 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2525 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002526 continue;
2527 }
John McCall8b07ec22010-05-15 11:32:37 +00002528 else if (const ObjCObjectPointerType *PTTo =
2529 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002531 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002532 if (Context.hasSameUnqualifiedType(
2533 PTTo->getObjectType()->getBaseType(),
2534 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002535 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002536 }
Richard Trieucaff2472011-11-23 22:32:32 +00002537 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002539 }
2540 }
2541 return true;
2542}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002543
Douglas Gregor39c16d42008-10-24 04:54:22 +00002544/// CheckPointerConversion - Check the pointer conversion from the
2545/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002546/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002547/// conversions for which IsPointerConversion has already returned
2548/// true. It returns true and produces a diagnostic if there was an
2549/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002550bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002551 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002552 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002553 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002554 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002555 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002556
John McCall8cb679e2010-11-15 09:13:47 +00002557 Kind = CK_BitCast;
2558
Chandler Carruthffab8732011-04-09 07:32:05 +00002559 if (!IsCStyleOrFunctionalCast &&
2560 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2561 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2562 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002563 PDiag(diag::warn_impcast_bool_to_null_pointer)
2564 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002565
John McCall9320b872011-09-09 05:25:32 +00002566 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2567 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002568 QualType FromPointeeType = FromPtrType->getPointeeType(),
2569 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002570
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002571 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2572 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002573 // We must have a derived-to-base conversion. Check an
2574 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002575 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2576 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002577 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002578 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002579 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002581 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002582 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002583 }
2584 }
John McCall9320b872011-09-09 05:25:32 +00002585 } else if (const ObjCObjectPointerType *ToPtrType =
2586 ToType->getAs<ObjCObjectPointerType>()) {
2587 if (const ObjCObjectPointerType *FromPtrType =
2588 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002589 // Objective-C++ conversions are always okay.
2590 // FIXME: We should have a different class of conversions for the
2591 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002592 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002593 return false;
John McCall9320b872011-09-09 05:25:32 +00002594 } else if (FromType->isBlockPointerType()) {
2595 Kind = CK_BlockPointerToObjCPointerCast;
2596 } else {
2597 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002598 }
John McCall9320b872011-09-09 05:25:32 +00002599 } else if (ToType->isBlockPointerType()) {
2600 if (!FromType->isBlockPointerType())
2601 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002602 }
John McCall8cb679e2010-11-15 09:13:47 +00002603
2604 // We shouldn't fall into this case unless it's valid for other
2605 // reasons.
2606 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2607 Kind = CK_NullToPointer;
2608
Douglas Gregor39c16d42008-10-24 04:54:22 +00002609 return false;
2610}
2611
Sebastian Redl72b597d2009-01-25 19:43:20 +00002612/// IsMemberPointerConversion - Determines whether the conversion of the
2613/// expression From, which has the (possibly adjusted) type FromType, can be
2614/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2615/// If so, returns true and places the converted type (that might differ from
2616/// ToType in its cv-qualifiers at some level) into ConvertedType.
2617bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002619 bool InOverloadResolution,
2620 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002621 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002622 if (!ToTypePtr)
2623 return false;
2624
2625 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002626 if (From->isNullPointerConstant(Context,
2627 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2628 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002629 ConvertedType = ToType;
2630 return true;
2631 }
2632
2633 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002634 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002635 if (!FromTypePtr)
2636 return false;
2637
2638 // A pointer to member of B can be converted to a pointer to member of D,
2639 // where D is derived from B (C++ 4.11p2).
2640 QualType FromClass(FromTypePtr->getClass(), 0);
2641 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002642
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002643 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002644 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002645 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002646 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2647 ToClass.getTypePtr());
2648 return true;
2649 }
2650
2651 return false;
2652}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653
Sebastian Redl72b597d2009-01-25 19:43:20 +00002654/// CheckMemberPointerConversion - Check the member pointer conversion from the
2655/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002656/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002657/// for which IsMemberPointerConversion has already returned true. It returns
2658/// true and produces a diagnostic if there was an error, or returns false
2659/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002660bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002661 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002662 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002663 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002664 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002665 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002666 if (!FromPtrType) {
2667 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002669 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002670 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002671 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002672 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002673 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002674
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002675 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002676 assert(ToPtrType && "No member pointer cast has a target type "
2677 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002678
Sebastian Redled8f2002009-01-28 18:33:18 +00002679 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2680 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002681
Sebastian Redled8f2002009-01-28 18:33:18 +00002682 // FIXME: What about dependent types?
2683 assert(FromClass->isRecordType() && "Pointer into non-class.");
2684 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002685
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002687 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002688 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2689 assert(DerivationOkay &&
2690 "Should not have been called if derivation isn't OK.");
2691 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002692
Sebastian Redled8f2002009-01-28 18:33:18 +00002693 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2694 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002695 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2696 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2697 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2698 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002700
Douglas Gregor89ee6822009-02-28 01:32:25 +00002701 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002702 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2703 << FromClass << ToClass << QualType(VBase, 0)
2704 << From->getSourceRange();
2705 return true;
2706 }
2707
John McCall5b0829a2010-02-10 09:31:12 +00002708 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002709 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2710 Paths.front(),
2711 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002712
Anders Carlssond7923c62009-08-22 23:33:40 +00002713 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002714 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002715 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002716 return false;
2717}
2718
Douglas Gregor9a657932008-10-21 23:43:52 +00002719/// IsQualificationConversion - Determines whether the conversion from
2720/// an rvalue of type FromType to ToType is a qualification conversion
2721/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002722///
2723/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2724/// when the qualification conversion involves a change in the Objective-C
2725/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002726bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002727Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002728 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002729 FromType = Context.getCanonicalType(FromType);
2730 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002731 ObjCLifetimeConversion = false;
2732
Douglas Gregor9a657932008-10-21 23:43:52 +00002733 // If FromType and ToType are the same type, this is not a
2734 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002735 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002737
Douglas Gregor9a657932008-10-21 23:43:52 +00002738 // (C++ 4.4p4):
2739 // A conversion can add cv-qualifiers at levels other than the first
2740 // in multi-level pointers, subject to the following rules: [...]
2741 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002742 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002743 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002744 // Within each iteration of the loop, we check the qualifiers to
2745 // determine if this still looks like a qualification
2746 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002747 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002748 // until there are no more pointers or pointers-to-members left to
2749 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002750 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002751
Douglas Gregor90609aa2011-04-25 18:40:17 +00002752 Qualifiers FromQuals = FromType.getQualifiers();
2753 Qualifiers ToQuals = ToType.getQualifiers();
2754
John McCall31168b02011-06-15 23:02:42 +00002755 // Objective-C ARC:
2756 // Check Objective-C lifetime conversions.
2757 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2758 UnwrappedAnyPointer) {
2759 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2760 ObjCLifetimeConversion = true;
2761 FromQuals.removeObjCLifetime();
2762 ToQuals.removeObjCLifetime();
2763 } else {
2764 // Qualification conversions cannot cast between different
2765 // Objective-C lifetime qualifiers.
2766 return false;
2767 }
2768 }
2769
Douglas Gregorf30053d2011-05-08 06:09:53 +00002770 // Allow addition/removal of GC attributes but not changing GC attributes.
2771 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2772 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2773 FromQuals.removeObjCGCAttr();
2774 ToQuals.removeObjCGCAttr();
2775 }
2776
Douglas Gregor9a657932008-10-21 23:43:52 +00002777 // -- for every j > 0, if const is in cv 1,j then const is in cv
2778 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002779 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002780 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002781
Douglas Gregor9a657932008-10-21 23:43:52 +00002782 // -- if the cv 1,j and cv 2,j are different, then const is in
2783 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002784 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002785 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002786 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Douglas Gregor9a657932008-10-21 23:43:52 +00002788 // Keep track of whether all prior cv-qualifiers in the "to" type
2789 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002790 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002791 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002792 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002793
2794 // We are left with FromType and ToType being the pointee types
2795 // after unwrapping the original FromType and ToType the same number
2796 // of types. If we unwrapped any pointers, and if FromType and
2797 // ToType have the same unqualified type (since we checked
2798 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002799 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002800}
2801
Douglas Gregorc79862f2012-04-12 17:51:55 +00002802/// \brief - Determine whether this is a conversion from a scalar type to an
2803/// atomic type.
2804///
2805/// If successful, updates \c SCS's second and third steps in the conversion
2806/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002807static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2808 bool InOverloadResolution,
2809 StandardConversionSequence &SCS,
2810 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002811 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2812 if (!ToAtomic)
2813 return false;
2814
2815 StandardConversionSequence InnerSCS;
2816 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2817 InOverloadResolution, InnerSCS,
2818 CStyle, /*AllowObjCWritebackConversion=*/false))
2819 return false;
2820
2821 SCS.Second = InnerSCS.Second;
2822 SCS.setToType(1, InnerSCS.getToType(1));
2823 SCS.Third = InnerSCS.Third;
2824 SCS.QualificationIncludesObjCLifetime
2825 = InnerSCS.QualificationIncludesObjCLifetime;
2826 SCS.setToType(2, InnerSCS.getToType(2));
2827 return true;
2828}
2829
Sebastian Redle5417162012-03-27 18:33:03 +00002830static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2831 CXXConstructorDecl *Constructor,
2832 QualType Type) {
2833 const FunctionProtoType *CtorType =
2834 Constructor->getType()->getAs<FunctionProtoType>();
2835 if (CtorType->getNumArgs() > 0) {
2836 QualType FirstArg = CtorType->getArgType(0);
2837 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2838 return true;
2839 }
2840 return false;
2841}
2842
Sebastian Redl82ace982012-02-11 23:51:08 +00002843static OverloadingResult
2844IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2845 CXXRecordDecl *To,
2846 UserDefinedConversionSequence &User,
2847 OverloadCandidateSet &CandidateSet,
2848 bool AllowExplicit) {
2849 DeclContext::lookup_iterator Con, ConEnd;
2850 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2851 Con != ConEnd; ++Con) {
2852 NamedDecl *D = *Con;
2853 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2854
2855 // Find the constructor (which may be a template).
2856 CXXConstructorDecl *Constructor = 0;
2857 FunctionTemplateDecl *ConstructorTmpl
2858 = dyn_cast<FunctionTemplateDecl>(D);
2859 if (ConstructorTmpl)
2860 Constructor
2861 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2862 else
2863 Constructor = cast<CXXConstructorDecl>(D);
2864
2865 bool Usable = !Constructor->isInvalidDecl() &&
2866 S.isInitListConstructor(Constructor) &&
2867 (AllowExplicit || !Constructor->isExplicit());
2868 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002869 // If the first argument is (a reference to) the target type,
2870 // suppress conversions.
2871 bool SuppressUserConversions =
2872 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002873 if (ConstructorTmpl)
2874 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2875 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002876 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002877 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002878 else
2879 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002880 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002881 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002882 }
2883 }
2884
2885 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2886
2887 OverloadCandidateSet::iterator Best;
2888 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2889 case OR_Success: {
2890 // Record the standard conversion we used and the conversion function.
2891 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2892 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2893
2894 QualType ThisType = Constructor->getThisType(S.Context);
2895 // Initializer lists don't have conversions as such.
2896 User.Before.setAsIdentityConversion();
2897 User.HadMultipleCandidates = HadMultipleCandidates;
2898 User.ConversionFunction = Constructor;
2899 User.FoundConversionFunction = Best->FoundDecl;
2900 User.After.setAsIdentityConversion();
2901 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2902 User.After.setAllToTypes(ToType);
2903 return OR_Success;
2904 }
2905
2906 case OR_No_Viable_Function:
2907 return OR_No_Viable_Function;
2908 case OR_Deleted:
2909 return OR_Deleted;
2910 case OR_Ambiguous:
2911 return OR_Ambiguous;
2912 }
2913
2914 llvm_unreachable("Invalid OverloadResult!");
2915}
2916
Douglas Gregor576e98c2009-01-30 23:27:23 +00002917/// Determines whether there is a user-defined conversion sequence
2918/// (C++ [over.ics.user]) that converts expression From to the type
2919/// ToType. If such a conversion exists, User will contain the
2920/// user-defined conversion sequence that performs such a conversion
2921/// and this routine will return true. Otherwise, this routine returns
2922/// false and User is unspecified.
2923///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002924/// \param AllowExplicit true if the conversion should consider C++0x
2925/// "explicit" conversion functions as well as non-explicit conversion
2926/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002927static OverloadingResult
2928IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002929 UserDefinedConversionSequence &User,
2930 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002931 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002932 // Whether we will only visit constructors.
2933 bool ConstructorsOnly = false;
2934
2935 // If the type we are conversion to is a class type, enumerate its
2936 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002937 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002938 // C++ [over.match.ctor]p1:
2939 // When objects of class type are direct-initialized (8.5), or
2940 // copy-initialized from an expression of the same or a
2941 // derived class type (8.5), overload resolution selects the
2942 // constructor. [...] For copy-initialization, the candidate
2943 // functions are all the converting constructors (12.3.1) of
2944 // that class. The argument list is the expression-list within
2945 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002946 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002947 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002948 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002949 ConstructorsOnly = true;
2950
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002951 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002952 // RequireCompleteType may have returned true due to some invalid decl
2953 // during template instantiation, but ToType may be complete enough now
2954 // to try to recover.
2955 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002956 // We're not going to find any constructors.
2957 } else if (CXXRecordDecl *ToRecordDecl
2958 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002959
2960 Expr **Args = &From;
2961 unsigned NumArgs = 1;
2962 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002963 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002964 // But first, see if there is an init-list-contructor that will work.
2965 OverloadingResult Result = IsInitializerListConstructorConversion(
2966 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2967 if (Result != OR_No_Viable_Function)
2968 return Result;
2969 // Never mind.
2970 CandidateSet.clear();
2971
2972 // If we're list-initializing, we pass the individual elements as
2973 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002974 Args = InitList->getInits();
2975 NumArgs = InitList->getNumInits();
2976 ListInitializing = true;
2977 }
2978
Douglas Gregor89ee6822009-02-28 01:32:25 +00002979 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002980 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002981 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002982 NamedDecl *D = *Con;
2983 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2984
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002985 // Find the constructor (which may be a template).
2986 CXXConstructorDecl *Constructor = 0;
2987 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002988 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002989 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002990 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002991 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2992 else
John McCalla0296f72010-03-19 07:35:19 +00002993 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002995 bool Usable = !Constructor->isInvalidDecl();
2996 if (ListInitializing)
2997 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2998 else
2999 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3000 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003001 bool SuppressUserConversions = !ConstructorsOnly;
3002 if (SuppressUserConversions && ListInitializing) {
3003 SuppressUserConversions = false;
3004 if (NumArgs == 1) {
3005 // If the first argument is (a reference to) the target type,
3006 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003007 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3008 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003009 }
3010 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003011 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003012 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3013 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003014 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003015 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003016 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003017 // Allow one user-defined conversion when user specifies a
3018 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003019 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003020 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003021 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003022 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003023 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003024 }
3025 }
3026
Douglas Gregor5ab11652010-04-17 22:01:05 +00003027 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003028 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003029 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003030 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003031 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003032 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003033 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003034 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3035 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00003036 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003037 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003038 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003039 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003040 DeclAccessPair FoundDecl = I.getPair();
3041 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3043 if (isa<UsingShadowDecl>(D))
3044 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3045
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003046 CXXConversionDecl *Conv;
3047 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003048 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003050 else
John McCallda4458e2010-03-31 01:36:47 +00003051 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003052
3053 if (AllowExplicit || !Conv->isExplicit()) {
3054 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003055 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3056 ActingContext, From, ToType,
3057 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003058 else
John McCall5c32be02010-08-24 20:38:10 +00003059 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3060 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003061 }
3062 }
3063 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003064 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003065
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003066 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3067
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003068 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003069 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003070 case OR_Success:
3071 // Record the standard conversion we used and the conversion function.
3072 if (CXXConstructorDecl *Constructor
3073 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003074 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003075
John McCall5c32be02010-08-24 20:38:10 +00003076 // C++ [over.ics.user]p1:
3077 // If the user-defined conversion is specified by a
3078 // constructor (12.3.1), the initial standard conversion
3079 // sequence converts the source type to the type required by
3080 // the argument of the constructor.
3081 //
3082 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003083 if (isa<InitListExpr>(From)) {
3084 // Initializer lists don't have conversions as such.
3085 User.Before.setAsIdentityConversion();
3086 } else {
3087 if (Best->Conversions[0].isEllipsis())
3088 User.EllipsisConversion = true;
3089 else {
3090 User.Before = Best->Conversions[0].Standard;
3091 User.EllipsisConversion = false;
3092 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003093 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003094 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003095 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003096 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003097 User.After.setAsIdentityConversion();
3098 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3099 User.After.setAllToTypes(ToType);
3100 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003101 }
3102 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003103 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003104 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003105
John McCall5c32be02010-08-24 20:38:10 +00003106 // C++ [over.ics.user]p1:
3107 //
3108 // [...] If the user-defined conversion is specified by a
3109 // conversion function (12.3.2), the initial standard
3110 // conversion sequence converts the source type to the
3111 // implicit object parameter of the conversion function.
3112 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003113 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003114 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003115 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003116 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003117
John McCall5c32be02010-08-24 20:38:10 +00003118 // C++ [over.ics.user]p2:
3119 // The second standard conversion sequence converts the
3120 // result of the user-defined conversion to the target type
3121 // for the sequence. Since an implicit conversion sequence
3122 // is an initialization, the special rules for
3123 // initialization by user-defined conversion apply when
3124 // selecting the best user-defined conversion for a
3125 // user-defined conversion sequence (see 13.3.3 and
3126 // 13.3.3.1).
3127 User.After = Best->FinalConversion;
3128 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003129 }
David Blaikie8a40f702012-01-17 06:56:22 +00003130 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003131
John McCall5c32be02010-08-24 20:38:10 +00003132 case OR_No_Viable_Function:
3133 return OR_No_Viable_Function;
3134 case OR_Deleted:
3135 // No conversion here! We're done.
3136 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003137
John McCall5c32be02010-08-24 20:38:10 +00003138 case OR_Ambiguous:
3139 return OR_Ambiguous;
3140 }
3141
David Blaikie8a40f702012-01-17 06:56:22 +00003142 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003143}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003145bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003146Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003147 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003148 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003150 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003151 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003152 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003153 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003154 diag::err_typecheck_ambiguous_condition)
3155 << From->getType() << ToType << From->getSourceRange();
3156 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003157 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003158 diag::err_typecheck_nonviable_condition)
3159 << From->getType() << ToType << From->getSourceRange();
3160 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003161 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003162 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003164}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003165
Douglas Gregor2837aa22012-02-22 17:32:19 +00003166/// \brief Compare the user-defined conversion functions or constructors
3167/// of two user-defined conversion sequences to determine whether any ordering
3168/// is possible.
3169static ImplicitConversionSequence::CompareKind
3170compareConversionFunctions(Sema &S,
3171 FunctionDecl *Function1,
3172 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003173 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003174 return ImplicitConversionSequence::Indistinguishable;
3175
3176 // Objective-C++:
3177 // If both conversion functions are implicitly-declared conversions from
3178 // a lambda closure type to a function pointer and a block pointer,
3179 // respectively, always prefer the conversion to a function pointer,
3180 // because the function pointer is more lightweight and is more likely
3181 // to keep code working.
3182 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3183 if (!Conv1)
3184 return ImplicitConversionSequence::Indistinguishable;
3185
3186 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3187 if (!Conv2)
3188 return ImplicitConversionSequence::Indistinguishable;
3189
3190 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3191 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3192 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3193 if (Block1 != Block2)
3194 return Block1? ImplicitConversionSequence::Worse
3195 : ImplicitConversionSequence::Better;
3196 }
3197
3198 return ImplicitConversionSequence::Indistinguishable;
3199}
3200
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003201/// CompareImplicitConversionSequences - Compare two implicit
3202/// conversion sequences to determine whether one is better than the
3203/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003204static ImplicitConversionSequence::CompareKind
3205CompareImplicitConversionSequences(Sema &S,
3206 const ImplicitConversionSequence& ICS1,
3207 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003208{
3209 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3210 // conversion sequences (as defined in 13.3.3.1)
3211 // -- a standard conversion sequence (13.3.3.1.1) is a better
3212 // conversion sequence than a user-defined conversion sequence or
3213 // an ellipsis conversion sequence, and
3214 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3215 // conversion sequence than an ellipsis conversion sequence
3216 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003217 //
John McCall0d1da222010-01-12 00:44:57 +00003218 // C++0x [over.best.ics]p10:
3219 // For the purpose of ranking implicit conversion sequences as
3220 // described in 13.3.3.2, the ambiguous conversion sequence is
3221 // treated as a user-defined sequence that is indistinguishable
3222 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003223 if (ICS1.getKindRank() < ICS2.getKindRank())
3224 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003225 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003226 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003227
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003228 // The following checks require both conversion sequences to be of
3229 // the same kind.
3230 if (ICS1.getKind() != ICS2.getKind())
3231 return ImplicitConversionSequence::Indistinguishable;
3232
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003233 ImplicitConversionSequence::CompareKind Result =
3234 ImplicitConversionSequence::Indistinguishable;
3235
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003236 // Two implicit conversion sequences of the same form are
3237 // indistinguishable conversion sequences unless one of the
3238 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003239 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003240 Result = CompareStandardConversionSequences(S,
3241 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003242 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003243 // User-defined conversion sequence U1 is a better conversion
3244 // sequence than another user-defined conversion sequence U2 if
3245 // they contain the same user-defined conversion function or
3246 // constructor and if the second standard conversion sequence of
3247 // U1 is better than the second standard conversion sequence of
3248 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003249 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003250 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003251 Result = CompareStandardConversionSequences(S,
3252 ICS1.UserDefined.After,
3253 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003254 else
3255 Result = compareConversionFunctions(S,
3256 ICS1.UserDefined.ConversionFunction,
3257 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003258 }
3259
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003260 // List-initialization sequence L1 is a better conversion sequence than
3261 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3262 // for some X and L2 does not.
3263 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003264 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003265 ICS1.isListInitializationSequence() &&
3266 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003267 if (ICS1.isStdInitializerListElement() &&
3268 !ICS2.isStdInitializerListElement())
3269 return ImplicitConversionSequence::Better;
3270 if (!ICS1.isStdInitializerListElement() &&
3271 ICS2.isStdInitializerListElement())
3272 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003273 }
3274
3275 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003276}
3277
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003278static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3279 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3280 Qualifiers Quals;
3281 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003285 return Context.hasSameUnqualifiedType(T1, T2);
3286}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003288// Per 13.3.3.2p3, compare the given standard conversion sequences to
3289// determine if one is a proper subset of the other.
3290static ImplicitConversionSequence::CompareKind
3291compareStandardConversionSubsets(ASTContext &Context,
3292 const StandardConversionSequence& SCS1,
3293 const StandardConversionSequence& SCS2) {
3294 ImplicitConversionSequence::CompareKind Result
3295 = ImplicitConversionSequence::Indistinguishable;
3296
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003298 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003299 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3300 return ImplicitConversionSequence::Better;
3301 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3302 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003304 if (SCS1.Second != SCS2.Second) {
3305 if (SCS1.Second == ICK_Identity)
3306 Result = ImplicitConversionSequence::Better;
3307 else if (SCS2.Second == ICK_Identity)
3308 Result = ImplicitConversionSequence::Worse;
3309 else
3310 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003311 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003312 return ImplicitConversionSequence::Indistinguishable;
3313
3314 if (SCS1.Third == SCS2.Third) {
3315 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3316 : ImplicitConversionSequence::Indistinguishable;
3317 }
3318
3319 if (SCS1.Third == ICK_Identity)
3320 return Result == ImplicitConversionSequence::Worse
3321 ? ImplicitConversionSequence::Indistinguishable
3322 : ImplicitConversionSequence::Better;
3323
3324 if (SCS2.Third == ICK_Identity)
3325 return Result == ImplicitConversionSequence::Better
3326 ? ImplicitConversionSequence::Indistinguishable
3327 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003329 return ImplicitConversionSequence::Indistinguishable;
3330}
3331
Douglas Gregore696ebb2011-01-26 14:52:12 +00003332/// \brief Determine whether one of the given reference bindings is better
3333/// than the other based on what kind of bindings they are.
3334static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3335 const StandardConversionSequence &SCS2) {
3336 // C++0x [over.ics.rank]p3b4:
3337 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3338 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003340 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003342 // reference*.
3343 //
3344 // FIXME: Rvalue references. We're going rogue with the above edits,
3345 // because the semantics in the current C++0x working paper (N3225 at the
3346 // time of this writing) break the standard definition of std::forward
3347 // and std::reference_wrapper when dealing with references to functions.
3348 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003349 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3350 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
Douglas Gregore696ebb2011-01-26 14:52:12 +00003353 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3354 SCS2.IsLvalueReference) ||
3355 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3356 !SCS2.IsLvalueReference);
3357}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003359/// CompareStandardConversionSequences - Compare two standard
3360/// conversion sequences to determine whether one is better than the
3361/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003362static ImplicitConversionSequence::CompareKind
3363CompareStandardConversionSequences(Sema &S,
3364 const StandardConversionSequence& SCS1,
3365 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003366{
3367 // Standard conversion sequence S1 is a better conversion sequence
3368 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3369
3370 // -- S1 is a proper subsequence of S2 (comparing the conversion
3371 // sequences in the canonical form defined by 13.3.3.1.1,
3372 // excluding any Lvalue Transformation; the identity conversion
3373 // sequence is considered to be a subsequence of any
3374 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003375 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003376 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003377 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378
3379 // -- the rank of S1 is better than the rank of S2 (by the rules
3380 // defined below), or, if not that,
3381 ImplicitConversionRank Rank1 = SCS1.getRank();
3382 ImplicitConversionRank Rank2 = SCS2.getRank();
3383 if (Rank1 < Rank2)
3384 return ImplicitConversionSequence::Better;
3385 else if (Rank2 < Rank1)
3386 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003387
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003388 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3389 // are indistinguishable unless one of the following rules
3390 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003391
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003392 // A conversion that is not a conversion of a pointer, or
3393 // pointer to member, to bool is better than another conversion
3394 // that is such a conversion.
3395 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3396 return SCS2.isPointerConversionToBool()
3397 ? ImplicitConversionSequence::Better
3398 : ImplicitConversionSequence::Worse;
3399
Douglas Gregor5c407d92008-10-23 00:40:37 +00003400 // C++ [over.ics.rank]p4b2:
3401 //
3402 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003403 // conversion of B* to A* is better than conversion of B* to
3404 // void*, and conversion of A* to void* is better than conversion
3405 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003406 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003407 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003408 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003409 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003410 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3411 // Exactly one of the conversion sequences is a conversion to
3412 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003413 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3414 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003415 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3416 // Neither conversion sequence converts to a void pointer; compare
3417 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003418 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003419 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003420 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003421 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3422 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003423 // Both conversion sequences are conversions to void
3424 // pointers. Compare the source types to determine if there's an
3425 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003426 QualType FromType1 = SCS1.getFromType();
3427 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003428
3429 // Adjust the types we're converting from via the array-to-pointer
3430 // conversion, if we need to.
3431 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003432 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003433 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003434 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003435
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003436 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3437 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003438
John McCall5c32be02010-08-24 20:38:10 +00003439 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003440 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003441 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003442 return ImplicitConversionSequence::Worse;
3443
3444 // Objective-C++: If one interface is more specific than the
3445 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003446 const ObjCObjectPointerType* FromObjCPtr1
3447 = FromType1->getAs<ObjCObjectPointerType>();
3448 const ObjCObjectPointerType* FromObjCPtr2
3449 = FromType2->getAs<ObjCObjectPointerType>();
3450 if (FromObjCPtr1 && FromObjCPtr2) {
3451 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3452 FromObjCPtr2);
3453 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3454 FromObjCPtr1);
3455 if (AssignLeft != AssignRight) {
3456 return AssignLeft? ImplicitConversionSequence::Better
3457 : ImplicitConversionSequence::Worse;
3458 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003459 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003460 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003461
3462 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3463 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003464 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003465 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003466 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003467
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003468 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003469 // Check for a better reference binding based on the kind of bindings.
3470 if (isBetterReferenceBindingKind(SCS1, SCS2))
3471 return ImplicitConversionSequence::Better;
3472 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3473 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474
Sebastian Redlb28b4072009-03-22 23:49:27 +00003475 // C++ [over.ics.rank]p3b4:
3476 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3477 // which the references refer are the same type except for
3478 // top-level cv-qualifiers, and the type to which the reference
3479 // initialized by S2 refers is more cv-qualified than the type
3480 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003481 QualType T1 = SCS1.getToType(2);
3482 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003483 T1 = S.Context.getCanonicalType(T1);
3484 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003485 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003486 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3487 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003488 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003489 // Objective-C++ ARC: If the references refer to objects with different
3490 // lifetimes, prefer bindings that don't change lifetime.
3491 if (SCS1.ObjCLifetimeConversionBinding !=
3492 SCS2.ObjCLifetimeConversionBinding) {
3493 return SCS1.ObjCLifetimeConversionBinding
3494 ? ImplicitConversionSequence::Worse
3495 : ImplicitConversionSequence::Better;
3496 }
3497
Chandler Carruth8e543b32010-12-12 08:17:55 +00003498 // If the type is an array type, promote the element qualifiers to the
3499 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003500 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003501 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003502 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003503 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003504 if (T2.isMoreQualifiedThan(T1))
3505 return ImplicitConversionSequence::Better;
3506 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003507 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003508 }
3509 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003510
Francois Pichet08d2fa02011-09-18 21:37:37 +00003511 // In Microsoft mode, prefer an integral conversion to a
3512 // floating-to-integral conversion if the integral conversion
3513 // is between types of the same size.
3514 // For example:
3515 // void f(float);
3516 // void f(int);
3517 // int main {
3518 // long a;
3519 // f(a);
3520 // }
3521 // Here, MSVC will call f(int) instead of generating a compile error
3522 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003524 SCS1.Second == ICK_Integral_Conversion &&
3525 SCS2.Second == ICK_Floating_Integral &&
3526 S.Context.getTypeSize(SCS1.getFromType()) ==
3527 S.Context.getTypeSize(SCS1.getToType(2)))
3528 return ImplicitConversionSequence::Better;
3529
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003530 return ImplicitConversionSequence::Indistinguishable;
3531}
3532
3533/// CompareQualificationConversions - Compares two standard conversion
3534/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003535/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3536ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003537CompareQualificationConversions(Sema &S,
3538 const StandardConversionSequence& SCS1,
3539 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003540 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003541 // -- S1 and S2 differ only in their qualification conversion and
3542 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3543 // cv-qualification signature of type T1 is a proper subset of
3544 // the cv-qualification signature of type T2, and S1 is not the
3545 // deprecated string literal array-to-pointer conversion (4.2).
3546 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3547 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3548 return ImplicitConversionSequence::Indistinguishable;
3549
3550 // FIXME: the example in the standard doesn't use a qualification
3551 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003552 QualType T1 = SCS1.getToType(2);
3553 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003554 T1 = S.Context.getCanonicalType(T1);
3555 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003556 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003557 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3558 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559
3560 // If the types are the same, we won't learn anything by unwrapped
3561 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003562 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003563 return ImplicitConversionSequence::Indistinguishable;
3564
Chandler Carruth607f38e2009-12-29 07:16:59 +00003565 // If the type is an array type, promote the element qualifiers to the type
3566 // for comparison.
3567 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003568 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003569 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003570 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003571
Mike Stump11289f42009-09-09 15:08:12 +00003572 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003573 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003574
3575 // Objective-C++ ARC:
3576 // Prefer qualification conversions not involving a change in lifetime
3577 // to qualification conversions that do not change lifetime.
3578 if (SCS1.QualificationIncludesObjCLifetime !=
3579 SCS2.QualificationIncludesObjCLifetime) {
3580 Result = SCS1.QualificationIncludesObjCLifetime
3581 ? ImplicitConversionSequence::Worse
3582 : ImplicitConversionSequence::Better;
3583 }
3584
John McCall5c32be02010-08-24 20:38:10 +00003585 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003586 // Within each iteration of the loop, we check the qualifiers to
3587 // determine if this still looks like a qualification
3588 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003589 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003590 // until there are no more pointers or pointers-to-members left
3591 // to unwrap. This essentially mimics what
3592 // IsQualificationConversion does, but here we're checking for a
3593 // strict subset of qualifiers.
3594 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3595 // The qualifiers are the same, so this doesn't tell us anything
3596 // about how the sequences rank.
3597 ;
3598 else if (T2.isMoreQualifiedThan(T1)) {
3599 // T1 has fewer qualifiers, so it could be the better sequence.
3600 if (Result == ImplicitConversionSequence::Worse)
3601 // Neither has qualifiers that are a subset of the other's
3602 // qualifiers.
3603 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003605 Result = ImplicitConversionSequence::Better;
3606 } else if (T1.isMoreQualifiedThan(T2)) {
3607 // T2 has fewer qualifiers, so it could be the better sequence.
3608 if (Result == ImplicitConversionSequence::Better)
3609 // Neither has qualifiers that are a subset of the other's
3610 // qualifiers.
3611 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003612
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003613 Result = ImplicitConversionSequence::Worse;
3614 } else {
3615 // Qualifiers are disjoint.
3616 return ImplicitConversionSequence::Indistinguishable;
3617 }
3618
3619 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003620 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003621 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003622 }
3623
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003624 // Check that the winning standard conversion sequence isn't using
3625 // the deprecated string literal array to pointer conversion.
3626 switch (Result) {
3627 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003628 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003629 Result = ImplicitConversionSequence::Indistinguishable;
3630 break;
3631
3632 case ImplicitConversionSequence::Indistinguishable:
3633 break;
3634
3635 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003636 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003637 Result = ImplicitConversionSequence::Indistinguishable;
3638 break;
3639 }
3640
3641 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003642}
3643
Douglas Gregor5c407d92008-10-23 00:40:37 +00003644/// CompareDerivedToBaseConversions - Compares two standard conversion
3645/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003646/// various kinds of derived-to-base conversions (C++
3647/// [over.ics.rank]p4b3). As part of these checks, we also look at
3648/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003649ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003650CompareDerivedToBaseConversions(Sema &S,
3651 const StandardConversionSequence& SCS1,
3652 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003653 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003654 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003655 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003656 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003657
3658 // Adjust the types we're converting from via the array-to-pointer
3659 // conversion, if we need to.
3660 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003661 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003662 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003663 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003664
3665 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003666 FromType1 = S.Context.getCanonicalType(FromType1);
3667 ToType1 = S.Context.getCanonicalType(ToType1);
3668 FromType2 = S.Context.getCanonicalType(FromType2);
3669 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003670
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003671 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003672 //
3673 // If class B is derived directly or indirectly from class A and
3674 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003675 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003676 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003677 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003678 SCS2.Second == ICK_Pointer_Conversion &&
3679 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3680 FromType1->isPointerType() && FromType2->isPointerType() &&
3681 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003682 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003684 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003685 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003686 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003687 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003688 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003689 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003690
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003691 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003692 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003693 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003694 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003695 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003696 return ImplicitConversionSequence::Worse;
3697 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003698
3699 // -- conversion of B* to A* is better than conversion of C* to A*,
3700 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003701 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003702 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003703 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003704 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003705 }
3706 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3707 SCS2.Second == ICK_Pointer_Conversion) {
3708 const ObjCObjectPointerType *FromPtr1
3709 = FromType1->getAs<ObjCObjectPointerType>();
3710 const ObjCObjectPointerType *FromPtr2
3711 = FromType2->getAs<ObjCObjectPointerType>();
3712 const ObjCObjectPointerType *ToPtr1
3713 = ToType1->getAs<ObjCObjectPointerType>();
3714 const ObjCObjectPointerType *ToPtr2
3715 = ToType2->getAs<ObjCObjectPointerType>();
3716
3717 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3718 // Apply the same conversion ranking rules for Objective-C pointer types
3719 // that we do for C++ pointers to class types. However, we employ the
3720 // Objective-C pseudo-subtyping relationship used for assignment of
3721 // Objective-C pointer types.
3722 bool FromAssignLeft
3723 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3724 bool FromAssignRight
3725 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3726 bool ToAssignLeft
3727 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3728 bool ToAssignRight
3729 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3730
3731 // A conversion to an a non-id object pointer type or qualified 'id'
3732 // type is better than a conversion to 'id'.
3733 if (ToPtr1->isObjCIdType() &&
3734 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3735 return ImplicitConversionSequence::Worse;
3736 if (ToPtr2->isObjCIdType() &&
3737 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3738 return ImplicitConversionSequence::Better;
3739
3740 // A conversion to a non-id object pointer type is better than a
3741 // conversion to a qualified 'id' type
3742 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3743 return ImplicitConversionSequence::Worse;
3744 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3745 return ImplicitConversionSequence::Better;
3746
3747 // A conversion to an a non-Class object pointer type or qualified 'Class'
3748 // type is better than a conversion to 'Class'.
3749 if (ToPtr1->isObjCClassType() &&
3750 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3751 return ImplicitConversionSequence::Worse;
3752 if (ToPtr2->isObjCClassType() &&
3753 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3754 return ImplicitConversionSequence::Better;
3755
3756 // A conversion to a non-Class object pointer type is better than a
3757 // conversion to a qualified 'Class' type.
3758 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3759 return ImplicitConversionSequence::Worse;
3760 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3761 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003762
Douglas Gregor058d3de2011-01-31 18:51:41 +00003763 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3764 if (S.Context.hasSameType(FromType1, FromType2) &&
3765 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3766 (ToAssignLeft != ToAssignRight))
3767 return ToAssignLeft? ImplicitConversionSequence::Worse
3768 : ImplicitConversionSequence::Better;
3769
3770 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3771 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3772 (FromAssignLeft != FromAssignRight))
3773 return FromAssignLeft? ImplicitConversionSequence::Better
3774 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003775 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003776 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003777
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003778 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003779 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3780 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3781 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003783 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003785 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003787 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003789 ToType2->getAs<MemberPointerType>();
3790 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3791 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3792 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3793 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3794 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3795 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3796 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3797 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003798 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003799 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003800 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003801 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003802 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003803 return ImplicitConversionSequence::Better;
3804 }
3805 // conversion of B::* to C::* is better than conversion of A::* to C::*
3806 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003807 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003808 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003809 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003810 return ImplicitConversionSequence::Worse;
3811 }
3812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Douglas Gregor5ab11652010-04-17 22:01:05 +00003814 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003815 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003816 // -- binding of an expression of type C to a reference of type
3817 // B& is better than binding an expression of type C to a
3818 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003819 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3820 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3821 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003822 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003823 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003824 return ImplicitConversionSequence::Worse;
3825 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003826
Douglas Gregor2fe98832008-11-03 19:09:14 +00003827 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003828 // -- binding of an expression of type B to a reference of type
3829 // A& is better than binding an expression of type C to a
3830 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003831 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3832 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3833 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003834 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003835 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003836 return ImplicitConversionSequence::Worse;
3837 }
3838 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003839
Douglas Gregor5c407d92008-10-23 00:40:37 +00003840 return ImplicitConversionSequence::Indistinguishable;
3841}
3842
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003843/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3844/// determine whether they are reference-related,
3845/// reference-compatible, reference-compatible with added
3846/// qualification, or incompatible, for use in C++ initialization by
3847/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3848/// type, and the first type (T1) is the pointee type of the reference
3849/// type being initialized.
3850Sema::ReferenceCompareResult
3851Sema::CompareReferenceRelationship(SourceLocation Loc,
3852 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003853 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003854 bool &ObjCConversion,
3855 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003856 assert(!OrigT1->isReferenceType() &&
3857 "T1 must be the pointee type of the reference type");
3858 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3859
3860 QualType T1 = Context.getCanonicalType(OrigT1);
3861 QualType T2 = Context.getCanonicalType(OrigT2);
3862 Qualifiers T1Quals, T2Quals;
3863 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3864 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3865
3866 // C++ [dcl.init.ref]p4:
3867 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3868 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3869 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003870 DerivedToBase = false;
3871 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003872 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003873 if (UnqualT1 == UnqualT2) {
3874 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003875 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003876 IsDerivedFrom(UnqualT2, UnqualT1))
3877 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003878 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3879 UnqualT2->isObjCObjectOrInterfaceType() &&
3880 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3881 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003882 else
3883 return Ref_Incompatible;
3884
3885 // At this point, we know that T1 and T2 are reference-related (at
3886 // least).
3887
3888 // If the type is an array type, promote the element qualifiers to the type
3889 // for comparison.
3890 if (isa<ArrayType>(T1) && T1Quals)
3891 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3892 if (isa<ArrayType>(T2) && T2Quals)
3893 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3894
3895 // C++ [dcl.init.ref]p4:
3896 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3897 // reference-related to T2 and cv1 is the same cv-qualification
3898 // as, or greater cv-qualification than, cv2. For purposes of
3899 // overload resolution, cases for which cv1 is greater
3900 // cv-qualification than cv2 are identified as
3901 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003902 //
3903 // Note that we also require equivalence of Objective-C GC and address-space
3904 // qualifiers when performing these computations, so that e.g., an int in
3905 // address space 1 is not reference-compatible with an int in address
3906 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003907 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3908 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3909 T1Quals.removeObjCLifetime();
3910 T2Quals.removeObjCLifetime();
3911 ObjCLifetimeConversion = true;
3912 }
3913
Douglas Gregord517d552011-04-28 17:56:11 +00003914 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003915 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003916 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003917 return Ref_Compatible_With_Added_Qualification;
3918 else
3919 return Ref_Related;
3920}
3921
Douglas Gregor836a7e82010-08-11 02:15:33 +00003922/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003923/// with DeclType. Return true if something definite is found.
3924static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003925FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3926 QualType DeclType, SourceLocation DeclLoc,
3927 Expr *Init, QualType T2, bool AllowRvalues,
3928 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003929 assert(T2->isRecordType() && "Can only find conversions of record types.");
3930 CXXRecordDecl *T2RecordDecl
3931 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3932
3933 OverloadCandidateSet CandidateSet(DeclLoc);
3934 const UnresolvedSetImpl *Conversions
3935 = T2RecordDecl->getVisibleConversionFunctions();
3936 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3937 E = Conversions->end(); I != E; ++I) {
3938 NamedDecl *D = *I;
3939 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3940 if (isa<UsingShadowDecl>(D))
3941 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3942
3943 FunctionTemplateDecl *ConvTemplate
3944 = dyn_cast<FunctionTemplateDecl>(D);
3945 CXXConversionDecl *Conv;
3946 if (ConvTemplate)
3947 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3948 else
3949 Conv = cast<CXXConversionDecl>(D);
3950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003952 // explicit conversions, skip it.
3953 if (!AllowExplicit && Conv->isExplicit())
3954 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955
Douglas Gregor836a7e82010-08-11 02:15:33 +00003956 if (AllowRvalues) {
3957 bool DerivedToBase = false;
3958 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003959 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003960
3961 // If we are initializing an rvalue reference, don't permit conversion
3962 // functions that return lvalues.
3963 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3964 const ReferenceType *RefType
3965 = Conv->getConversionType()->getAs<LValueReferenceType>();
3966 if (RefType && !RefType->getPointeeType()->isFunctionType())
3967 continue;
3968 }
3969
Douglas Gregor836a7e82010-08-11 02:15:33 +00003970 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003971 S.CompareReferenceRelationship(
3972 DeclLoc,
3973 Conv->getConversionType().getNonReferenceType()
3974 .getUnqualifiedType(),
3975 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003976 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003977 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003978 continue;
3979 } else {
3980 // If the conversion function doesn't return a reference type,
3981 // it can't be considered for this conversion. An rvalue reference
3982 // is only acceptable if its referencee is a function type.
3983
3984 const ReferenceType *RefType =
3985 Conv->getConversionType()->getAs<ReferenceType>();
3986 if (!RefType ||
3987 (!RefType->isLValueReferenceType() &&
3988 !RefType->getPointeeType()->isFunctionType()))
3989 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991
Douglas Gregor836a7e82010-08-11 02:15:33 +00003992 if (ConvTemplate)
3993 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003994 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003995 else
3996 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003997 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003998 }
3999
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004000 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4001
Sebastian Redld92badf2010-06-30 18:13:39 +00004002 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004003 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004004 case OR_Success:
4005 // C++ [over.ics.ref]p1:
4006 //
4007 // [...] If the parameter binds directly to the result of
4008 // applying a conversion function to the argument
4009 // expression, the implicit conversion sequence is a
4010 // user-defined conversion sequence (13.3.3.1.2), with the
4011 // second standard conversion sequence either an identity
4012 // conversion or, if the conversion function returns an
4013 // entity of a type that is a derived class of the parameter
4014 // type, a derived-to-base Conversion.
4015 if (!Best->FinalConversion.DirectBinding)
4016 return false;
4017
Chandler Carruth30141632011-02-25 19:41:05 +00004018 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004019 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004020 ICS.setUserDefined();
4021 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4022 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004023 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004024 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004025 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004026 ICS.UserDefined.EllipsisConversion = false;
4027 assert(ICS.UserDefined.After.ReferenceBinding &&
4028 ICS.UserDefined.After.DirectBinding &&
4029 "Expected a direct reference binding!");
4030 return true;
4031
4032 case OR_Ambiguous:
4033 ICS.setAmbiguous();
4034 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4035 Cand != CandidateSet.end(); ++Cand)
4036 if (Cand->Viable)
4037 ICS.Ambiguous.addConversion(Cand->Function);
4038 return true;
4039
4040 case OR_No_Viable_Function:
4041 case OR_Deleted:
4042 // There was no suitable conversion, or we found a deleted
4043 // conversion; continue with other checks.
4044 return false;
4045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
David Blaikie8a40f702012-01-17 06:56:22 +00004047 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004048}
4049
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004050/// \brief Compute an implicit conversion sequence for reference
4051/// initialization.
4052static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004053TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004054 SourceLocation DeclLoc,
4055 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004056 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004057 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4058
4059 // Most paths end in a failed conversion.
4060 ImplicitConversionSequence ICS;
4061 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4062
4063 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4064 QualType T2 = Init->getType();
4065
4066 // If the initializer is the address of an overloaded function, try
4067 // to resolve the overloaded function. If all goes well, T2 is the
4068 // type of the resulting function.
4069 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4070 DeclAccessPair Found;
4071 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4072 false, Found))
4073 T2 = Fn->getType();
4074 }
4075
4076 // Compute some basic properties of the types and the initializer.
4077 bool isRValRef = DeclType->isRValueReferenceType();
4078 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004079 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004080 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004081 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004082 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004083 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004084 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004085
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004086
Sebastian Redld92badf2010-06-30 18:13:39 +00004087 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004088 // A reference to type "cv1 T1" is initialized by an expression
4089 // of type "cv2 T2" as follows:
4090
Sebastian Redld92badf2010-06-30 18:13:39 +00004091 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004092 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004093 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4094 // reference-compatible with "cv2 T2," or
4095 //
4096 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4097 if (InitCategory.isLValue() &&
4098 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004100 // When a parameter of reference type binds directly (8.5.3)
4101 // to an argument expression, the implicit conversion sequence
4102 // is the identity conversion, unless the argument expression
4103 // has a type that is a derived class of the parameter type,
4104 // in which case the implicit conversion sequence is a
4105 // derived-to-base Conversion (13.3.3.1).
4106 ICS.setStandard();
4107 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004108 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4109 : ObjCConversion? ICK_Compatible_Conversion
4110 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004111 ICS.Standard.Third = ICK_Identity;
4112 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4113 ICS.Standard.setToType(0, T2);
4114 ICS.Standard.setToType(1, T1);
4115 ICS.Standard.setToType(2, T1);
4116 ICS.Standard.ReferenceBinding = true;
4117 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004118 ICS.Standard.IsLvalueReference = !isRValRef;
4119 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4120 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004121 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004122 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004123 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004124
Sebastian Redld92badf2010-06-30 18:13:39 +00004125 // Nothing more to do: the inaccessibility/ambiguity check for
4126 // derived-to-base conversions is suppressed when we're
4127 // computing the implicit conversion sequence (C++
4128 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004129 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004131
Sebastian Redld92badf2010-06-30 18:13:39 +00004132 // -- has a class type (i.e., T2 is a class type), where T1 is
4133 // not reference-related to T2, and can be implicitly
4134 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4135 // is reference-compatible with "cv3 T3" 92) (this
4136 // conversion is selected by enumerating the applicable
4137 // conversion functions (13.3.1.6) and choosing the best
4138 // one through overload resolution (13.3)),
4139 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004142 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4143 Init, T2, /*AllowRvalues=*/false,
4144 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004145 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004146 }
4147 }
4148
Sebastian Redld92badf2010-06-30 18:13:39 +00004149 // -- Otherwise, the reference shall be an lvalue reference to a
4150 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004151 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004153 // We actually handle one oddity of C++ [over.ics.ref] at this
4154 // point, which is that, due to p2 (which short-circuits reference
4155 // binding by only attempting a simple conversion for non-direct
4156 // bindings) and p3's strange wording, we allow a const volatile
4157 // reference to bind to an rvalue. Hence the check for the presence
4158 // of "const" rather than checking for "const" being the only
4159 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004160 // This is also the point where rvalue references and lvalue inits no longer
4161 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004162 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004163 return ICS;
4164
Douglas Gregorf143cd52011-01-24 16:14:37 +00004165 // -- If the initializer expression
4166 //
4167 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004168 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004169 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4170 (InitCategory.isXValue() ||
4171 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4172 (InitCategory.isLValue() && T2->isFunctionType()))) {
4173 ICS.setStandard();
4174 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004176 : ObjCConversion? ICK_Compatible_Conversion
4177 : ICK_Identity;
4178 ICS.Standard.Third = ICK_Identity;
4179 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4180 ICS.Standard.setToType(0, T2);
4181 ICS.Standard.setToType(1, T1);
4182 ICS.Standard.setToType(2, T1);
4183 ICS.Standard.ReferenceBinding = true;
4184 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4185 // binding unless we're binding to a class prvalue.
4186 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4187 // allow the use of rvalue references in C++98/03 for the benefit of
4188 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004190 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004191 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004192 ICS.Standard.IsLvalueReference = !isRValRef;
4193 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004195 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004196 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004197 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregorf143cd52011-01-24 16:14:37 +00004201 // -- has a class type (i.e., T2 is a class type), where T1 is not
4202 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 // an xvalue, class prvalue, or function lvalue of type
4204 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004205 // "cv3 T3",
4206 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004208 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004210 // class subobject).
4211 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004213 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4214 Init, T2, /*AllowRvalues=*/true,
4215 AllowExplicit)) {
4216 // In the second case, if the reference is an rvalue reference
4217 // and the second standard conversion sequence of the
4218 // user-defined conversion sequence includes an lvalue-to-rvalue
4219 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004221 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4222 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4223
Douglas Gregor95273c32011-01-21 16:36:05 +00004224 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227 // -- Otherwise, a temporary of type "cv1 T1" is created and
4228 // initialized from the initializer expression using the
4229 // rules for a non-reference copy initialization (8.5). The
4230 // reference is then bound to the temporary. If T1 is
4231 // reference-related to T2, cv1 must be the same
4232 // cv-qualification as, or greater cv-qualification than,
4233 // cv2; otherwise, the program is ill-formed.
4234 if (RefRelationship == Sema::Ref_Related) {
4235 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4236 // we would be reference-compatible or reference-compatible with
4237 // added qualification. But that wasn't the case, so the reference
4238 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004239 //
4240 // Note that we only want to check address spaces and cvr-qualifiers here.
4241 // ObjC GC and lifetime qualifiers aren't important.
4242 Qualifiers T1Quals = T1.getQualifiers();
4243 Qualifiers T2Quals = T2.getQualifiers();
4244 T1Quals.removeObjCGCAttr();
4245 T1Quals.removeObjCLifetime();
4246 T2Quals.removeObjCGCAttr();
4247 T2Quals.removeObjCLifetime();
4248 if (!T1Quals.compatiblyIncludes(T2Quals))
4249 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004250 }
4251
4252 // If at least one of the types is a class type, the types are not
4253 // related, and we aren't allowed any user conversions, the
4254 // reference binding fails. This case is important for breaking
4255 // recursion, since TryImplicitConversion below will attempt to
4256 // create a temporary through the use of a copy constructor.
4257 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4258 (T1->isRecordType() || T2->isRecordType()))
4259 return ICS;
4260
Douglas Gregorcba72b12011-01-21 05:18:22 +00004261 // If T1 is reference-related to T2 and the reference is an rvalue
4262 // reference, the initializer expression shall not be an lvalue.
4263 if (RefRelationship >= Sema::Ref_Related &&
4264 isRValRef && Init->Classify(S.Context).isLValue())
4265 return ICS;
4266
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004267 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004268 // When a parameter of reference type is not bound directly to
4269 // an argument expression, the conversion sequence is the one
4270 // required to convert the argument expression to the
4271 // underlying type of the reference according to
4272 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4273 // to copy-initializing a temporary of the underlying type with
4274 // the argument expression. Any difference in top-level
4275 // cv-qualification is subsumed by the initialization itself
4276 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004277 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4278 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004279 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004280 /*CStyle=*/false,
4281 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004282
4283 // Of course, that's still a reference binding.
4284 if (ICS.isStandard()) {
4285 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004286 ICS.Standard.IsLvalueReference = !isRValRef;
4287 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4288 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004289 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004290 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004291 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004292 // Don't allow rvalue references to bind to lvalues.
4293 if (DeclType->isRValueReferenceType()) {
4294 if (const ReferenceType *RefType
4295 = ICS.UserDefined.ConversionFunction->getResultType()
4296 ->getAs<LValueReferenceType>()) {
4297 if (!RefType->getPointeeType()->isFunctionType()) {
4298 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4299 DeclType);
4300 return ICS;
4301 }
4302 }
4303 }
4304
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004305 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004306 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4307 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4308 ICS.UserDefined.After.BindsToRvalue = true;
4309 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4310 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004311 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004312
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004313 return ICS;
4314}
4315
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004316static ImplicitConversionSequence
4317TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4318 bool SuppressUserConversions,
4319 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004320 bool AllowObjCWritebackConversion,
4321 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004322
4323/// TryListConversion - Try to copy-initialize a value of type ToType from the
4324/// initializer list From.
4325static ImplicitConversionSequence
4326TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4327 bool SuppressUserConversions,
4328 bool InOverloadResolution,
4329 bool AllowObjCWritebackConversion) {
4330 // C++11 [over.ics.list]p1:
4331 // When an argument is an initializer list, it is not an expression and
4332 // special rules apply for converting it to a parameter type.
4333
4334 ImplicitConversionSequence Result;
4335 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004336 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004337
Sebastian Redl09edce02012-01-23 22:09:39 +00004338 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004339 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004340 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004341 return Result;
4342
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004343 // C++11 [over.ics.list]p2:
4344 // If the parameter type is std::initializer_list<X> or "array of X" and
4345 // all the elements can be implicitly converted to X, the implicit
4346 // conversion sequence is the worst conversion necessary to convert an
4347 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004348 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004349 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004350 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004351 X = S.Context.getBaseElementType(ToType);
4352 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004353 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004354 if (!X.isNull()) {
4355 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4356 Expr *Init = From->getInit(i);
4357 ImplicitConversionSequence ICS =
4358 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4359 InOverloadResolution,
4360 AllowObjCWritebackConversion);
4361 // If a single element isn't convertible, fail.
4362 if (ICS.isBad()) {
4363 Result = ICS;
4364 break;
4365 }
4366 // Otherwise, look for the worst conversion.
4367 if (Result.isBad() ||
4368 CompareImplicitConversionSequences(S, ICS, Result) ==
4369 ImplicitConversionSequence::Worse)
4370 Result = ICS;
4371 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004372
4373 // For an empty list, we won't have computed any conversion sequence.
4374 // Introduce the identity conversion sequence.
4375 if (From->getNumInits() == 0) {
4376 Result.setStandard();
4377 Result.Standard.setAsIdentityConversion();
4378 Result.Standard.setFromType(ToType);
4379 Result.Standard.setAllToTypes(ToType);
4380 }
4381
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004382 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004383 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004384 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004385 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004386
4387 // C++11 [over.ics.list]p3:
4388 // Otherwise, if the parameter is a non-aggregate class X and overload
4389 // resolution chooses a single best constructor [...] the implicit
4390 // conversion sequence is a user-defined conversion sequence. If multiple
4391 // constructors are viable but none is better than the others, the
4392 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004393 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4394 // This function can deal with initializer lists.
4395 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4396 /*AllowExplicit=*/false,
4397 InOverloadResolution, /*CStyle=*/false,
4398 AllowObjCWritebackConversion);
4399 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004400 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004401 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004402
4403 // C++11 [over.ics.list]p4:
4404 // Otherwise, if the parameter has an aggregate type which can be
4405 // initialized from the initializer list [...] the implicit conversion
4406 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004407 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004408 // Type is an aggregate, argument is an init list. At this point it comes
4409 // down to checking whether the initialization works.
4410 // FIXME: Find out whether this parameter is consumed or not.
4411 InitializedEntity Entity =
4412 InitializedEntity::InitializeParameter(S.Context, ToType,
4413 /*Consumed=*/false);
4414 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4415 Result.setUserDefined();
4416 Result.UserDefined.Before.setAsIdentityConversion();
4417 // Initializer lists don't have a type.
4418 Result.UserDefined.Before.setFromType(QualType());
4419 Result.UserDefined.Before.setAllToTypes(QualType());
4420
4421 Result.UserDefined.After.setAsIdentityConversion();
4422 Result.UserDefined.After.setFromType(ToType);
4423 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004424 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004425 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004426 return Result;
4427 }
4428
4429 // C++11 [over.ics.list]p5:
4430 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004431 if (ToType->isReferenceType()) {
4432 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4433 // mention initializer lists in any way. So we go by what list-
4434 // initialization would do and try to extrapolate from that.
4435
4436 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4437
4438 // If the initializer list has a single element that is reference-related
4439 // to the parameter type, we initialize the reference from that.
4440 if (From->getNumInits() == 1) {
4441 Expr *Init = From->getInit(0);
4442
4443 QualType T2 = Init->getType();
4444
4445 // If the initializer is the address of an overloaded function, try
4446 // to resolve the overloaded function. If all goes well, T2 is the
4447 // type of the resulting function.
4448 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4449 DeclAccessPair Found;
4450 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4451 Init, ToType, false, Found))
4452 T2 = Fn->getType();
4453 }
4454
4455 // Compute some basic properties of the types and the initializer.
4456 bool dummy1 = false;
4457 bool dummy2 = false;
4458 bool dummy3 = false;
4459 Sema::ReferenceCompareResult RefRelationship
4460 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4461 dummy2, dummy3);
4462
4463 if (RefRelationship >= Sema::Ref_Related)
4464 return TryReferenceInit(S, Init, ToType,
4465 /*FIXME:*/From->getLocStart(),
4466 SuppressUserConversions,
4467 /*AllowExplicit=*/false);
4468 }
4469
4470 // Otherwise, we bind the reference to a temporary created from the
4471 // initializer list.
4472 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4473 InOverloadResolution,
4474 AllowObjCWritebackConversion);
4475 if (Result.isFailure())
4476 return Result;
4477 assert(!Result.isEllipsis() &&
4478 "Sub-initialization cannot result in ellipsis conversion.");
4479
4480 // Can we even bind to a temporary?
4481 if (ToType->isRValueReferenceType() ||
4482 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4483 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4484 Result.UserDefined.After;
4485 SCS.ReferenceBinding = true;
4486 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4487 SCS.BindsToRvalue = true;
4488 SCS.BindsToFunctionLvalue = false;
4489 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4490 SCS.ObjCLifetimeConversionBinding = false;
4491 } else
4492 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4493 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004494 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004495 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004496
4497 // C++11 [over.ics.list]p6:
4498 // Otherwise, if the parameter type is not a class:
4499 if (!ToType->isRecordType()) {
4500 // - if the initializer list has one element, the implicit conversion
4501 // sequence is the one required to convert the element to the
4502 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004503 unsigned NumInits = From->getNumInits();
4504 if (NumInits == 1)
4505 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4506 SuppressUserConversions,
4507 InOverloadResolution,
4508 AllowObjCWritebackConversion);
4509 // - if the initializer list has no elements, the implicit conversion
4510 // sequence is the identity conversion.
4511 else if (NumInits == 0) {
4512 Result.setStandard();
4513 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004514 Result.Standard.setFromType(ToType);
4515 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004516 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004517 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004518 return Result;
4519 }
4520
4521 // C++11 [over.ics.list]p7:
4522 // In all cases other than those enumerated above, no conversion is possible
4523 return Result;
4524}
4525
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004526/// TryCopyInitialization - Try to copy-initialize a value of type
4527/// ToType from the expression From. Return the implicit conversion
4528/// sequence required to pass this argument, which may be a bad
4529/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004530/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004531/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004532static ImplicitConversionSequence
4533TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004535 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004536 bool AllowObjCWritebackConversion,
4537 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004538 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4539 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4540 InOverloadResolution,AllowObjCWritebackConversion);
4541
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004542 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004543 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004544 /*FIXME:*/From->getLocStart(),
4545 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004546 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004547
John McCall5c32be02010-08-24 20:38:10 +00004548 return TryImplicitConversion(S, From, ToType,
4549 SuppressUserConversions,
4550 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004551 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004552 /*CStyle=*/false,
4553 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004554}
4555
Anna Zaks1b068122011-07-28 19:46:48 +00004556static bool TryCopyInitialization(const CanQualType FromQTy,
4557 const CanQualType ToQTy,
4558 Sema &S,
4559 SourceLocation Loc,
4560 ExprValueKind FromVK) {
4561 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4562 ImplicitConversionSequence ICS =
4563 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4564
4565 return !ICS.isBad();
4566}
4567
Douglas Gregor436424c2008-11-18 23:14:02 +00004568/// TryObjectArgumentInitialization - Try to initialize the object
4569/// parameter of the given member function (@c Method) from the
4570/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004571static ImplicitConversionSequence
4572TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004573 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004574 CXXMethodDecl *Method,
4575 CXXRecordDecl *ActingContext) {
4576 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004577 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4578 // const volatile object.
4579 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4580 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004581 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004582
4583 // Set up the conversion sequence as a "bad" conversion, to allow us
4584 // to exit early.
4585 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004586
4587 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004588 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004589 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004590 FromType = PT->getPointeeType();
4591
Douglas Gregor02824322011-01-26 19:30:28 +00004592 // When we had a pointer, it's implicitly dereferenced, so we
4593 // better have an lvalue.
4594 assert(FromClassification.isLValue());
4595 }
4596
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004597 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004598
Douglas Gregor02824322011-01-26 19:30:28 +00004599 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004601 // parameter is
4602 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004603 // - "lvalue reference to cv X" for functions declared without a
4604 // ref-qualifier or with the & ref-qualifier
4605 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004606 // ref-qualifier
4607 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004609 // cv-qualification on the member function declaration.
4610 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004612 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004613 // (C++ [over.match.funcs]p5). We perform a simplified version of
4614 // reference binding here, that allows class rvalues to bind to
4615 // non-constant references.
4616
Douglas Gregor02824322011-01-26 19:30:28 +00004617 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004618 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004620 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004621 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004622 ICS.setBad(BadConversionSequence::bad_qualifiers,
4623 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004624 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004625 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004626
4627 // Check that we have either the same type or a derived type. It
4628 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004629 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004630 ImplicitConversionKind SecondKind;
4631 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4632 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004633 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004634 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004635 else {
John McCall65eb8792010-02-25 01:37:24 +00004636 ICS.setBad(BadConversionSequence::unrelated_class,
4637 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004638 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004639 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004640
Douglas Gregor02824322011-01-26 19:30:28 +00004641 // Check the ref-qualifier.
4642 switch (Method->getRefQualifier()) {
4643 case RQ_None:
4644 // Do nothing; we don't care about lvalueness or rvalueness.
4645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
Douglas Gregor02824322011-01-26 19:30:28 +00004647 case RQ_LValue:
4648 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4649 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004651 ImplicitParamType);
4652 return ICS;
4653 }
4654 break;
4655
4656 case RQ_RValue:
4657 if (!FromClassification.isRValue()) {
4658 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004660 ImplicitParamType);
4661 return ICS;
4662 }
4663 break;
4664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665
Douglas Gregor436424c2008-11-18 23:14:02 +00004666 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004667 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004668 ICS.Standard.setAsIdentityConversion();
4669 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004670 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004671 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004672 ICS.Standard.ReferenceBinding = true;
4673 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004675 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004676 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4677 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4678 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004679 return ICS;
4680}
4681
4682/// PerformObjectArgumentInitialization - Perform initialization of
4683/// the implicit object parameter for the given Method with the given
4684/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004685ExprResult
4686Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004688 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004689 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004690 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004691 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004692 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004693
Douglas Gregor02824322011-01-26 19:30:28 +00004694 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004695 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004696 FromRecordType = PT->getPointeeType();
4697 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004698 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004699 } else {
4700 FromRecordType = From->getType();
4701 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004702 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004703 }
4704
John McCall6e9f8f62009-12-03 04:06:58 +00004705 // Note that we always use the true parent context when performing
4706 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004707 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004708 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4709 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004710 if (ICS.isBad()) {
4711 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4712 Qualifiers FromQs = FromRecordType.getQualifiers();
4713 Qualifiers ToQs = DestType.getQualifiers();
4714 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4715 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004716 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004717 diag::err_member_function_call_bad_cvr)
4718 << Method->getDeclName() << FromRecordType << (CVR - 1)
4719 << From->getSourceRange();
4720 Diag(Method->getLocation(), diag::note_previous_decl)
4721 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004722 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004723 }
4724 }
4725
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004726 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004727 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004728 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
John Wiegley01296292011-04-08 18:41:53 +00004731 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4732 ExprResult FromRes =
4733 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4734 if (FromRes.isInvalid())
4735 return ExprError();
4736 From = FromRes.take();
4737 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004738
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004739 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004740 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004741 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004742 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004743}
4744
Douglas Gregor5fb53972009-01-14 15:45:31 +00004745/// TryContextuallyConvertToBool - Attempt to contextually convert the
4746/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004747static ImplicitConversionSequence
4748TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004749 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004750 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004751 // FIXME: Are these flags correct?
4752 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004753 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004754 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004755 /*CStyle=*/false,
4756 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004757}
4758
4759/// PerformContextuallyConvertToBool - Perform a contextual conversion
4760/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004761ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004762 if (checkPlaceholderForOverload(*this, From))
4763 return ExprError();
4764
John McCall5c32be02010-08-24 20:38:10 +00004765 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004766 if (!ICS.isBad())
4767 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Fariborz Jahanian76197412009-11-18 18:26:29 +00004769 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004770 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004771 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004772 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004773 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004774}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Richard Smithf8379a02012-01-18 23:55:52 +00004776/// Check that the specified conversion is permitted in a converted constant
4777/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4778/// is acceptable.
4779static bool CheckConvertedConstantConversions(Sema &S,
4780 StandardConversionSequence &SCS) {
4781 // Since we know that the target type is an integral or unscoped enumeration
4782 // type, most conversion kinds are impossible. All possible First and Third
4783 // conversions are fine.
4784 switch (SCS.Second) {
4785 case ICK_Identity:
4786 case ICK_Integral_Promotion:
4787 case ICK_Integral_Conversion:
4788 return true;
4789
4790 case ICK_Boolean_Conversion:
4791 // Conversion from an integral or unscoped enumeration type to bool is
4792 // classified as ICK_Boolean_Conversion, but it's also an integral
4793 // conversion, so it's permitted in a converted constant expression.
4794 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4795 SCS.getToType(2)->isBooleanType();
4796
4797 case ICK_Floating_Integral:
4798 case ICK_Complex_Real:
4799 return false;
4800
4801 case ICK_Lvalue_To_Rvalue:
4802 case ICK_Array_To_Pointer:
4803 case ICK_Function_To_Pointer:
4804 case ICK_NoReturn_Adjustment:
4805 case ICK_Qualification:
4806 case ICK_Compatible_Conversion:
4807 case ICK_Vector_Conversion:
4808 case ICK_Vector_Splat:
4809 case ICK_Derived_To_Base:
4810 case ICK_Pointer_Conversion:
4811 case ICK_Pointer_Member:
4812 case ICK_Block_Pointer_Conversion:
4813 case ICK_Writeback_Conversion:
4814 case ICK_Floating_Promotion:
4815 case ICK_Complex_Promotion:
4816 case ICK_Complex_Conversion:
4817 case ICK_Floating_Conversion:
4818 case ICK_TransparentUnionConversion:
4819 llvm_unreachable("unexpected second conversion kind");
4820
4821 case ICK_Num_Conversion_Kinds:
4822 break;
4823 }
4824
4825 llvm_unreachable("unknown conversion kind");
4826}
4827
4828/// CheckConvertedConstantExpression - Check that the expression From is a
4829/// converted constant expression of type T, perform the conversion and produce
4830/// the converted expression, per C++11 [expr.const]p3.
4831ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4832 llvm::APSInt &Value,
4833 CCEKind CCE) {
4834 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4835 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4836
4837 if (checkPlaceholderForOverload(*this, From))
4838 return ExprError();
4839
4840 // C++11 [expr.const]p3 with proposed wording fixes:
4841 // A converted constant expression of type T is a core constant expression,
4842 // implicitly converted to a prvalue of type T, where the converted
4843 // expression is a literal constant expression and the implicit conversion
4844 // sequence contains only user-defined conversions, lvalue-to-rvalue
4845 // conversions, integral promotions, and integral conversions other than
4846 // narrowing conversions.
4847 ImplicitConversionSequence ICS =
4848 TryImplicitConversion(From, T,
4849 /*SuppressUserConversions=*/false,
4850 /*AllowExplicit=*/false,
4851 /*InOverloadResolution=*/false,
4852 /*CStyle=*/false,
4853 /*AllowObjcWritebackConversion=*/false);
4854 StandardConversionSequence *SCS = 0;
4855 switch (ICS.getKind()) {
4856 case ImplicitConversionSequence::StandardConversion:
4857 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004858 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004859 diag::err_typecheck_converted_constant_expression_disallowed)
4860 << From->getType() << From->getSourceRange() << T;
4861 SCS = &ICS.Standard;
4862 break;
4863 case ImplicitConversionSequence::UserDefinedConversion:
4864 // We are converting from class type to an integral or enumeration type, so
4865 // the Before sequence must be trivial.
4866 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004867 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004868 diag::err_typecheck_converted_constant_expression_disallowed)
4869 << From->getType() << From->getSourceRange() << T;
4870 SCS = &ICS.UserDefined.After;
4871 break;
4872 case ImplicitConversionSequence::AmbiguousConversion:
4873 case ImplicitConversionSequence::BadConversion:
4874 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004875 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004876 diag::err_typecheck_converted_constant_expression)
4877 << From->getType() << From->getSourceRange() << T;
4878 return ExprError();
4879
4880 case ImplicitConversionSequence::EllipsisConversion:
4881 llvm_unreachable("ellipsis conversion in converted constant expression");
4882 }
4883
4884 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4885 if (Result.isInvalid())
4886 return Result;
4887
4888 // Check for a narrowing implicit conversion.
4889 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004890 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004891 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4892 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004893 case NK_Variable_Narrowing:
4894 // Implicit conversion to a narrower type, and the value is not a constant
4895 // expression. We'll diagnose this in a moment.
4896 case NK_Not_Narrowing:
4897 break;
4898
4899 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004900 Diag(From->getLocStart(),
4901 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4902 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004903 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004904 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004905 break;
4906
4907 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004908 Diag(From->getLocStart(),
4909 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4910 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004911 << CCE << /*Constant*/0 << From->getType() << T;
4912 break;
4913 }
4914
4915 // Check the expression is a constant expression.
4916 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4917 Expr::EvalResult Eval;
4918 Eval.Diag = &Notes;
4919
4920 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4921 // The expression can't be folded, so we can't keep it at this position in
4922 // the AST.
4923 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004924 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004925 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004926
4927 if (Notes.empty()) {
4928 // It's a constant expression.
4929 return Result;
4930 }
Richard Smithf8379a02012-01-18 23:55:52 +00004931 }
4932
4933 // It's not a constant expression. Produce an appropriate diagnostic.
4934 if (Notes.size() == 1 &&
4935 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4936 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4937 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004938 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004939 << CCE << From->getSourceRange();
4940 for (unsigned I = 0; I < Notes.size(); ++I)
4941 Diag(Notes[I].first, Notes[I].second);
4942 }
Richard Smith911e1422012-01-30 22:27:01 +00004943 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004944}
4945
John McCallfec112d2011-09-09 06:11:02 +00004946/// dropPointerConversions - If the given standard conversion sequence
4947/// involves any pointer conversions, remove them. This may change
4948/// the result type of the conversion sequence.
4949static void dropPointerConversion(StandardConversionSequence &SCS) {
4950 if (SCS.Second == ICK_Pointer_Conversion) {
4951 SCS.Second = ICK_Identity;
4952 SCS.Third = ICK_Identity;
4953 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4954 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004955}
John McCall5c32be02010-08-24 20:38:10 +00004956
John McCallfec112d2011-09-09 06:11:02 +00004957/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4958/// convert the expression From to an Objective-C pointer type.
4959static ImplicitConversionSequence
4960TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4961 // Do an implicit conversion to 'id'.
4962 QualType Ty = S.Context.getObjCIdType();
4963 ImplicitConversionSequence ICS
4964 = TryImplicitConversion(S, From, Ty,
4965 // FIXME: Are these flags correct?
4966 /*SuppressUserConversions=*/false,
4967 /*AllowExplicit=*/true,
4968 /*InOverloadResolution=*/false,
4969 /*CStyle=*/false,
4970 /*AllowObjCWritebackConversion=*/false);
4971
4972 // Strip off any final conversions to 'id'.
4973 switch (ICS.getKind()) {
4974 case ImplicitConversionSequence::BadConversion:
4975 case ImplicitConversionSequence::AmbiguousConversion:
4976 case ImplicitConversionSequence::EllipsisConversion:
4977 break;
4978
4979 case ImplicitConversionSequence::UserDefinedConversion:
4980 dropPointerConversion(ICS.UserDefined.After);
4981 break;
4982
4983 case ImplicitConversionSequence::StandardConversion:
4984 dropPointerConversion(ICS.Standard);
4985 break;
4986 }
4987
4988 return ICS;
4989}
4990
4991/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4992/// conversion of the expression From to an Objective-C pointer type.
4993ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004994 if (checkPlaceholderForOverload(*this, From))
4995 return ExprError();
4996
John McCall8b07ec22010-05-15 11:32:37 +00004997 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004998 ImplicitConversionSequence ICS =
4999 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005000 if (!ICS.isBad())
5001 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005002 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005003}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005004
Richard Smith8dd34252012-02-04 07:07:42 +00005005/// Determine whether the provided type is an integral type, or an enumeration
5006/// type of a permitted flavor.
5007static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5008 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5009 : T->isIntegralOrUnscopedEnumerationType();
5010}
5011
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005013/// enumeration type.
5014///
5015/// This routine will attempt to convert an expression of class type to an
5016/// integral or enumeration type, if that class type only has a single
5017/// conversion to an integral or enumeration type.
5018///
Douglas Gregor4799d032010-06-30 00:20:43 +00005019/// \param Loc The source location of the construct that requires the
5020/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005021///
Douglas Gregor4799d032010-06-30 00:20:43 +00005022/// \param FromE The expression we're converting from.
5023///
5024/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5025/// have integral or enumeration type.
5026///
5027/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5028/// incomplete class type.
5029///
5030/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5031/// explicit conversion function (because no implicit conversion functions
5032/// were available). This is a recovery mode.
5033///
5034/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5035/// showing which conversion was picked.
5036///
5037/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5038/// conversion function that could convert to integral or enumeration type.
5039///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00005041/// usable conversion function.
5042///
5043/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5044/// function, which may be an extension in this case.
5045///
Richard Smith8dd34252012-02-04 07:07:42 +00005046/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5047/// enumerations should be considered.
5048///
Douglas Gregor4799d032010-06-30 00:20:43 +00005049/// \returns The expression, converted to an integral or enumeration type if
5050/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051ExprResult
John McCallb268a282010-08-23 23:25:46 +00005052Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005053 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005054 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005055 // We can't perform any more checking for type-dependent expressions.
5056 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005057 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Eli Friedman1da70392012-01-26 00:26:18 +00005059 // Process placeholders immediately.
5060 if (From->hasPlaceholderType()) {
5061 ExprResult result = CheckPlaceholderExpr(From);
5062 if (result.isInvalid()) return result;
5063 From = result.take();
5064 }
5065
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005066 // If the expression already has integral or enumeration type, we're golden.
5067 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005068 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005069 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005070
5071 // FIXME: Check for missing '()' if T is a function type?
5072
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 // 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 +00005074 // expression of integral or enumeration type.
5075 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005076 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005077 if (!Diagnoser.Suppress)
5078 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005079 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005082 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005083 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005084 ICEConvertDiagnoser &Diagnoser;
5085 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005086
Douglas Gregore2b37442012-05-04 22:38:52 +00005087 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5088 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005089
5090 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005091 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005092 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005093 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005094
5095 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005096 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005098 // Look for a conversion to an integral or enumeration type.
5099 UnresolvedSet<4> ViableConversions;
5100 UnresolvedSet<4> ExplicitConversions;
5101 const UnresolvedSetImpl *Conversions
5102 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005104 bool HadMultipleCandidates = (Conversions->size() > 1);
5105
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107 E = Conversions->end();
5108 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005109 ++I) {
5110 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005111 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5112 if (isIntegralOrEnumerationType(
5113 Conversion->getConversionType().getNonReferenceType(),
5114 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005115 if (Conversion->isExplicit())
5116 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5117 else
5118 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5119 }
Richard Smith8dd34252012-02-04 07:07:42 +00005120 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005123 switch (ViableConversions.size()) {
5124 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005125 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005126 DeclAccessPair Found = ExplicitConversions[0];
5127 CXXConversionDecl *Conversion
5128 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005130 // The user probably meant to invoke the given explicit
5131 // conversion; use it.
5132 QualType ConvTy
5133 = Conversion->getConversionType().getNonReferenceType();
5134 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005135 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136
Douglas Gregore2b37442012-05-04 22:38:52 +00005137 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005138 << FixItHint::CreateInsertion(From->getLocStart(),
5139 "static_cast<" + TypeStr + ">(")
5140 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5141 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005142 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
5144 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005145 // explicit conversion function.
5146 if (isSFINAEContext())
5147 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005148
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005149 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005150 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5151 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005152 if (Result.isInvalid())
5153 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005154 // Record usage of conversion in an implicit cast.
5155 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5156 CK_UserDefinedConversion,
5157 Result.get(), 0,
5158 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005161 // We'll complain below about a non-integral condition type.
5162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005164 case 1: {
5165 // Apply this conversion.
5166 DeclAccessPair Found = ViableConversions[0];
5167 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregor4799d032010-06-30 00:20:43 +00005169 CXXConversionDecl *Conversion
5170 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5171 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005173 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005174 if (isSFINAEContext())
5175 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176
Douglas Gregore2b37442012-05-04 22:38:52 +00005177 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5178 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005180
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005181 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5182 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005183 if (Result.isInvalid())
5184 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005185 // Record usage of conversion in an implicit cast.
5186 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5187 CK_UserDefinedConversion,
5188 Result.get(), 0,
5189 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005190 break;
5191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005192
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005193 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005194 if (Diagnoser.Suppress)
5195 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005196
Douglas Gregore2b37442012-05-04 22:38:52 +00005197 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005198 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5199 CXXConversionDecl *Conv
5200 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5201 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005202 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005203 }
John McCallb268a282010-08-23 23:25:46 +00005204 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Richard Smithf4c51d92012-02-04 09:53:13 +00005207 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005208 !Diagnoser.Suppress) {
5209 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5210 << From->getSourceRange();
5211 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005212
Eli Friedman1da70392012-01-26 00:26:18 +00005213 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005214}
5215
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005216/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005217/// candidate functions, using the given function call arguments. If
5218/// @p SuppressUserConversions, then don't allow user-defined
5219/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005220///
James Dennett2a4d13c2012-06-15 07:13:21 +00005221/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005222/// based on an incomplete set of function arguments. This feature is used by
5223/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005224void
5225Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005226 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005227 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005228 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005229 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005230 bool PartialOverloading,
5231 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005232 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005233 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005234 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005235 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005236 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005237
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005238 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005239 if (!isa<CXXConstructorDecl>(Method)) {
5240 // If we get here, it's because we're calling a member function
5241 // that is named without a member access expression (e.g.,
5242 // "this->f") that was either written explicitly or created
5243 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005244 // function, e.g., X::f(). We use an empty type for the implied
5245 // object argument (C++ [over.call.func]p3), and the acting context
5246 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005247 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005248 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005249 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005250 return;
5251 }
5252 // We treat a constructor like a non-member function, since its object
5253 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005254 }
5255
Douglas Gregorff7028a2009-11-13 23:59:09 +00005256 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005257 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005258
Douglas Gregor27381f32009-11-23 12:27:39 +00005259 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005260 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005261
Douglas Gregorffe14e32009-11-14 01:20:54 +00005262 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5263 // C++ [class.copy]p3:
5264 // A member function template is never instantiated to perform the copy
5265 // of a class object to an object of its class type.
5266 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005267 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005268 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005269 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5270 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005271 return;
5272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005274 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005275 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005276 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005277 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005278 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005279 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005280 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005281 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005283 unsigned NumArgsInProto = Proto->getNumArgs();
5284
5285 // (C++ 13.3.2p2): A candidate function having fewer than m
5286 // parameters is viable only if it has an ellipsis in its parameter
5287 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005288 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005289 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005290 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005291 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005292 return;
5293 }
5294
5295 // (C++ 13.3.2p2): A candidate function having more than m parameters
5296 // is viable only if the (m+1)st parameter has a default argument
5297 // (8.3.6). For the purposes of overload resolution, the
5298 // parameter list is truncated on the right, so that there are
5299 // exactly m parameters.
5300 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005301 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005302 // Not enough arguments.
5303 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005304 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005305 return;
5306 }
5307
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005308 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005309 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005310 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5311 if (CheckCUDATarget(Caller, Function)) {
5312 Candidate.Viable = false;
5313 Candidate.FailureKind = ovl_fail_bad_target;
5314 return;
5315 }
5316
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005317 // Determine the implicit conversion sequences for each of the
5318 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005319 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005320 if (ArgIdx < NumArgsInProto) {
5321 // (C++ 13.3.2p3): for F to be a viable function, there shall
5322 // exist for each argument an implicit conversion sequence
5323 // (13.3.3.1) that converts that argument to the corresponding
5324 // parameter of F.
5325 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005326 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005327 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005329 /*InOverloadResolution=*/true,
5330 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005331 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005332 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005333 if (Candidate.Conversions[ArgIdx].isBad()) {
5334 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005335 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005336 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005337 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005338 } else {
5339 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5340 // argument for which there is no corresponding parameter is
5341 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005342 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005343 }
5344 }
5345}
5346
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005347/// \brief Add all of the function declarations in the given function set to
5348/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005349void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005350 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005351 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005352 bool SuppressUserConversions,
5353 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005354 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005355 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5356 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005357 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005358 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005359 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005360 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005361 Args.slice(1), CandidateSet,
5362 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005363 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005364 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005365 SuppressUserConversions);
5366 } else {
John McCalla0296f72010-03-19 07:35:19 +00005367 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005368 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5369 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005370 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005371 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005372 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005374 Args[0]->Classify(Context), Args.slice(1),
5375 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005376 else
John McCalla0296f72010-03-19 07:35:19 +00005377 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005378 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005379 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005380 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005381 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005382}
5383
John McCallf0f1cf02009-11-17 07:50:12 +00005384/// AddMethodCandidate - Adds a named decl (which is some kind of
5385/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005386void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005387 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005388 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005389 Expr **Args, unsigned NumArgs,
5390 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005391 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005392 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005393 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005394
5395 if (isa<UsingShadowDecl>(Decl))
5396 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
John McCallf0f1cf02009-11-17 07:50:12 +00005398 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5399 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5400 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005401 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5402 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005403 ObjectType, ObjectClassification,
5404 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005405 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005406 } else {
John McCalla0296f72010-03-19 07:35:19 +00005407 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005408 ObjectType, ObjectClassification,
5409 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005410 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005411 }
5412}
5413
Douglas Gregor436424c2008-11-18 23:14:02 +00005414/// AddMethodCandidate - Adds the given C++ member function to the set
5415/// of candidate functions, using the given function call arguments
5416/// and the object argument (@c Object). For example, in a call
5417/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5418/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5419/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005420/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005421void
John McCalla0296f72010-03-19 07:35:19 +00005422Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005423 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005424 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005425 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005426 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005427 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005428 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005429 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005430 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005431 assert(!isa<CXXConstructorDecl>(Method) &&
5432 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005433
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005434 if (!CandidateSet.isNewCandidate(Method))
5435 return;
5436
Douglas Gregor27381f32009-11-23 12:27:39 +00005437 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005438 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005439
Douglas Gregor436424c2008-11-18 23:14:02 +00005440 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005441 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005442 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005443 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005444 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005445 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005446 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005447
5448 unsigned NumArgsInProto = Proto->getNumArgs();
5449
5450 // (C++ 13.3.2p2): A candidate function having fewer than m
5451 // parameters is viable only if it has an ellipsis in its parameter
5452 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005453 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005454 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005455 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005456 return;
5457 }
5458
5459 // (C++ 13.3.2p2): A candidate function having more than m parameters
5460 // is viable only if the (m+1)st parameter has a default argument
5461 // (8.3.6). For the purposes of overload resolution, the
5462 // parameter list is truncated on the right, so that there are
5463 // exactly m parameters.
5464 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005465 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005466 // Not enough arguments.
5467 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005468 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005469 return;
5470 }
5471
5472 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005473
John McCall6e9f8f62009-12-03 04:06:58 +00005474 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005475 // The implicit object argument is ignored.
5476 Candidate.IgnoreObjectArgument = true;
5477 else {
5478 // Determine the implicit conversion sequence for the object
5479 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005480 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005481 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5482 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005483 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005484 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005485 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005486 return;
5487 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005488 }
5489
5490 // Determine the implicit conversion sequences for each of the
5491 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005492 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005493 if (ArgIdx < NumArgsInProto) {
5494 // (C++ 13.3.2p3): for F to be a viable function, there shall
5495 // exist for each argument an implicit conversion sequence
5496 // (13.3.3.1) that converts that argument to the corresponding
5497 // parameter of F.
5498 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005499 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005500 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005502 /*InOverloadResolution=*/true,
5503 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005504 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005505 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005506 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005507 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005508 break;
5509 }
5510 } else {
5511 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5512 // argument for which there is no corresponding parameter is
5513 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005514 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005515 }
5516 }
5517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Douglas Gregor97628d62009-08-21 00:16:32 +00005519/// \brief Add a C++ member function template as a candidate to the candidate
5520/// set, using template argument deduction to produce an appropriate member
5521/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005522void
Douglas Gregor97628d62009-08-21 00:16:32 +00005523Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005524 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005525 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005526 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005527 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005528 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005529 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005530 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005531 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005532 if (!CandidateSet.isNewCandidate(MethodTmpl))
5533 return;
5534
Douglas Gregor97628d62009-08-21 00:16:32 +00005535 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005536 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005537 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005538 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005539 // candidate functions in the usual way.113) A given name can refer to one
5540 // or more function templates and also to a set of overloaded non-template
5541 // functions. In such a case, the candidate functions generated from each
5542 // function template are combined with the set of non-template candidate
5543 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005544 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005545 FunctionDecl *Specialization = 0;
5546 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005547 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5548 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005549 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005550 Candidate.FoundDecl = FoundDecl;
5551 Candidate.Function = MethodTmpl->getTemplatedDecl();
5552 Candidate.Viable = false;
5553 Candidate.FailureKind = ovl_fail_bad_deduction;
5554 Candidate.IsSurrogate = false;
5555 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005556 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005557 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005558 Info);
5559 return;
5560 }
Mike Stump11289f42009-09-09 15:08:12 +00005561
Douglas Gregor97628d62009-08-21 00:16:32 +00005562 // Add the function template specialization produced by template argument
5563 // deduction as a candidate.
5564 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005565 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005566 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005567 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005568 ActingContext, ObjectType, ObjectClassification, Args,
5569 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005570}
5571
Douglas Gregor05155d82009-08-21 23:19:43 +00005572/// \brief Add a C++ function template specialization as a candidate
5573/// in the candidate set, using template argument deduction to produce
5574/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005575void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005576Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005577 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005578 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005579 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005580 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005581 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005582 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5583 return;
5584
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005585 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005586 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005587 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005588 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005589 // candidate functions in the usual way.113) A given name can refer to one
5590 // or more function templates and also to a set of overloaded non-template
5591 // functions. In such a case, the candidate functions generated from each
5592 // function template are combined with the set of non-template candidate
5593 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005594 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005595 FunctionDecl *Specialization = 0;
5596 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005597 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5598 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005599 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005600 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005601 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5602 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005603 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005604 Candidate.IsSurrogate = false;
5605 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005606 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005608 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005609 return;
5610 }
Mike Stump11289f42009-09-09 15:08:12 +00005611
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005612 // Add the function template specialization produced by template argument
5613 // deduction as a candidate.
5614 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005615 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005616 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005617}
Mike Stump11289f42009-09-09 15:08:12 +00005618
Douglas Gregora1f013e2008-11-07 22:36:19 +00005619/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005620/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005621/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005622/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005623/// (which may or may not be the same type as the type that the
5624/// conversion function produces).
5625void
5626Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005627 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005628 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005629 Expr *From, QualType ToType,
5630 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005631 assert(!Conversion->getDescribedFunctionTemplate() &&
5632 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005633 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005634 if (!CandidateSet.isNewCandidate(Conversion))
5635 return;
5636
Douglas Gregor27381f32009-11-23 12:27:39 +00005637 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005638 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005639
Douglas Gregora1f013e2008-11-07 22:36:19 +00005640 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005641 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005642 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005643 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005644 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005645 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005646 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005647 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005648 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005649 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005650 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005651
Douglas Gregor6affc782010-08-19 15:37:02 +00005652 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653 // For conversion functions, the function is considered to be a member of
5654 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005655 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005656 //
5657 // Determine the implicit conversion sequence for the implicit
5658 // object parameter.
5659 QualType ImplicitParamType = From->getType();
5660 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5661 ImplicitParamType = FromPtrType->getPointeeType();
5662 CXXRecordDecl *ConversionContext
5663 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005665 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666 = TryObjectArgumentInitialization(*this, From->getType(),
5667 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005668 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
John McCall0d1da222010-01-12 00:44:57 +00005670 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005671 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005672 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005673 return;
5674 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005675
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005677 // derived to base as such conversions are given Conversion Rank. They only
5678 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5679 QualType FromCanon
5680 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5681 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5682 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5683 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005684 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005685 return;
5686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687
Douglas Gregora1f013e2008-11-07 22:36:19 +00005688 // To determine what the conversion from the result of calling the
5689 // conversion function to the type we're eventually trying to
5690 // convert to (ToType), we need to synthesize a call to the
5691 // conversion function and attempt copy initialization from it. This
5692 // makes sure that we get the right semantics with respect to
5693 // lvalues/rvalues and the type. Fortunately, we can allocate this
5694 // call on the stack and we don't need its arguments to be
5695 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005696 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005697 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005698 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5699 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005700 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005701 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005702
Richard Smith48d24642011-07-13 22:53:21 +00005703 QualType ConversionType = Conversion->getConversionType();
5704 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005705 Candidate.Viable = false;
5706 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5707 return;
5708 }
5709
Richard Smith48d24642011-07-13 22:53:21 +00005710 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005711
Mike Stump11289f42009-09-09 15:08:12 +00005712 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005713 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5714 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005715 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005716 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005717 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005718 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005719 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005720 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005721 /*InOverloadResolution=*/false,
5722 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005723
John McCall0d1da222010-01-12 00:44:57 +00005724 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005725 case ImplicitConversionSequence::StandardConversion:
5726 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005727
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005728 // C++ [over.ics.user]p3:
5729 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005731 // shall have exact match rank.
5732 if (Conversion->getPrimaryTemplate() &&
5733 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5734 Candidate.Viable = false;
5735 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregorcba72b12011-01-21 05:18:22 +00005738 // C++0x [dcl.init.ref]p5:
5739 // In the second case, if the reference is an rvalue reference and
5740 // the second standard conversion sequence of the user-defined
5741 // conversion sequence includes an lvalue-to-rvalue conversion, the
5742 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005743 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005744 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5745 Candidate.Viable = false;
5746 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5747 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005748 break;
5749
5750 case ImplicitConversionSequence::BadConversion:
5751 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005752 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005753 break;
5754
5755 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005756 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005757 "Can only end up with a standard conversion sequence or failure");
5758 }
5759}
5760
Douglas Gregor05155d82009-08-21 23:19:43 +00005761/// \brief Adds a conversion function template specialization
5762/// candidate to the overload set, using template argument deduction
5763/// to deduce the template arguments of the conversion function
5764/// template from the type that we are converting to (C++
5765/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005766void
Douglas Gregor05155d82009-08-21 23:19:43 +00005767Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005768 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005769 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005770 Expr *From, QualType ToType,
5771 OverloadCandidateSet &CandidateSet) {
5772 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5773 "Only conversion function templates permitted here");
5774
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005775 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5776 return;
5777
John McCallbc077cf2010-02-08 23:07:23 +00005778 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005779 CXXConversionDecl *Specialization = 0;
5780 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005781 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005782 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005783 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005784 Candidate.FoundDecl = FoundDecl;
5785 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5786 Candidate.Viable = false;
5787 Candidate.FailureKind = ovl_fail_bad_deduction;
5788 Candidate.IsSurrogate = false;
5789 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005790 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005792 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005793 return;
5794 }
Mike Stump11289f42009-09-09 15:08:12 +00005795
Douglas Gregor05155d82009-08-21 23:19:43 +00005796 // Add the conversion function template specialization produced by
5797 // template argument deduction as a candidate.
5798 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005799 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005800 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005801}
5802
Douglas Gregorab7897a2008-11-19 22:57:39 +00005803/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5804/// converts the given @c Object to a function pointer via the
5805/// conversion function @c Conversion, and then attempts to call it
5806/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5807/// the type of function that we'll eventually be calling.
5808void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005809 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005810 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005811 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005812 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005813 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005814 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005815 if (!CandidateSet.isNewCandidate(Conversion))
5816 return;
5817
Douglas Gregor27381f32009-11-23 12:27:39 +00005818 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005819 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005820
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005821 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005822 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005823 Candidate.Function = 0;
5824 Candidate.Surrogate = Conversion;
5825 Candidate.Viable = true;
5826 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005827 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005828 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005829
5830 // Determine the implicit conversion sequence for the implicit
5831 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005832 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005834 Object->Classify(Context),
5835 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005836 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005837 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005838 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005839 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005840 return;
5841 }
5842
5843 // The first conversion is actually a user-defined conversion whose
5844 // first conversion is ObjectInit's standard conversion (which is
5845 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005846 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005847 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005848 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005849 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005850 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005851 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005852 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005853 = Candidate.Conversions[0].UserDefined.Before;
5854 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5855
Mike Stump11289f42009-09-09 15:08:12 +00005856 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005857 unsigned NumArgsInProto = Proto->getNumArgs();
5858
5859 // (C++ 13.3.2p2): A candidate function having fewer than m
5860 // parameters is viable only if it has an ellipsis in its parameter
5861 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005862 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005863 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005864 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005865 return;
5866 }
5867
5868 // Function types don't have any default arguments, so just check if
5869 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005870 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005871 // Not enough arguments.
5872 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005873 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005874 return;
5875 }
5876
5877 // Determine the implicit conversion sequences for each of the
5878 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005879 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005880 if (ArgIdx < NumArgsInProto) {
5881 // (C++ 13.3.2p3): for F to be a viable function, there shall
5882 // exist for each argument an implicit conversion sequence
5883 // (13.3.3.1) that converts that argument to the corresponding
5884 // parameter of F.
5885 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005886 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005887 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005888 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005889 /*InOverloadResolution=*/false,
5890 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005891 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005892 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005893 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005894 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005895 break;
5896 }
5897 } else {
5898 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5899 // argument for which there is no corresponding parameter is
5900 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005901 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005902 }
5903 }
5904}
5905
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005906/// \brief Add overload candidates for overloaded operators that are
5907/// member functions.
5908///
5909/// Add the overloaded operator candidates that are member functions
5910/// for the operator Op that was used in an operator expression such
5911/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5912/// CandidateSet will store the added overload candidates. (C++
5913/// [over.match.oper]).
5914void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5915 SourceLocation OpLoc,
5916 Expr **Args, unsigned NumArgs,
5917 OverloadCandidateSet& CandidateSet,
5918 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005919 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5920
5921 // C++ [over.match.oper]p3:
5922 // For a unary operator @ with an operand of a type whose
5923 // cv-unqualified version is T1, and for a binary operator @ with
5924 // a left operand of a type whose cv-unqualified version is T1 and
5925 // a right operand of a type whose cv-unqualified version is T2,
5926 // three sets of candidate functions, designated member
5927 // candidates, non-member candidates and built-in candidates, are
5928 // constructed as follows:
5929 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005930
5931 // -- If T1 is a class type, the set of member candidates is the
5932 // result of the qualified lookup of T1::operator@
5933 // (13.3.1.1.1); otherwise, the set of member candidates is
5934 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005935 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005936 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005937 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005938 return;
Mike Stump11289f42009-09-09 15:08:12 +00005939
John McCall27b18f82009-11-17 02:14:36 +00005940 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5941 LookupQualifiedName(Operators, T1Rec->getDecl());
5942 Operators.suppressDiagnostics();
5943
Mike Stump11289f42009-09-09 15:08:12 +00005944 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005945 OperEnd = Operators.end();
5946 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005947 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005948 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005949 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005950 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005951 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005952 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005953}
5954
Douglas Gregora11693b2008-11-12 17:17:38 +00005955/// AddBuiltinCandidate - Add a candidate for a built-in
5956/// operator. ResultTy and ParamTys are the result and parameter types
5957/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005958/// arguments being passed to the candidate. IsAssignmentOperator
5959/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005960/// operator. NumContextualBoolArguments is the number of arguments
5961/// (at the beginning of the argument list) that will be contextually
5962/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005963void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005964 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005965 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005966 bool IsAssignmentOperator,
5967 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005968 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005969 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005970
Douglas Gregora11693b2008-11-12 17:17:38 +00005971 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005972 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005973 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005974 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005975 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005976 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005977 Candidate.BuiltinTypes.ResultTy = ResultTy;
5978 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5979 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5980
5981 // Determine the implicit conversion sequences for each of the
5982 // arguments.
5983 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005984 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005985 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005986 // C++ [over.match.oper]p4:
5987 // For the built-in assignment operators, conversions of the
5988 // left operand are restricted as follows:
5989 // -- no temporaries are introduced to hold the left operand, and
5990 // -- no user-defined conversions are applied to the left
5991 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005992 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005993 //
5994 // We block these conversions by turning off user-defined
5995 // conversions, since that is the only way that initialization of
5996 // a reference to a non-class type can occur from something that
5997 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005998 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005999 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006000 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006001 Candidate.Conversions[ArgIdx]
6002 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006003 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006004 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006005 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006006 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006007 /*InOverloadResolution=*/false,
6008 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006009 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006010 }
John McCall0d1da222010-01-12 00:44:57 +00006011 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006012 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006013 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006014 break;
6015 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006016 }
6017}
6018
6019/// BuiltinCandidateTypeSet - A set of types that will be used for the
6020/// candidate operator functions for built-in operators (C++
6021/// [over.built]). The types are separated into pointer types and
6022/// enumeration types.
6023class BuiltinCandidateTypeSet {
6024 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006025 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006026
6027 /// PointerTypes - The set of pointer types that will be used in the
6028 /// built-in candidates.
6029 TypeSet PointerTypes;
6030
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006031 /// MemberPointerTypes - The set of member pointer types that will be
6032 /// used in the built-in candidates.
6033 TypeSet MemberPointerTypes;
6034
Douglas Gregora11693b2008-11-12 17:17:38 +00006035 /// EnumerationTypes - The set of enumeration types that will be
6036 /// used in the built-in candidates.
6037 TypeSet EnumerationTypes;
6038
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006039 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006040 /// candidates.
6041 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006042
6043 /// \brief A flag indicating non-record types are viable candidates
6044 bool HasNonRecordTypes;
6045
6046 /// \brief A flag indicating whether either arithmetic or enumeration types
6047 /// were present in the candidate set.
6048 bool HasArithmeticOrEnumeralTypes;
6049
Douglas Gregor80af3132011-05-21 23:15:46 +00006050 /// \brief A flag indicating whether the nullptr type was present in the
6051 /// candidate set.
6052 bool HasNullPtrType;
6053
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006054 /// Sema - The semantic analysis instance where we are building the
6055 /// candidate type set.
6056 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006057
Douglas Gregora11693b2008-11-12 17:17:38 +00006058 /// Context - The AST context in which we will build the type sets.
6059 ASTContext &Context;
6060
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006061 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6062 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006063 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006064
6065public:
6066 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006067 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006068
Mike Stump11289f42009-09-09 15:08:12 +00006069 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006070 : HasNonRecordTypes(false),
6071 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006072 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006073 SemaRef(SemaRef),
6074 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006075
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006077 SourceLocation Loc,
6078 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006079 bool AllowExplicitConversions,
6080 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006081
6082 /// pointer_begin - First pointer type found;
6083 iterator pointer_begin() { return PointerTypes.begin(); }
6084
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006085 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006086 iterator pointer_end() { return PointerTypes.end(); }
6087
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006088 /// member_pointer_begin - First member pointer type found;
6089 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6090
6091 /// member_pointer_end - Past the last member pointer type found;
6092 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6093
Douglas Gregora11693b2008-11-12 17:17:38 +00006094 /// enumeration_begin - First enumeration type found;
6095 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6096
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006097 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006098 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006100 iterator vector_begin() { return VectorTypes.begin(); }
6101 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006102
6103 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6104 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006105 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006106};
6107
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006108/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006109/// the set of pointer types along with any more-qualified variants of
6110/// that type. For example, if @p Ty is "int const *", this routine
6111/// will add "int const *", "int const volatile *", "int const
6112/// restrict *", and "int const volatile restrict *" to the set of
6113/// pointer types. Returns true if the add of @p Ty itself succeeded,
6114/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006115///
6116/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006117bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006118BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6119 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006120
Douglas Gregora11693b2008-11-12 17:17:38 +00006121 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006122 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006123 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006125 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006126 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006127 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006128 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006129 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6130 PointeeTy = PTy->getPointeeType();
6131 buildObjCPtr = true;
6132 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006133 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006134 }
6135
Sebastian Redl4990a632009-11-18 20:39:26 +00006136 // Don't add qualified variants of arrays. For one, they're not allowed
6137 // (the qualifier would sink to the element type), and for another, the
6138 // only overload situation where it matters is subscript or pointer +- int,
6139 // and those shouldn't have qualifier variants anyway.
6140 if (PointeeTy->isArrayType())
6141 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006142
John McCall8ccfcb52009-09-24 19:53:00 +00006143 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006144 bool hasVolatile = VisibleQuals.hasVolatile();
6145 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006146
John McCall8ccfcb52009-09-24 19:53:00 +00006147 // Iterate through all strict supersets of BaseCVR.
6148 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6149 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006150 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006151 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006152
6153 // Skip over restrict if no restrict found anywhere in the types, or if
6154 // the type cannot be restrict-qualified.
6155 if ((CVR & Qualifiers::Restrict) &&
6156 (!hasRestrict ||
6157 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6158 continue;
6159
6160 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006161 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006162
6163 // Build qualified pointer type.
6164 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006165 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006166 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006167 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006168 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6169
6170 // Insert qualified pointer type.
6171 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006172 }
6173
6174 return true;
6175}
6176
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006177/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6178/// to the set of pointer types along with any more-qualified variants of
6179/// that type. For example, if @p Ty is "int const *", this routine
6180/// will add "int const *", "int const volatile *", "int const
6181/// restrict *", and "int const volatile restrict *" to the set of
6182/// pointer types. Returns true if the add of @p Ty itself succeeded,
6183/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006184///
6185/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006186bool
6187BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6188 QualType Ty) {
6189 // Insert this type.
6190 if (!MemberPointerTypes.insert(Ty))
6191 return false;
6192
John McCall8ccfcb52009-09-24 19:53:00 +00006193 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6194 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006195
John McCall8ccfcb52009-09-24 19:53:00 +00006196 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006197 // Don't add qualified variants of arrays. For one, they're not allowed
6198 // (the qualifier would sink to the element type), and for another, the
6199 // only overload situation where it matters is subscript or pointer +- int,
6200 // and those shouldn't have qualifier variants anyway.
6201 if (PointeeTy->isArrayType())
6202 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006203 const Type *ClassTy = PointerTy->getClass();
6204
6205 // Iterate through all strict supersets of the pointee type's CVR
6206 // qualifiers.
6207 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6208 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6209 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006210
John McCall8ccfcb52009-09-24 19:53:00 +00006211 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006212 MemberPointerTypes.insert(
6213 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006214 }
6215
6216 return true;
6217}
6218
Douglas Gregora11693b2008-11-12 17:17:38 +00006219/// AddTypesConvertedFrom - Add each of the types to which the type @p
6220/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006221/// primarily interested in pointer types and enumeration types. We also
6222/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006223/// AllowUserConversions is true if we should look at the conversion
6224/// functions of a class type, and AllowExplicitConversions if we
6225/// should also include the explicit conversion functions of a class
6226/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006227void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006228BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006229 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006230 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006231 bool AllowExplicitConversions,
6232 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006233 // Only deal with canonical types.
6234 Ty = Context.getCanonicalType(Ty);
6235
6236 // Look through reference types; they aren't part of the type of an
6237 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006238 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006239 Ty = RefTy->getPointeeType();
6240
John McCall33ddac02011-01-19 10:06:00 +00006241 // If we're dealing with an array type, decay to the pointer.
6242 if (Ty->isArrayType())
6243 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6244
6245 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006246 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006247
Chandler Carruth00a38332010-12-13 01:44:01 +00006248 // Flag if we ever add a non-record type.
6249 const RecordType *TyRec = Ty->getAs<RecordType>();
6250 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6251
Chandler Carruth00a38332010-12-13 01:44:01 +00006252 // Flag if we encounter an arithmetic type.
6253 HasArithmeticOrEnumeralTypes =
6254 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6255
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006256 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6257 PointerTypes.insert(Ty);
6258 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006259 // Insert our type, and its more-qualified variants, into the set
6260 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006261 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006262 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006263 } else if (Ty->isMemberPointerType()) {
6264 // Member pointers are far easier, since the pointee can't be converted.
6265 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6266 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006267 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006268 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006269 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006270 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006271 // We treat vector types as arithmetic types in many contexts as an
6272 // extension.
6273 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006274 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006275 } else if (Ty->isNullPtrType()) {
6276 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006277 } else if (AllowUserConversions && TyRec) {
6278 // No conversion functions in incomplete types.
6279 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6280 return;
Mike Stump11289f42009-09-09 15:08:12 +00006281
Chandler Carruth00a38332010-12-13 01:44:01 +00006282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6283 const UnresolvedSetImpl *Conversions
6284 = ClassDecl->getVisibleConversionFunctions();
6285 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6286 E = Conversions->end(); I != E; ++I) {
6287 NamedDecl *D = I.getDecl();
6288 if (isa<UsingShadowDecl>(D))
6289 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006290
Chandler Carruth00a38332010-12-13 01:44:01 +00006291 // Skip conversion function templates; they don't tell us anything
6292 // about which builtin types we can convert to.
6293 if (isa<FunctionTemplateDecl>(D))
6294 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006295
Chandler Carruth00a38332010-12-13 01:44:01 +00006296 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6297 if (AllowExplicitConversions || !Conv->isExplicit()) {
6298 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6299 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006300 }
6301 }
6302 }
6303}
6304
Douglas Gregor84605ae2009-08-24 13:43:27 +00006305/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6306/// the volatile- and non-volatile-qualified assignment operators for the
6307/// given type to the candidate set.
6308static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6309 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006310 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006311 unsigned NumArgs,
6312 OverloadCandidateSet &CandidateSet) {
6313 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006314
Douglas Gregor84605ae2009-08-24 13:43:27 +00006315 // T& operator=(T&, T)
6316 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6317 ParamTypes[1] = T;
6318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6319 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006320
Douglas Gregor84605ae2009-08-24 13:43:27 +00006321 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6322 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006323 ParamTypes[0]
6324 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006325 ParamTypes[1] = T;
6326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006327 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006328 }
6329}
Mike Stump11289f42009-09-09 15:08:12 +00006330
Sebastian Redl1054fae2009-10-25 17:03:50 +00006331/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6332/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006333static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6334 Qualifiers VRQuals;
6335 const RecordType *TyRec;
6336 if (const MemberPointerType *RHSMPType =
6337 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006338 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006339 else
6340 TyRec = ArgExpr->getType()->getAs<RecordType>();
6341 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006342 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006343 VRQuals.addVolatile();
6344 VRQuals.addRestrict();
6345 return VRQuals;
6346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006348 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006349 if (!ClassDecl->hasDefinition())
6350 return VRQuals;
6351
John McCallad371252010-01-20 00:46:10 +00006352 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006353 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354
John McCallad371252010-01-20 00:46:10 +00006355 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006356 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006357 NamedDecl *D = I.getDecl();
6358 if (isa<UsingShadowDecl>(D))
6359 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6360 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006361 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6362 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6363 CanTy = ResTypeRef->getPointeeType();
6364 // Need to go down the pointer/mempointer chain and add qualifiers
6365 // as see them.
6366 bool done = false;
6367 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006368 if (CanTy.isRestrictQualified())
6369 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006370 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6371 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006373 CanTy->getAs<MemberPointerType>())
6374 CanTy = ResTypeMPtr->getPointeeType();
6375 else
6376 done = true;
6377 if (CanTy.isVolatileQualified())
6378 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006379 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6380 return VRQuals;
6381 }
6382 }
6383 }
6384 return VRQuals;
6385}
John McCall52872982010-11-13 05:51:15 +00006386
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006387namespace {
John McCall52872982010-11-13 05:51:15 +00006388
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006389/// \brief Helper class to manage the addition of builtin operator overload
6390/// candidates. It provides shared state and utility methods used throughout
6391/// the process, as well as a helper method to add each group of builtin
6392/// operator overloads from the standard to a candidate set.
6393class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006394 // Common instance state available to all overload candidate addition methods.
6395 Sema &S;
6396 Expr **Args;
6397 unsigned NumArgs;
6398 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006399 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006400 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006401 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006402
Chandler Carruthc6586e52010-12-12 10:35:00 +00006403 // Define some constants used to index and iterate over the arithemetic types
6404 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006405 // The "promoted arithmetic types" are the arithmetic
6406 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006407 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006408 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006409 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006410 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006411 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006412 LastPromotedArithmeticType = 11;
6413 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006414
Chandler Carruthc6586e52010-12-12 10:35:00 +00006415 /// \brief Get the canonical type for a given arithmetic type index.
6416 CanQualType getArithmeticType(unsigned index) {
6417 assert(index < NumArithmeticTypes);
6418 static CanQualType ASTContext::* const
6419 ArithmeticTypes[NumArithmeticTypes] = {
6420 // Start of promoted types.
6421 &ASTContext::FloatTy,
6422 &ASTContext::DoubleTy,
6423 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006424
Chandler Carruthc6586e52010-12-12 10:35:00 +00006425 // Start of integral types.
6426 &ASTContext::IntTy,
6427 &ASTContext::LongTy,
6428 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006429 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006430 &ASTContext::UnsignedIntTy,
6431 &ASTContext::UnsignedLongTy,
6432 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006433 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006434 // End of promoted types.
6435
6436 &ASTContext::BoolTy,
6437 &ASTContext::CharTy,
6438 &ASTContext::WCharTy,
6439 &ASTContext::Char16Ty,
6440 &ASTContext::Char32Ty,
6441 &ASTContext::SignedCharTy,
6442 &ASTContext::ShortTy,
6443 &ASTContext::UnsignedCharTy,
6444 &ASTContext::UnsignedShortTy,
6445 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006446 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006447 };
6448 return S.Context.*ArithmeticTypes[index];
6449 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006450
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006451 /// \brief Gets the canonical type resulting from the usual arithemetic
6452 /// converions for the given arithmetic types.
6453 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6454 // Accelerator table for performing the usual arithmetic conversions.
6455 // The rules are basically:
6456 // - if either is floating-point, use the wider floating-point
6457 // - if same signedness, use the higher rank
6458 // - if same size, use unsigned of the higher rank
6459 // - use the larger type
6460 // These rules, together with the axiom that higher ranks are
6461 // never smaller, are sufficient to precompute all of these results
6462 // *except* when dealing with signed types of higher rank.
6463 // (we could precompute SLL x UI for all known platforms, but it's
6464 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006465 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006466 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006467 Dep=-1,
6468 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006469 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006470 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006471 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006472/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6473/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6474/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6475/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6476/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6477/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6478/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6479/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6480/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6481/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6482/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006483 };
6484
6485 assert(L < LastPromotedArithmeticType);
6486 assert(R < LastPromotedArithmeticType);
6487 int Idx = ConversionsTable[L][R];
6488
6489 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006490 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006491
6492 // Slow path: we need to compare widths.
6493 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006494 CanQualType LT = getArithmeticType(L),
6495 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006496 unsigned LW = S.Context.getIntWidth(LT),
6497 RW = S.Context.getIntWidth(RT);
6498
6499 // If they're different widths, use the signed type.
6500 if (LW > RW) return LT;
6501 else if (LW < RW) return RT;
6502
6503 // Otherwise, use the unsigned type of the signed type's rank.
6504 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6505 assert(L == SLL || R == SLL);
6506 return S.Context.UnsignedLongLongTy;
6507 }
6508
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006509 /// \brief Helper method to factor out the common pattern of adding overloads
6510 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006511 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006512 bool HasVolatile,
6513 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006514 QualType ParamTypes[2] = {
6515 S.Context.getLValueReferenceType(CandidateTy),
6516 S.Context.IntTy
6517 };
6518
6519 // Non-volatile version.
6520 if (NumArgs == 1)
6521 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6522 else
6523 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6524
6525 // Use a heuristic to reduce number of builtin candidates in the set:
6526 // add volatile version only if there are conversions to a volatile type.
6527 if (HasVolatile) {
6528 ParamTypes[0] =
6529 S.Context.getLValueReferenceType(
6530 S.Context.getVolatileType(CandidateTy));
6531 if (NumArgs == 1)
6532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6533 else
6534 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6535 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006536
6537 // Add restrict version only if there are conversions to a restrict type
6538 // and our candidate type is a non-restrict-qualified pointer.
6539 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6540 !CandidateTy.isRestrictQualified()) {
6541 ParamTypes[0]
6542 = S.Context.getLValueReferenceType(
6543 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6544 if (NumArgs == 1)
6545 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6546 else
6547 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6548
6549 if (HasVolatile) {
6550 ParamTypes[0]
6551 = S.Context.getLValueReferenceType(
6552 S.Context.getCVRQualifiedType(CandidateTy,
6553 (Qualifiers::Volatile |
6554 Qualifiers::Restrict)));
6555 if (NumArgs == 1)
6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6557 CandidateSet);
6558 else
6559 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6560 }
6561 }
6562
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006563 }
6564
6565public:
6566 BuiltinOperatorOverloadBuilder(
6567 Sema &S, Expr **Args, unsigned NumArgs,
6568 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006569 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006570 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006571 OverloadCandidateSet &CandidateSet)
6572 : S(S), Args(Args), NumArgs(NumArgs),
6573 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006574 HasArithmeticOrEnumeralCandidateType(
6575 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006576 CandidateTypes(CandidateTypes),
6577 CandidateSet(CandidateSet) {
6578 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006579 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006580 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006581 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006582 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006583 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006584 assert(getArithmeticType(FirstPromotedArithmeticType)
6585 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006586 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006587 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006588 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006589 "Invalid last promoted arithmetic type");
6590 }
6591
6592 // C++ [over.built]p3:
6593 //
6594 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6595 // is either volatile or empty, there exist candidate operator
6596 // functions of the form
6597 //
6598 // VQ T& operator++(VQ T&);
6599 // T operator++(VQ T&, int);
6600 //
6601 // C++ [over.built]p4:
6602 //
6603 // For every pair (T, VQ), where T is an arithmetic type other
6604 // than bool, and VQ is either volatile or empty, there exist
6605 // candidate operator functions of the form
6606 //
6607 // VQ T& operator--(VQ T&);
6608 // T operator--(VQ T&, int);
6609 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006610 if (!HasArithmeticOrEnumeralCandidateType)
6611 return;
6612
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006613 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6614 Arith < NumArithmeticTypes; ++Arith) {
6615 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006616 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006617 VisibleTypeConversionsQuals.hasVolatile(),
6618 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006619 }
6620 }
6621
6622 // C++ [over.built]p5:
6623 //
6624 // For every pair (T, VQ), where T is a cv-qualified or
6625 // cv-unqualified object type, and VQ is either volatile or
6626 // empty, there exist candidate operator functions of the form
6627 //
6628 // T*VQ& operator++(T*VQ&);
6629 // T*VQ& operator--(T*VQ&);
6630 // T* operator++(T*VQ&, int);
6631 // T* operator--(T*VQ&, int);
6632 void addPlusPlusMinusMinusPointerOverloads() {
6633 for (BuiltinCandidateTypeSet::iterator
6634 Ptr = CandidateTypes[0].pointer_begin(),
6635 PtrEnd = CandidateTypes[0].pointer_end();
6636 Ptr != PtrEnd; ++Ptr) {
6637 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006638 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006639 continue;
6640
6641 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006642 (!(*Ptr).isVolatileQualified() &&
6643 VisibleTypeConversionsQuals.hasVolatile()),
6644 (!(*Ptr).isRestrictQualified() &&
6645 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006646 }
6647 }
6648
6649 // C++ [over.built]p6:
6650 // For every cv-qualified or cv-unqualified object type T, there
6651 // exist candidate operator functions of the form
6652 //
6653 // T& operator*(T*);
6654 //
6655 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006657 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006658 // T& operator*(T*);
6659 void addUnaryStarPointerOverloads() {
6660 for (BuiltinCandidateTypeSet::iterator
6661 Ptr = CandidateTypes[0].pointer_begin(),
6662 PtrEnd = CandidateTypes[0].pointer_end();
6663 Ptr != PtrEnd; ++Ptr) {
6664 QualType ParamTy = *Ptr;
6665 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006666 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6667 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668
Douglas Gregor02824322011-01-26 19:30:28 +00006669 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6670 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6671 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006673 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6674 &ParamTy, Args, 1, CandidateSet);
6675 }
6676 }
6677
6678 // C++ [over.built]p9:
6679 // For every promoted arithmetic type T, there exist candidate
6680 // operator functions of the form
6681 //
6682 // T operator+(T);
6683 // T operator-(T);
6684 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006685 if (!HasArithmeticOrEnumeralCandidateType)
6686 return;
6687
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006688 for (unsigned Arith = FirstPromotedArithmeticType;
6689 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006690 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006691 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6692 }
6693
6694 // Extension: We also add these operators for vector types.
6695 for (BuiltinCandidateTypeSet::iterator
6696 Vec = CandidateTypes[0].vector_begin(),
6697 VecEnd = CandidateTypes[0].vector_end();
6698 Vec != VecEnd; ++Vec) {
6699 QualType VecTy = *Vec;
6700 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6701 }
6702 }
6703
6704 // C++ [over.built]p8:
6705 // For every type T, there exist candidate operator functions of
6706 // the form
6707 //
6708 // T* operator+(T*);
6709 void addUnaryPlusPointerOverloads() {
6710 for (BuiltinCandidateTypeSet::iterator
6711 Ptr = CandidateTypes[0].pointer_begin(),
6712 PtrEnd = CandidateTypes[0].pointer_end();
6713 Ptr != PtrEnd; ++Ptr) {
6714 QualType ParamTy = *Ptr;
6715 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6716 }
6717 }
6718
6719 // C++ [over.built]p10:
6720 // For every promoted integral type T, there exist candidate
6721 // operator functions of the form
6722 //
6723 // T operator~(T);
6724 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006725 if (!HasArithmeticOrEnumeralCandidateType)
6726 return;
6727
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006728 for (unsigned Int = FirstPromotedIntegralType;
6729 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006730 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006731 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6732 }
6733
6734 // Extension: We also add this operator for vector types.
6735 for (BuiltinCandidateTypeSet::iterator
6736 Vec = CandidateTypes[0].vector_begin(),
6737 VecEnd = CandidateTypes[0].vector_end();
6738 Vec != VecEnd; ++Vec) {
6739 QualType VecTy = *Vec;
6740 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6741 }
6742 }
6743
6744 // C++ [over.match.oper]p16:
6745 // For every pointer to member type T, there exist candidate operator
6746 // functions of the form
6747 //
6748 // bool operator==(T,T);
6749 // bool operator!=(T,T);
6750 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6751 /// Set of (canonical) types that we've already handled.
6752 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6753
6754 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6755 for (BuiltinCandidateTypeSet::iterator
6756 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6757 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6758 MemPtr != MemPtrEnd;
6759 ++MemPtr) {
6760 // Don't add the same builtin candidate twice.
6761 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6762 continue;
6763
6764 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6765 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6766 CandidateSet);
6767 }
6768 }
6769 }
6770
6771 // C++ [over.built]p15:
6772 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006773 // For every T, where T is an enumeration type, a pointer type, or
6774 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006775 //
6776 // bool operator<(T, T);
6777 // bool operator>(T, T);
6778 // bool operator<=(T, T);
6779 // bool operator>=(T, T);
6780 // bool operator==(T, T);
6781 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006782 void addRelationalPointerOrEnumeralOverloads() {
6783 // C++ [over.built]p1:
6784 // If there is a user-written candidate with the same name and parameter
6785 // types as a built-in candidate operator function, the built-in operator
6786 // function is hidden and is not included in the set of candidate
6787 // functions.
6788 //
6789 // The text is actually in a note, but if we don't implement it then we end
6790 // up with ambiguities when the user provides an overloaded operator for
6791 // an enumeration type. Note that only enumeration types have this problem,
6792 // so we track which enumeration types we've seen operators for. Also, the
6793 // only other overloaded operator with enumeration argumenst, operator=,
6794 // cannot be overloaded for enumeration types, so this is the only place
6795 // where we must suppress candidates like this.
6796 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6797 UserDefinedBinaryOperators;
6798
6799 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6800 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6801 CandidateTypes[ArgIdx].enumeration_end()) {
6802 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6803 CEnd = CandidateSet.end();
6804 C != CEnd; ++C) {
6805 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6806 continue;
6807
6808 QualType FirstParamType =
6809 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6810 QualType SecondParamType =
6811 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6812
6813 // Skip if either parameter isn't of enumeral type.
6814 if (!FirstParamType->isEnumeralType() ||
6815 !SecondParamType->isEnumeralType())
6816 continue;
6817
6818 // Add this operator to the set of known user-defined operators.
6819 UserDefinedBinaryOperators.insert(
6820 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6821 S.Context.getCanonicalType(SecondParamType)));
6822 }
6823 }
6824 }
6825
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006826 /// Set of (canonical) types that we've already handled.
6827 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6828
6829 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6830 for (BuiltinCandidateTypeSet::iterator
6831 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6832 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6833 Ptr != PtrEnd; ++Ptr) {
6834 // Don't add the same builtin candidate twice.
6835 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6836 continue;
6837
6838 QualType ParamTypes[2] = { *Ptr, *Ptr };
6839 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6840 CandidateSet);
6841 }
6842 for (BuiltinCandidateTypeSet::iterator
6843 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6844 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6845 Enum != EnumEnd; ++Enum) {
6846 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6847
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006848 // Don't add the same builtin candidate twice, or if a user defined
6849 // candidate exists.
6850 if (!AddedTypes.insert(CanonType) ||
6851 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6852 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006853 continue;
6854
6855 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006856 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6857 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006858 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006859
6860 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6861 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6862 if (AddedTypes.insert(NullPtrTy) &&
6863 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6864 NullPtrTy))) {
6865 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6866 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6867 CandidateSet);
6868 }
6869 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006870 }
6871 }
6872
6873 // C++ [over.built]p13:
6874 //
6875 // For every cv-qualified or cv-unqualified object type T
6876 // there exist candidate operator functions of the form
6877 //
6878 // T* operator+(T*, ptrdiff_t);
6879 // T& operator[](T*, ptrdiff_t); [BELOW]
6880 // T* operator-(T*, ptrdiff_t);
6881 // T* operator+(ptrdiff_t, T*);
6882 // T& operator[](ptrdiff_t, T*); [BELOW]
6883 //
6884 // C++ [over.built]p14:
6885 //
6886 // For every T, where T is a pointer to object type, there
6887 // exist candidate operator functions of the form
6888 //
6889 // ptrdiff_t operator-(T, T);
6890 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6891 /// Set of (canonical) types that we've already handled.
6892 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6893
6894 for (int Arg = 0; Arg < 2; ++Arg) {
6895 QualType AsymetricParamTypes[2] = {
6896 S.Context.getPointerDiffType(),
6897 S.Context.getPointerDiffType(),
6898 };
6899 for (BuiltinCandidateTypeSet::iterator
6900 Ptr = CandidateTypes[Arg].pointer_begin(),
6901 PtrEnd = CandidateTypes[Arg].pointer_end();
6902 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006903 QualType PointeeTy = (*Ptr)->getPointeeType();
6904 if (!PointeeTy->isObjectType())
6905 continue;
6906
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006907 AsymetricParamTypes[Arg] = *Ptr;
6908 if (Arg == 0 || Op == OO_Plus) {
6909 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6910 // T* operator+(ptrdiff_t, T*);
6911 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6912 CandidateSet);
6913 }
6914 if (Op == OO_Minus) {
6915 // ptrdiff_t operator-(T, T);
6916 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6917 continue;
6918
6919 QualType ParamTypes[2] = { *Ptr, *Ptr };
6920 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6921 Args, 2, CandidateSet);
6922 }
6923 }
6924 }
6925 }
6926
6927 // C++ [over.built]p12:
6928 //
6929 // For every pair of promoted arithmetic types L and R, there
6930 // exist candidate operator functions of the form
6931 //
6932 // LR operator*(L, R);
6933 // LR operator/(L, R);
6934 // LR operator+(L, R);
6935 // LR operator-(L, R);
6936 // bool operator<(L, R);
6937 // bool operator>(L, R);
6938 // bool operator<=(L, R);
6939 // bool operator>=(L, R);
6940 // bool operator==(L, R);
6941 // bool operator!=(L, R);
6942 //
6943 // where LR is the result of the usual arithmetic conversions
6944 // between types L and R.
6945 //
6946 // C++ [over.built]p24:
6947 //
6948 // For every pair of promoted arithmetic types L and R, there exist
6949 // candidate operator functions of the form
6950 //
6951 // LR operator?(bool, L, R);
6952 //
6953 // where LR is the result of the usual arithmetic conversions
6954 // between types L and R.
6955 // Our candidates ignore the first parameter.
6956 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006957 if (!HasArithmeticOrEnumeralCandidateType)
6958 return;
6959
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006960 for (unsigned Left = FirstPromotedArithmeticType;
6961 Left < LastPromotedArithmeticType; ++Left) {
6962 for (unsigned Right = FirstPromotedArithmeticType;
6963 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006964 QualType LandR[2] = { getArithmeticType(Left),
6965 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006966 QualType Result =
6967 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006968 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006969 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6970 }
6971 }
6972
6973 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6974 // conditional operator for vector types.
6975 for (BuiltinCandidateTypeSet::iterator
6976 Vec1 = CandidateTypes[0].vector_begin(),
6977 Vec1End = CandidateTypes[0].vector_end();
6978 Vec1 != Vec1End; ++Vec1) {
6979 for (BuiltinCandidateTypeSet::iterator
6980 Vec2 = CandidateTypes[1].vector_begin(),
6981 Vec2End = CandidateTypes[1].vector_end();
6982 Vec2 != Vec2End; ++Vec2) {
6983 QualType LandR[2] = { *Vec1, *Vec2 };
6984 QualType Result = S.Context.BoolTy;
6985 if (!isComparison) {
6986 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6987 Result = *Vec1;
6988 else
6989 Result = *Vec2;
6990 }
6991
6992 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6993 }
6994 }
6995 }
6996
6997 // C++ [over.built]p17:
6998 //
6999 // For every pair of promoted integral types L and R, there
7000 // exist candidate operator functions of the form
7001 //
7002 // LR operator%(L, R);
7003 // LR operator&(L, R);
7004 // LR operator^(L, R);
7005 // LR operator|(L, R);
7006 // L operator<<(L, R);
7007 // L operator>>(L, R);
7008 //
7009 // where LR is the result of the usual arithmetic conversions
7010 // between types L and R.
7011 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007012 if (!HasArithmeticOrEnumeralCandidateType)
7013 return;
7014
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007015 for (unsigned Left = FirstPromotedIntegralType;
7016 Left < LastPromotedIntegralType; ++Left) {
7017 for (unsigned Right = FirstPromotedIntegralType;
7018 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007019 QualType LandR[2] = { getArithmeticType(Left),
7020 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007021 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7022 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007023 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007024 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7025 }
7026 }
7027 }
7028
7029 // C++ [over.built]p20:
7030 //
7031 // For every pair (T, VQ), where T is an enumeration or
7032 // pointer to member type and VQ is either volatile or
7033 // empty, there exist candidate operator functions of the form
7034 //
7035 // VQ T& operator=(VQ T&, T);
7036 void addAssignmentMemberPointerOrEnumeralOverloads() {
7037 /// Set of (canonical) types that we've already handled.
7038 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7039
7040 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7041 for (BuiltinCandidateTypeSet::iterator
7042 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7043 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7044 Enum != EnumEnd; ++Enum) {
7045 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7046 continue;
7047
7048 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7049 CandidateSet);
7050 }
7051
7052 for (BuiltinCandidateTypeSet::iterator
7053 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7054 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7055 MemPtr != MemPtrEnd; ++MemPtr) {
7056 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7057 continue;
7058
7059 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7060 CandidateSet);
7061 }
7062 }
7063 }
7064
7065 // C++ [over.built]p19:
7066 //
7067 // For every pair (T, VQ), where T is any type and VQ is either
7068 // volatile or empty, there exist candidate operator functions
7069 // of the form
7070 //
7071 // T*VQ& operator=(T*VQ&, T*);
7072 //
7073 // C++ [over.built]p21:
7074 //
7075 // For every pair (T, VQ), where T is a cv-qualified or
7076 // cv-unqualified object type and VQ is either volatile or
7077 // empty, there exist candidate operator functions of the form
7078 //
7079 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7080 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7081 void addAssignmentPointerOverloads(bool isEqualOp) {
7082 /// Set of (canonical) types that we've already handled.
7083 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7084
7085 for (BuiltinCandidateTypeSet::iterator
7086 Ptr = CandidateTypes[0].pointer_begin(),
7087 PtrEnd = CandidateTypes[0].pointer_end();
7088 Ptr != PtrEnd; ++Ptr) {
7089 // If this is operator=, keep track of the builtin candidates we added.
7090 if (isEqualOp)
7091 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007092 else if (!(*Ptr)->getPointeeType()->isObjectType())
7093 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007094
7095 // non-volatile version
7096 QualType ParamTypes[2] = {
7097 S.Context.getLValueReferenceType(*Ptr),
7098 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7099 };
7100 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7101 /*IsAssigmentOperator=*/ isEqualOp);
7102
Douglas Gregor5bee2582012-06-04 00:15:09 +00007103 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7104 VisibleTypeConversionsQuals.hasVolatile();
7105 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007106 // volatile version
7107 ParamTypes[0] =
7108 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7110 /*IsAssigmentOperator=*/isEqualOp);
7111 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007112
7113 if (!(*Ptr).isRestrictQualified() &&
7114 VisibleTypeConversionsQuals.hasRestrict()) {
7115 // restrict version
7116 ParamTypes[0]
7117 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7119 /*IsAssigmentOperator=*/isEqualOp);
7120
7121 if (NeedVolatile) {
7122 // volatile restrict version
7123 ParamTypes[0]
7124 = S.Context.getLValueReferenceType(
7125 S.Context.getCVRQualifiedType(*Ptr,
7126 (Qualifiers::Volatile |
7127 Qualifiers::Restrict)));
7128 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7129 CandidateSet,
7130 /*IsAssigmentOperator=*/isEqualOp);
7131 }
7132 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007133 }
7134
7135 if (isEqualOp) {
7136 for (BuiltinCandidateTypeSet::iterator
7137 Ptr = CandidateTypes[1].pointer_begin(),
7138 PtrEnd = CandidateTypes[1].pointer_end();
7139 Ptr != PtrEnd; ++Ptr) {
7140 // Make sure we don't add the same candidate twice.
7141 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7142 continue;
7143
Chandler Carruth8e543b32010-12-12 08:17:55 +00007144 QualType ParamTypes[2] = {
7145 S.Context.getLValueReferenceType(*Ptr),
7146 *Ptr,
7147 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007148
7149 // non-volatile version
7150 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7151 /*IsAssigmentOperator=*/true);
7152
Douglas Gregor5bee2582012-06-04 00:15:09 +00007153 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7154 VisibleTypeConversionsQuals.hasVolatile();
7155 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007156 // volatile version
7157 ParamTypes[0] =
7158 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7160 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007162
7163 if (!(*Ptr).isRestrictQualified() &&
7164 VisibleTypeConversionsQuals.hasRestrict()) {
7165 // restrict version
7166 ParamTypes[0]
7167 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7169 CandidateSet, /*IsAssigmentOperator=*/true);
7170
7171 if (NeedVolatile) {
7172 // volatile restrict version
7173 ParamTypes[0]
7174 = S.Context.getLValueReferenceType(
7175 S.Context.getCVRQualifiedType(*Ptr,
7176 (Qualifiers::Volatile |
7177 Qualifiers::Restrict)));
7178 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7179 CandidateSet, /*IsAssigmentOperator=*/true);
7180
7181 }
7182 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007183 }
7184 }
7185 }
7186
7187 // C++ [over.built]p18:
7188 //
7189 // For every triple (L, VQ, R), where L is an arithmetic type,
7190 // VQ is either volatile or empty, and R is a promoted
7191 // arithmetic type, there exist candidate operator functions of
7192 // the form
7193 //
7194 // VQ L& operator=(VQ L&, R);
7195 // VQ L& operator*=(VQ L&, R);
7196 // VQ L& operator/=(VQ L&, R);
7197 // VQ L& operator+=(VQ L&, R);
7198 // VQ L& operator-=(VQ L&, R);
7199 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007200 if (!HasArithmeticOrEnumeralCandidateType)
7201 return;
7202
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007203 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7204 for (unsigned Right = FirstPromotedArithmeticType;
7205 Right < LastPromotedArithmeticType; ++Right) {
7206 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007207 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007208
7209 // Add this built-in operator as a candidate (VQ is empty).
7210 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007211 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7213 /*IsAssigmentOperator=*/isEqualOp);
7214
7215 // Add this built-in operator as a candidate (VQ is 'volatile').
7216 if (VisibleTypeConversionsQuals.hasVolatile()) {
7217 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007218 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007219 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007220 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7221 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007222 /*IsAssigmentOperator=*/isEqualOp);
7223 }
7224 }
7225 }
7226
7227 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7228 for (BuiltinCandidateTypeSet::iterator
7229 Vec1 = CandidateTypes[0].vector_begin(),
7230 Vec1End = CandidateTypes[0].vector_end();
7231 Vec1 != Vec1End; ++Vec1) {
7232 for (BuiltinCandidateTypeSet::iterator
7233 Vec2 = CandidateTypes[1].vector_begin(),
7234 Vec2End = CandidateTypes[1].vector_end();
7235 Vec2 != Vec2End; ++Vec2) {
7236 QualType ParamTypes[2];
7237 ParamTypes[1] = *Vec2;
7238 // Add this built-in operator as a candidate (VQ is empty).
7239 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7241 /*IsAssigmentOperator=*/isEqualOp);
7242
7243 // Add this built-in operator as a candidate (VQ is 'volatile').
7244 if (VisibleTypeConversionsQuals.hasVolatile()) {
7245 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7246 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007247 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7248 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007249 /*IsAssigmentOperator=*/isEqualOp);
7250 }
7251 }
7252 }
7253 }
7254
7255 // C++ [over.built]p22:
7256 //
7257 // For every triple (L, VQ, R), where L is an integral type, VQ
7258 // is either volatile or empty, and R is a promoted integral
7259 // type, there exist candidate operator functions of the form
7260 //
7261 // VQ L& operator%=(VQ L&, R);
7262 // VQ L& operator<<=(VQ L&, R);
7263 // VQ L& operator>>=(VQ L&, R);
7264 // VQ L& operator&=(VQ L&, R);
7265 // VQ L& operator^=(VQ L&, R);
7266 // VQ L& operator|=(VQ L&, R);
7267 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007268 if (!HasArithmeticOrEnumeralCandidateType)
7269 return;
7270
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007271 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7272 for (unsigned Right = FirstPromotedIntegralType;
7273 Right < LastPromotedIntegralType; ++Right) {
7274 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007275 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007276
7277 // Add this built-in operator as a candidate (VQ is empty).
7278 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007279 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7281 if (VisibleTypeConversionsQuals.hasVolatile()) {
7282 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007283 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7285 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7286 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7287 CandidateSet);
7288 }
7289 }
7290 }
7291 }
7292
7293 // C++ [over.operator]p23:
7294 //
7295 // There also exist candidate operator functions of the form
7296 //
7297 // bool operator!(bool);
7298 // bool operator&&(bool, bool);
7299 // bool operator||(bool, bool);
7300 void addExclaimOverload() {
7301 QualType ParamTy = S.Context.BoolTy;
7302 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7303 /*IsAssignmentOperator=*/false,
7304 /*NumContextualBoolArguments=*/1);
7305 }
7306 void addAmpAmpOrPipePipeOverload() {
7307 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7308 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7309 /*IsAssignmentOperator=*/false,
7310 /*NumContextualBoolArguments=*/2);
7311 }
7312
7313 // C++ [over.built]p13:
7314 //
7315 // For every cv-qualified or cv-unqualified object type T there
7316 // exist candidate operator functions of the form
7317 //
7318 // T* operator+(T*, ptrdiff_t); [ABOVE]
7319 // T& operator[](T*, ptrdiff_t);
7320 // T* operator-(T*, ptrdiff_t); [ABOVE]
7321 // T* operator+(ptrdiff_t, T*); [ABOVE]
7322 // T& operator[](ptrdiff_t, T*);
7323 void addSubscriptOverloads() {
7324 for (BuiltinCandidateTypeSet::iterator
7325 Ptr = CandidateTypes[0].pointer_begin(),
7326 PtrEnd = CandidateTypes[0].pointer_end();
7327 Ptr != PtrEnd; ++Ptr) {
7328 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7329 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007330 if (!PointeeType->isObjectType())
7331 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007332
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007333 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7334
7335 // T& operator[](T*, ptrdiff_t)
7336 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7337 }
7338
7339 for (BuiltinCandidateTypeSet::iterator
7340 Ptr = CandidateTypes[1].pointer_begin(),
7341 PtrEnd = CandidateTypes[1].pointer_end();
7342 Ptr != PtrEnd; ++Ptr) {
7343 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7344 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007345 if (!PointeeType->isObjectType())
7346 continue;
7347
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007348 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7349
7350 // T& operator[](ptrdiff_t, T*)
7351 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7352 }
7353 }
7354
7355 // C++ [over.built]p11:
7356 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7357 // C1 is the same type as C2 or is a derived class of C2, T is an object
7358 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7359 // there exist candidate operator functions of the form
7360 //
7361 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7362 //
7363 // where CV12 is the union of CV1 and CV2.
7364 void addArrowStarOverloads() {
7365 for (BuiltinCandidateTypeSet::iterator
7366 Ptr = CandidateTypes[0].pointer_begin(),
7367 PtrEnd = CandidateTypes[0].pointer_end();
7368 Ptr != PtrEnd; ++Ptr) {
7369 QualType C1Ty = (*Ptr);
7370 QualType C1;
7371 QualifierCollector Q1;
7372 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7373 if (!isa<RecordType>(C1))
7374 continue;
7375 // heuristic to reduce number of builtin candidates in the set.
7376 // Add volatile/restrict version only if there are conversions to a
7377 // volatile/restrict type.
7378 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7379 continue;
7380 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7381 continue;
7382 for (BuiltinCandidateTypeSet::iterator
7383 MemPtr = CandidateTypes[1].member_pointer_begin(),
7384 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7385 MemPtr != MemPtrEnd; ++MemPtr) {
7386 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7387 QualType C2 = QualType(mptr->getClass(), 0);
7388 C2 = C2.getUnqualifiedType();
7389 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7390 break;
7391 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7392 // build CV12 T&
7393 QualType T = mptr->getPointeeType();
7394 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7395 T.isVolatileQualified())
7396 continue;
7397 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7398 T.isRestrictQualified())
7399 continue;
7400 T = Q1.apply(S.Context, T);
7401 QualType ResultTy = S.Context.getLValueReferenceType(T);
7402 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7403 }
7404 }
7405 }
7406
7407 // Note that we don't consider the first argument, since it has been
7408 // contextually converted to bool long ago. The candidates below are
7409 // therefore added as binary.
7410 //
7411 // C++ [over.built]p25:
7412 // For every type T, where T is a pointer, pointer-to-member, or scoped
7413 // enumeration type, there exist candidate operator functions of the form
7414 //
7415 // T operator?(bool, T, T);
7416 //
7417 void addConditionalOperatorOverloads() {
7418 /// Set of (canonical) types that we've already handled.
7419 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7420
7421 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7422 for (BuiltinCandidateTypeSet::iterator
7423 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7424 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7425 Ptr != PtrEnd; ++Ptr) {
7426 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7427 continue;
7428
7429 QualType ParamTypes[2] = { *Ptr, *Ptr };
7430 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7431 }
7432
7433 for (BuiltinCandidateTypeSet::iterator
7434 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7435 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7436 MemPtr != MemPtrEnd; ++MemPtr) {
7437 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7438 continue;
7439
7440 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7441 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7442 }
7443
David Blaikiebbafb8a2012-03-11 07:00:24 +00007444 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007445 for (BuiltinCandidateTypeSet::iterator
7446 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7447 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7448 Enum != EnumEnd; ++Enum) {
7449 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7450 continue;
7451
7452 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7453 continue;
7454
7455 QualType ParamTypes[2] = { *Enum, *Enum };
7456 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7457 }
7458 }
7459 }
7460 }
7461};
7462
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463} // end anonymous namespace
7464
7465/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7466/// operator overloads to the candidate set (C++ [over.built]), based
7467/// on the operator @p Op and the arguments given. For example, if the
7468/// operator is a binary '+', this routine might add "int
7469/// operator+(int, int)" to cover integer addition.
7470void
7471Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7472 SourceLocation OpLoc,
7473 Expr **Args, unsigned NumArgs,
7474 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007475 // Find all of the types that the arguments can convert to, but only
7476 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007477 // that make use of these types. Also record whether we encounter non-record
7478 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007479 Qualifiers VisibleTypeConversionsQuals;
7480 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007481 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7482 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007483
7484 bool HasNonRecordCandidateType = false;
7485 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007486 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007487 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7488 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7489 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7490 OpLoc,
7491 true,
7492 (Op == OO_Exclaim ||
7493 Op == OO_AmpAmp ||
7494 Op == OO_PipePipe),
7495 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007496 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7497 CandidateTypes[ArgIdx].hasNonRecordTypes();
7498 HasArithmeticOrEnumeralCandidateType =
7499 HasArithmeticOrEnumeralCandidateType ||
7500 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007501 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007502
Chandler Carruth00a38332010-12-13 01:44:01 +00007503 // Exit early when no non-record types have been added to the candidate set
7504 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007505 //
7506 // We can't exit early for !, ||, or &&, since there we have always have
7507 // 'bool' overloads.
7508 if (!HasNonRecordCandidateType &&
7509 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007510 return;
7511
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007512 // Setup an object to manage the common state for building overloads.
7513 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7514 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007515 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 CandidateTypes, CandidateSet);
7517
7518 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007519 switch (Op) {
7520 case OO_None:
7521 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007522 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007523
Chandler Carruth5184de02010-12-12 08:51:33 +00007524 case OO_New:
7525 case OO_Delete:
7526 case OO_Array_New:
7527 case OO_Array_Delete:
7528 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007529 llvm_unreachable(
7530 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007531
7532 case OO_Comma:
7533 case OO_Arrow:
7534 // C++ [over.match.oper]p3:
7535 // -- For the operator ',', the unary operator '&', or the
7536 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007537 break;
7538
7539 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007540 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007541 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007542 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007543
7544 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007545 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007546 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007547 } else {
7548 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7549 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7550 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007551 break;
7552
Chandler Carruth5184de02010-12-12 08:51:33 +00007553 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007554 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007555 OpBuilder.addUnaryStarPointerOverloads();
7556 else
7557 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7558 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007559
Chandler Carruth5184de02010-12-12 08:51:33 +00007560 case OO_Slash:
7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007562 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007563
7564 case OO_PlusPlus:
7565 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007566 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7567 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007568 break;
7569
Douglas Gregor84605ae2009-08-24 13:43:27 +00007570 case OO_EqualEqual:
7571 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007573 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007574
Douglas Gregora11693b2008-11-12 17:17:38 +00007575 case OO_Less:
7576 case OO_Greater:
7577 case OO_LessEqual:
7578 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007579 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007580 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7581 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007582
Douglas Gregora11693b2008-11-12 17:17:38 +00007583 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007584 case OO_Caret:
7585 case OO_Pipe:
7586 case OO_LessLess:
7587 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007588 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007589 break;
7590
Chandler Carruth5184de02010-12-12 08:51:33 +00007591 case OO_Amp: // '&' is either unary or binary
7592 if (NumArgs == 1)
7593 // C++ [over.match.oper]p3:
7594 // -- For the operator ',', the unary operator '&', or the
7595 // operator '->', the built-in candidates set is empty.
7596 break;
7597
7598 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7599 break;
7600
7601 case OO_Tilde:
7602 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7603 break;
7604
Douglas Gregora11693b2008-11-12 17:17:38 +00007605 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007606 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007607 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007608
7609 case OO_PlusEqual:
7610 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007611 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007612 // Fall through.
7613
7614 case OO_StarEqual:
7615 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007616 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007617 break;
7618
7619 case OO_PercentEqual:
7620 case OO_LessLessEqual:
7621 case OO_GreaterGreaterEqual:
7622 case OO_AmpEqual:
7623 case OO_CaretEqual:
7624 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007625 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007626 break;
7627
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007628 case OO_Exclaim:
7629 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007630 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007631
Douglas Gregora11693b2008-11-12 17:17:38 +00007632 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007633 case OO_PipePipe:
7634 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007635 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007636
7637 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007638 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007639 break;
7640
7641 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007643 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007644
7645 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007647 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7648 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007649 }
7650}
7651
Douglas Gregore254f902009-02-04 00:32:51 +00007652/// \brief Add function candidates found via argument-dependent lookup
7653/// to the set of overloading candidates.
7654///
7655/// This routine performs argument-dependent name lookup based on the
7656/// given function name (which may also be an operator name) and adds
7657/// all of the overload candidates found by ADL to the overload
7658/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007659void
Douglas Gregore254f902009-02-04 00:32:51 +00007660Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007661 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007662 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007663 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007664 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007665 bool PartialOverloading,
7666 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007667 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007668
John McCall91f61fc2010-01-26 06:04:06 +00007669 // FIXME: This approach for uniquing ADL results (and removing
7670 // redundant candidates from the set) relies on pointer-equality,
7671 // which means we need to key off the canonical decl. However,
7672 // always going back to the canonical decl might not get us the
7673 // right set of default arguments. What default arguments are
7674 // we supposed to consider on ADL candidates, anyway?
7675
Douglas Gregorcabea402009-09-22 15:41:20 +00007676 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007677 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007678 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007679
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007680 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007681 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7682 CandEnd = CandidateSet.end();
7683 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007684 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007685 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007686 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007687 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007688 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007689
7690 // For each of the ADL candidates we found, add it to the overload
7691 // set.
John McCall8fe68082010-01-26 07:16:45 +00007692 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007693 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007695 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007696 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007697
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007698 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7699 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007700 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007701 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007702 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007703 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007704 }
Douglas Gregore254f902009-02-04 00:32:51 +00007705}
7706
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007707/// isBetterOverloadCandidate - Determines whether the first overload
7708/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007709bool
John McCall5c32be02010-08-24 20:38:10 +00007710isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007711 const OverloadCandidate &Cand1,
7712 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007713 SourceLocation Loc,
7714 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007715 // Define viable functions to be better candidates than non-viable
7716 // functions.
7717 if (!Cand2.Viable)
7718 return Cand1.Viable;
7719 else if (!Cand1.Viable)
7720 return false;
7721
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007722 // C++ [over.match.best]p1:
7723 //
7724 // -- if F is a static member function, ICS1(F) is defined such
7725 // that ICS1(F) is neither better nor worse than ICS1(G) for
7726 // any function G, and, symmetrically, ICS1(G) is neither
7727 // better nor worse than ICS1(F).
7728 unsigned StartArg = 0;
7729 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7730 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007731
Douglas Gregord3cb3562009-07-07 23:38:56 +00007732 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007733 // A viable function F1 is defined to be a better function than another
7734 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007735 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007736 unsigned NumArgs = Cand1.NumConversions;
7737 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007738 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007739 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007740 switch (CompareImplicitConversionSequences(S,
7741 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007742 Cand2.Conversions[ArgIdx])) {
7743 case ImplicitConversionSequence::Better:
7744 // Cand1 has a better conversion sequence.
7745 HasBetterConversion = true;
7746 break;
7747
7748 case ImplicitConversionSequence::Worse:
7749 // Cand1 can't be better than Cand2.
7750 return false;
7751
7752 case ImplicitConversionSequence::Indistinguishable:
7753 // Do nothing.
7754 break;
7755 }
7756 }
7757
Mike Stump11289f42009-09-09 15:08:12 +00007758 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007759 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007760 if (HasBetterConversion)
7761 return true;
7762
Mike Stump11289f42009-09-09 15:08:12 +00007763 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007764 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007765 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007766 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7767 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007768
7769 // -- F1 and F2 are function template specializations, and the function
7770 // template for F1 is more specialized than the template for F2
7771 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007772 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007773 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007774 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007775 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007776 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7777 Cand2.Function->getPrimaryTemplate(),
7778 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007780 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007781 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007782 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007784
Douglas Gregora1f013e2008-11-07 22:36:19 +00007785 // -- the context is an initialization by user-defined conversion
7786 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7787 // from the return type of F1 to the destination type (i.e.,
7788 // the type of the entity being initialized) is a better
7789 // conversion sequence than the standard conversion sequence
7790 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007791 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007792 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007793 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007794 // First check whether we prefer one of the conversion functions over the
7795 // other. This only distinguishes the results in non-standard, extension
7796 // cases such as the conversion from a lambda closure type to a function
7797 // pointer or block.
7798 ImplicitConversionSequence::CompareKind FuncResult
7799 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7800 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7801 return FuncResult;
7802
John McCall5c32be02010-08-24 20:38:10 +00007803 switch (CompareStandardConversionSequences(S,
7804 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007805 Cand2.FinalConversion)) {
7806 case ImplicitConversionSequence::Better:
7807 // Cand1 has a better conversion sequence.
7808 return true;
7809
7810 case ImplicitConversionSequence::Worse:
7811 // Cand1 can't be better than Cand2.
7812 return false;
7813
7814 case ImplicitConversionSequence::Indistinguishable:
7815 // Do nothing
7816 break;
7817 }
7818 }
7819
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007820 return false;
7821}
7822
Mike Stump11289f42009-09-09 15:08:12 +00007823/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007824/// within an overload candidate set.
7825///
7826/// \param CandidateSet the set of candidate functions.
7827///
7828/// \param Loc the location of the function name (or operator symbol) for
7829/// which overload resolution occurs.
7830///
Mike Stump11289f42009-09-09 15:08:12 +00007831/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007832/// function, Best points to the candidate function found.
7833///
7834/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007835OverloadingResult
7836OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007837 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007838 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007839 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007840 Best = end();
7841 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7842 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007843 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007844 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007845 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007846 }
7847
7848 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007849 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007850 return OR_No_Viable_Function;
7851
7852 // Make sure that this function is better than every other viable
7853 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007854 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007855 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007856 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007857 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007858 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007859 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007860 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007862 }
Mike Stump11289f42009-09-09 15:08:12 +00007863
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007864 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007865 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007866 (Best->Function->isDeleted() ||
7867 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007868 return OR_Deleted;
7869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007870 return OR_Success;
7871}
7872
John McCall53262c92010-01-12 02:15:36 +00007873namespace {
7874
7875enum OverloadCandidateKind {
7876 oc_function,
7877 oc_method,
7878 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007879 oc_function_template,
7880 oc_method_template,
7881 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007882 oc_implicit_default_constructor,
7883 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007884 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007885 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007886 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007887 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007888};
7889
John McCalle1ac8d12010-01-13 00:25:19 +00007890OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7891 FunctionDecl *Fn,
7892 std::string &Description) {
7893 bool isTemplate = false;
7894
7895 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7896 isTemplate = true;
7897 Description = S.getTemplateArgumentBindingsText(
7898 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7899 }
John McCallfd0b2f82010-01-06 09:43:14 +00007900
7901 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007902 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007903 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007904
Sebastian Redl08905022011-02-05 19:23:19 +00007905 if (Ctor->getInheritedConstructor())
7906 return oc_implicit_inherited_constructor;
7907
Alexis Hunt119c10e2011-05-25 23:16:36 +00007908 if (Ctor->isDefaultConstructor())
7909 return oc_implicit_default_constructor;
7910
7911 if (Ctor->isMoveConstructor())
7912 return oc_implicit_move_constructor;
7913
7914 assert(Ctor->isCopyConstructor() &&
7915 "unexpected sort of implicit constructor");
7916 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007917 }
7918
7919 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7920 // This actually gets spelled 'candidate function' for now, but
7921 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007922 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007923 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007924
Alexis Hunt119c10e2011-05-25 23:16:36 +00007925 if (Meth->isMoveAssignmentOperator())
7926 return oc_implicit_move_assignment;
7927
Douglas Gregor12695102012-02-10 08:36:38 +00007928 if (Meth->isCopyAssignmentOperator())
7929 return oc_implicit_copy_assignment;
7930
7931 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7932 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007933 }
7934
John McCalle1ac8d12010-01-13 00:25:19 +00007935 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007936}
7937
Sebastian Redl08905022011-02-05 19:23:19 +00007938void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7939 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7940 if (!Ctor) return;
7941
7942 Ctor = Ctor->getInheritedConstructor();
7943 if (!Ctor) return;
7944
7945 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7946}
7947
John McCall53262c92010-01-12 02:15:36 +00007948} // end anonymous namespace
7949
7950// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007951void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007952 std::string FnDesc;
7953 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007954 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7955 << (unsigned) K << FnDesc;
7956 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7957 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007958 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007959}
7960
Douglas Gregorb491ed32011-02-19 21:32:49 +00007961//Notes the location of all overload candidates designated through
7962// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007963void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007964 assert(OverloadedExpr->getType() == Context.OverloadTy);
7965
7966 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7967 OverloadExpr *OvlExpr = Ovl.Expression;
7968
7969 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7970 IEnd = OvlExpr->decls_end();
7971 I != IEnd; ++I) {
7972 if (FunctionTemplateDecl *FunTmpl =
7973 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007974 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007975 } else if (FunctionDecl *Fun
7976 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007977 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007978 }
7979 }
7980}
7981
John McCall0d1da222010-01-12 00:44:57 +00007982/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7983/// "lead" diagnostic; it will be given two arguments, the source and
7984/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007985void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7986 Sema &S,
7987 SourceLocation CaretLoc,
7988 const PartialDiagnostic &PDiag) const {
7989 S.Diag(CaretLoc, PDiag)
7990 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007991 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007992 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7993 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007994 }
John McCall12f97bc2010-01-08 04:41:39 +00007995}
7996
John McCall0d1da222010-01-12 00:44:57 +00007997namespace {
7998
John McCall6a61b522010-01-13 09:16:55 +00007999void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8000 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8001 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008002 assert(Cand->Function && "for now, candidate must be a function");
8003 FunctionDecl *Fn = Cand->Function;
8004
8005 // There's a conversion slot for the object argument if this is a
8006 // non-constructor method. Note that 'I' corresponds the
8007 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008008 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008009 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008010 if (I == 0)
8011 isObjectArgument = true;
8012 else
8013 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008014 }
8015
John McCalle1ac8d12010-01-13 00:25:19 +00008016 std::string FnDesc;
8017 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8018
John McCall6a61b522010-01-13 09:16:55 +00008019 Expr *FromExpr = Conv.Bad.FromExpr;
8020 QualType FromTy = Conv.Bad.getFromType();
8021 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008022
John McCallfb7ad0f2010-02-02 02:42:52 +00008023 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008024 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008025 Expr *E = FromExpr->IgnoreParens();
8026 if (isa<UnaryOperator>(E))
8027 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008028 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008029
8030 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8031 << (unsigned) FnKind << FnDesc
8032 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8033 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008034 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008035 return;
8036 }
8037
John McCall6d174642010-01-23 08:10:49 +00008038 // Do some hand-waving analysis to see if the non-viability is due
8039 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008040 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8041 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8042 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8043 CToTy = RT->getPointeeType();
8044 else {
8045 // TODO: detect and diagnose the full richness of const mismatches.
8046 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8047 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8048 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8049 }
8050
8051 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8052 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008053 Qualifiers FromQs = CFromTy.getQualifiers();
8054 Qualifiers ToQs = CToTy.getQualifiers();
8055
8056 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8058 << (unsigned) FnKind << FnDesc
8059 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8060 << FromTy
8061 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8062 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008063 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008064 return;
8065 }
8066
John McCall31168b02011-06-15 23:02:42 +00008067 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008069 << (unsigned) FnKind << FnDesc
8070 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8071 << FromTy
8072 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8073 << (unsigned) isObjectArgument << I+1;
8074 MaybeEmitInheritedConstructorNote(S, Fn);
8075 return;
8076 }
8077
Douglas Gregoraec25842011-04-26 23:16:46 +00008078 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8080 << (unsigned) FnKind << FnDesc
8081 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8082 << FromTy
8083 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8084 << (unsigned) isObjectArgument << I+1;
8085 MaybeEmitInheritedConstructorNote(S, Fn);
8086 return;
8087 }
8088
John McCall47000992010-01-14 03:28:57 +00008089 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8090 assert(CVR && "unexpected qualifiers mismatch");
8091
8092 if (isObjectArgument) {
8093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8094 << (unsigned) FnKind << FnDesc
8095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8096 << FromTy << (CVR - 1);
8097 } else {
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8099 << (unsigned) FnKind << FnDesc
8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8101 << FromTy << (CVR - 1) << I+1;
8102 }
Sebastian Redl08905022011-02-05 19:23:19 +00008103 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008104 return;
8105 }
8106
Sebastian Redla72462c2011-09-24 17:48:32 +00008107 // Special diagnostic for failure to convert an initializer list, since
8108 // telling the user that it has type void is not useful.
8109 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8111 << (unsigned) FnKind << FnDesc
8112 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8113 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8114 MaybeEmitInheritedConstructorNote(S, Fn);
8115 return;
8116 }
8117
John McCall6d174642010-01-23 08:10:49 +00008118 // Diagnose references or pointers to incomplete types differently,
8119 // since it's far from impossible that the incompleteness triggered
8120 // the failure.
8121 QualType TempFromTy = FromTy.getNonReferenceType();
8122 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8123 TempFromTy = PTy->getPointeeType();
8124 if (TempFromTy->isIncompleteType()) {
8125 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8126 << (unsigned) FnKind << FnDesc
8127 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8128 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008129 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008130 return;
8131 }
8132
Douglas Gregor56f2e342010-06-30 23:01:39 +00008133 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008134 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008135 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8136 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8137 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8138 FromPtrTy->getPointeeType()) &&
8139 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8140 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008142 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008143 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008144 }
8145 } else if (const ObjCObjectPointerType *FromPtrTy
8146 = FromTy->getAs<ObjCObjectPointerType>()) {
8147 if (const ObjCObjectPointerType *ToPtrTy
8148 = ToTy->getAs<ObjCObjectPointerType>())
8149 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8150 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8152 FromPtrTy->getPointeeType()) &&
8153 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008154 BaseToDerivedConversion = 2;
8155 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008156 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8157 !FromTy->isIncompleteType() &&
8158 !ToRefTy->getPointeeType()->isIncompleteType() &&
8159 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8160 BaseToDerivedConversion = 3;
8161 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8162 ToTy.getNonReferenceType().getCanonicalType() ==
8163 FromTy.getNonReferenceType().getCanonicalType()) {
8164 QualType T1 = ToTy.getCanonicalType();
8165 QualType T2 = ToTy.getNonReferenceType();
8166 QualType T3 = T2.getUnqualifiedType();
8167 QualType T4 = FromTy.getCanonicalType();
8168 (void)T1; (void)T2; (void)T3; (void)T4;
8169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8170 << (unsigned) FnKind << FnDesc
8171 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8172 << (unsigned) isObjectArgument << I + 1;
8173 MaybeEmitInheritedConstructorNote(S, Fn);
8174 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008175 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008177
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008178 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008179 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008180 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008181 << (unsigned) FnKind << FnDesc
8182 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008183 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008184 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008185 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008186 return;
8187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008188
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008189 if (isa<ObjCObjectPointerType>(CFromTy) &&
8190 isa<PointerType>(CToTy)) {
8191 Qualifiers FromQs = CFromTy.getQualifiers();
8192 Qualifiers ToQs = CToTy.getQualifiers();
8193 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8195 << (unsigned) FnKind << FnDesc
8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8197 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8198 MaybeEmitInheritedConstructorNote(S, Fn);
8199 return;
8200 }
8201 }
8202
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008203 // Emit the generic diagnostic and, optionally, add the hints to it.
8204 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8205 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008206 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008207 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8208 << (unsigned) (Cand->Fix.Kind);
8209
8210 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008211 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8212 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008213 FDiag << *HI;
8214 S.Diag(Fn->getLocation(), FDiag);
8215
Sebastian Redl08905022011-02-05 19:23:19 +00008216 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008217}
8218
8219void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8220 unsigned NumFormalArgs) {
8221 // TODO: treat calls to a missing default constructor as a special case
8222
8223 FunctionDecl *Fn = Cand->Function;
8224 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8225
8226 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008227
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008228 // With invalid overloaded operators, it's possible that we think we
8229 // have an arity mismatch when it fact it looks like we have the
8230 // right number of arguments, because only overloaded operators have
8231 // the weird behavior of overloading member and non-member functions.
8232 // Just don't report anything.
8233 if (Fn->isInvalidDecl() &&
8234 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8235 return;
8236
John McCall6a61b522010-01-13 09:16:55 +00008237 // at least / at most / exactly
8238 unsigned mode, modeCount;
8239 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008240 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8241 (Cand->FailureKind == ovl_fail_bad_deduction &&
8242 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008244 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008245 mode = 0; // "at least"
8246 else
8247 mode = 2; // "exactly"
8248 modeCount = MinParams;
8249 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008250 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8251 (Cand->FailureKind == ovl_fail_bad_deduction &&
8252 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008253 if (MinParams != FnTy->getNumArgs())
8254 mode = 1; // "at most"
8255 else
8256 mode = 2; // "exactly"
8257 modeCount = FnTy->getNumArgs();
8258 }
8259
8260 std::string Description;
8261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8262
Richard Smith10ff50d2012-05-11 05:16:41 +00008263 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8265 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8266 << Fn->getParamDecl(0) << NumFormalArgs;
8267 else
8268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8269 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8270 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008271 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008272}
8273
John McCall8b9ed552010-02-01 18:53:26 +00008274/// Diagnose a failed template-argument deduction.
8275void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008276 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008277 FunctionDecl *Fn = Cand->Function; // pattern
8278
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008279 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008280 NamedDecl *ParamD;
8281 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8282 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8283 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008284 switch (Cand->DeductionFailure.Result) {
8285 case Sema::TDK_Success:
8286 llvm_unreachable("TDK_success while diagnosing bad deduction");
8287
8288 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008289 assert(ParamD && "no parameter found for incomplete deduction result");
8290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8291 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008292 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008293 return;
8294 }
8295
John McCall42d7d192010-08-05 09:05:08 +00008296 case Sema::TDK_Underqualified: {
8297 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8298 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8299
8300 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8301
8302 // Param will have been canonicalized, but it should just be a
8303 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008304 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008305 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008306 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008307 assert(S.Context.hasSameType(Param, NonCanonParam));
8308
8309 // Arg has also been canonicalized, but there's nothing we can do
8310 // about that. It also doesn't matter as much, because it won't
8311 // have any template parameters in it (because deduction isn't
8312 // done on dependent types).
8313 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8314
8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8316 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008317 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008318 return;
8319 }
8320
8321 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008322 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008323 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008324 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008325 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008326 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008327 which = 1;
8328 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008329 which = 2;
8330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008331
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008333 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008334 << *Cand->DeductionFailure.getFirstArg()
8335 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008336 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008337 return;
8338 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008339
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008340 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008341 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008342 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008343 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008344 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8345 << ParamD->getDeclName();
8346 else {
8347 int index = 0;
8348 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8349 index = TTP->getIndex();
8350 else if (NonTypeTemplateParmDecl *NTTP
8351 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8352 index = NTTP->getIndex();
8353 else
8354 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008355 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008356 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8357 << (index + 1);
8358 }
Sebastian Redl08905022011-02-05 19:23:19 +00008359 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008360 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008361
Douglas Gregor02eb4832010-05-08 18:13:28 +00008362 case Sema::TDK_TooManyArguments:
8363 case Sema::TDK_TooFewArguments:
8364 DiagnoseArityMismatch(S, Cand, NumArgs);
8365 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008366
8367 case Sema::TDK_InstantiationDepth:
8368 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008369 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008370 return;
8371
8372 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008373 // Format the template argument list into the argument string.
8374 llvm::SmallString<128> TemplateArgString;
8375 if (TemplateArgumentList *Args =
8376 Cand->DeductionFailure.getTemplateArgumentList()) {
8377 TemplateArgString = " ";
8378 TemplateArgString += S.getTemplateArgumentBindingsText(
8379 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8380 }
8381
Richard Smith6f8d2c62012-05-09 05:17:00 +00008382 // If this candidate was disabled by enable_if, say so.
8383 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8384 if (PDiag && PDiag->second.getDiagID() ==
8385 diag::err_typename_nested_not_found_enable_if) {
8386 // FIXME: Use the source range of the condition, and the fully-qualified
8387 // name of the enable_if template. These are both present in PDiag.
8388 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8389 << "'enable_if'" << TemplateArgString;
8390 return;
8391 }
8392
Richard Smith9ca64612012-05-07 09:03:25 +00008393 // Format the SFINAE diagnostic into the argument string.
8394 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8395 // formatted message in another diagnostic.
8396 llvm::SmallString<128> SFINAEArgString;
8397 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008398 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008399 SFINAEArgString = ": ";
8400 R = SourceRange(PDiag->first, PDiag->first);
8401 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8402 }
8403
Douglas Gregord09efd42010-05-08 20:07:26 +00008404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008405 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008406 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008407 return;
8408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008409
John McCall8b9ed552010-02-01 18:53:26 +00008410 // TODO: diagnose these individually, then kill off
8411 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008412 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008413 case Sema::TDK_FailedOverloadResolution:
8414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008415 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008416 return;
8417 }
8418}
8419
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008420/// CUDA: diagnose an invalid call across targets.
8421void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8422 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8423 FunctionDecl *Callee = Cand->Function;
8424
8425 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8426 CalleeTarget = S.IdentifyCUDATarget(Callee);
8427
8428 std::string FnDesc;
8429 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8430
8431 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8432 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8433}
8434
John McCall8b9ed552010-02-01 18:53:26 +00008435/// Generates a 'note' diagnostic for an overload candidate. We've
8436/// already generated a primary error at the call site.
8437///
8438/// It really does need to be a single diagnostic with its caret
8439/// pointed at the candidate declaration. Yes, this creates some
8440/// major challenges of technical writing. Yes, this makes pointing
8441/// out problems with specific arguments quite awkward. It's still
8442/// better than generating twenty screens of text for every failed
8443/// overload.
8444///
8445/// It would be great to be able to express per-candidate problems
8446/// more richly for those diagnostic clients that cared, but we'd
8447/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008448void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008449 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008450 FunctionDecl *Fn = Cand->Function;
8451
John McCall12f97bc2010-01-08 04:41:39 +00008452 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008453 if (Cand->Viable && (Fn->isDeleted() ||
8454 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008455 std::string FnDesc;
8456 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008457
8458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008459 << FnKind << FnDesc
8460 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008461 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008462 return;
John McCall12f97bc2010-01-08 04:41:39 +00008463 }
8464
John McCalle1ac8d12010-01-13 00:25:19 +00008465 // We don't really have anything else to say about viable candidates.
8466 if (Cand->Viable) {
8467 S.NoteOverloadCandidate(Fn);
8468 return;
8469 }
John McCall0d1da222010-01-12 00:44:57 +00008470
John McCall6a61b522010-01-13 09:16:55 +00008471 switch (Cand->FailureKind) {
8472 case ovl_fail_too_many_arguments:
8473 case ovl_fail_too_few_arguments:
8474 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008475
John McCall6a61b522010-01-13 09:16:55 +00008476 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008477 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008478
John McCallfe796dd2010-01-23 05:17:32 +00008479 case ovl_fail_trivial_conversion:
8480 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008481 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008482 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008483
John McCall65eb8792010-02-25 01:37:24 +00008484 case ovl_fail_bad_conversion: {
8485 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008486 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008487 if (Cand->Conversions[I].isBad())
8488 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008489
John McCall6a61b522010-01-13 09:16:55 +00008490 // FIXME: this currently happens when we're called from SemaInit
8491 // when user-conversion overload fails. Figure out how to handle
8492 // those conditions and diagnose them well.
8493 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008494 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008495
8496 case ovl_fail_bad_target:
8497 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008498 }
John McCalld3224162010-01-08 00:58:21 +00008499}
8500
8501void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8502 // Desugar the type of the surrogate down to a function type,
8503 // retaining as many typedefs as possible while still showing
8504 // the function type (and, therefore, its parameter types).
8505 QualType FnType = Cand->Surrogate->getConversionType();
8506 bool isLValueReference = false;
8507 bool isRValueReference = false;
8508 bool isPointer = false;
8509 if (const LValueReferenceType *FnTypeRef =
8510 FnType->getAs<LValueReferenceType>()) {
8511 FnType = FnTypeRef->getPointeeType();
8512 isLValueReference = true;
8513 } else if (const RValueReferenceType *FnTypeRef =
8514 FnType->getAs<RValueReferenceType>()) {
8515 FnType = FnTypeRef->getPointeeType();
8516 isRValueReference = true;
8517 }
8518 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8519 FnType = FnTypePtr->getPointeeType();
8520 isPointer = true;
8521 }
8522 // Desugar down to a function type.
8523 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8524 // Reconstruct the pointer/reference as appropriate.
8525 if (isPointer) FnType = S.Context.getPointerType(FnType);
8526 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8527 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8528
8529 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8530 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008531 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008532}
8533
8534void NoteBuiltinOperatorCandidate(Sema &S,
8535 const char *Opc,
8536 SourceLocation OpLoc,
8537 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008538 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008539 std::string TypeStr("operator");
8540 TypeStr += Opc;
8541 TypeStr += "(";
8542 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008543 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008544 TypeStr += ")";
8545 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8546 } else {
8547 TypeStr += ", ";
8548 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8549 TypeStr += ")";
8550 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8551 }
8552}
8553
8554void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8555 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008556 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008557 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8558 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008559 if (ICS.isBad()) break; // all meaningless after first invalid
8560 if (!ICS.isAmbiguous()) continue;
8561
John McCall5c32be02010-08-24 20:38:10 +00008562 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008563 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008564 }
8565}
8566
John McCall3712d9e2010-01-15 23:32:50 +00008567SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8568 if (Cand->Function)
8569 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008570 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008571 return Cand->Surrogate->getLocation();
8572 return SourceLocation();
8573}
8574
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008575static unsigned
8576RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008577 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008578 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008579 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008580
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008581 case Sema::TDK_Incomplete:
8582 return 1;
8583
8584 case Sema::TDK_Underqualified:
8585 case Sema::TDK_Inconsistent:
8586 return 2;
8587
8588 case Sema::TDK_SubstitutionFailure:
8589 case Sema::TDK_NonDeducedMismatch:
8590 return 3;
8591
8592 case Sema::TDK_InstantiationDepth:
8593 case Sema::TDK_FailedOverloadResolution:
8594 return 4;
8595
8596 case Sema::TDK_InvalidExplicitArguments:
8597 return 5;
8598
8599 case Sema::TDK_TooManyArguments:
8600 case Sema::TDK_TooFewArguments:
8601 return 6;
8602 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008603 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008604}
8605
John McCallad2587a2010-01-12 00:48:53 +00008606struct CompareOverloadCandidatesForDisplay {
8607 Sema &S;
8608 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008609
8610 bool operator()(const OverloadCandidate *L,
8611 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008612 // Fast-path this check.
8613 if (L == R) return false;
8614
John McCall12f97bc2010-01-08 04:41:39 +00008615 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008616 if (L->Viable) {
8617 if (!R->Viable) return true;
8618
8619 // TODO: introduce a tri-valued comparison for overload
8620 // candidates. Would be more worthwhile if we had a sort
8621 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008622 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8623 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008624 } else if (R->Viable)
8625 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008626
John McCall3712d9e2010-01-15 23:32:50 +00008627 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008628
John McCall3712d9e2010-01-15 23:32:50 +00008629 // Criteria by which we can sort non-viable candidates:
8630 if (!L->Viable) {
8631 // 1. Arity mismatches come after other candidates.
8632 if (L->FailureKind == ovl_fail_too_many_arguments ||
8633 L->FailureKind == ovl_fail_too_few_arguments)
8634 return false;
8635 if (R->FailureKind == ovl_fail_too_many_arguments ||
8636 R->FailureKind == ovl_fail_too_few_arguments)
8637 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008638
John McCallfe796dd2010-01-23 05:17:32 +00008639 // 2. Bad conversions come first and are ordered by the number
8640 // of bad conversions and quality of good conversions.
8641 if (L->FailureKind == ovl_fail_bad_conversion) {
8642 if (R->FailureKind != ovl_fail_bad_conversion)
8643 return true;
8644
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008645 // The conversion that can be fixed with a smaller number of changes,
8646 // comes first.
8647 unsigned numLFixes = L->Fix.NumConversionsFixed;
8648 unsigned numRFixes = R->Fix.NumConversionsFixed;
8649 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8650 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008651 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008652 if (numLFixes < numRFixes)
8653 return true;
8654 else
8655 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008656 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008657
John McCallfe796dd2010-01-23 05:17:32 +00008658 // If there's any ordering between the defined conversions...
8659 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008660 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008661
8662 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008663 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008664 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008665 switch (CompareImplicitConversionSequences(S,
8666 L->Conversions[I],
8667 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008668 case ImplicitConversionSequence::Better:
8669 leftBetter++;
8670 break;
8671
8672 case ImplicitConversionSequence::Worse:
8673 leftBetter--;
8674 break;
8675
8676 case ImplicitConversionSequence::Indistinguishable:
8677 break;
8678 }
8679 }
8680 if (leftBetter > 0) return true;
8681 if (leftBetter < 0) return false;
8682
8683 } else if (R->FailureKind == ovl_fail_bad_conversion)
8684 return false;
8685
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008686 if (L->FailureKind == ovl_fail_bad_deduction) {
8687 if (R->FailureKind != ovl_fail_bad_deduction)
8688 return true;
8689
8690 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8691 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008692 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008693 } else if (R->FailureKind == ovl_fail_bad_deduction)
8694 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008695
John McCall3712d9e2010-01-15 23:32:50 +00008696 // TODO: others?
8697 }
8698
8699 // Sort everything else by location.
8700 SourceLocation LLoc = GetLocationForCandidate(L);
8701 SourceLocation RLoc = GetLocationForCandidate(R);
8702
8703 // Put candidates without locations (e.g. builtins) at the end.
8704 if (LLoc.isInvalid()) return false;
8705 if (RLoc.isInvalid()) return true;
8706
8707 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008708 }
8709};
8710
John McCallfe796dd2010-01-23 05:17:32 +00008711/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008712/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008713void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008714 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008715 assert(!Cand->Viable);
8716
8717 // Don't do anything on failures other than bad conversion.
8718 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8719
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008720 // We only want the FixIts if all the arguments can be corrected.
8721 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008722 // Use a implicit copy initialization to check conversion fixes.
8723 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008724
John McCallfe796dd2010-01-23 05:17:32 +00008725 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008726 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008727 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008728 while (true) {
8729 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8730 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008731 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008732 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008733 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008734 }
John McCallfe796dd2010-01-23 05:17:32 +00008735 }
8736
8737 if (ConvIdx == ConvCount)
8738 return;
8739
John McCall65eb8792010-02-25 01:37:24 +00008740 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8741 "remaining conversion is initialized?");
8742
Douglas Gregoradc7a702010-04-16 17:45:54 +00008743 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008744 // operation somehow.
8745 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008746
8747 const FunctionProtoType* Proto;
8748 unsigned ArgIdx = ConvIdx;
8749
8750 if (Cand->IsSurrogate) {
8751 QualType ConvType
8752 = Cand->Surrogate->getConversionType().getNonReferenceType();
8753 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8754 ConvType = ConvPtrType->getPointeeType();
8755 Proto = ConvType->getAs<FunctionProtoType>();
8756 ArgIdx--;
8757 } else if (Cand->Function) {
8758 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8759 if (isa<CXXMethodDecl>(Cand->Function) &&
8760 !isa<CXXConstructorDecl>(Cand->Function))
8761 ArgIdx--;
8762 } else {
8763 // Builtin binary operator with a bad first conversion.
8764 assert(ConvCount <= 3);
8765 for (; ConvIdx != ConvCount; ++ConvIdx)
8766 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008767 = TryCopyInitialization(S, Args[ConvIdx],
8768 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008769 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008770 /*InOverloadResolution*/ true,
8771 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008772 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008773 return;
8774 }
8775
8776 // Fill in the rest of the conversions.
8777 unsigned NumArgsInProto = Proto->getNumArgs();
8778 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008779 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008780 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008781 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008782 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008783 /*InOverloadResolution=*/true,
8784 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008785 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008786 // Store the FixIt in the candidate if it exists.
8787 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008788 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008789 }
John McCallfe796dd2010-01-23 05:17:32 +00008790 else
8791 Cand->Conversions[ConvIdx].setEllipsis();
8792 }
8793}
8794
John McCalld3224162010-01-08 00:58:21 +00008795} // end anonymous namespace
8796
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008797/// PrintOverloadCandidates - When overload resolution fails, prints
8798/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008799/// set.
John McCall5c32be02010-08-24 20:38:10 +00008800void OverloadCandidateSet::NoteCandidates(Sema &S,
8801 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008802 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008803 const char *Opc,
8804 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008805 // Sort the candidates by viability and position. Sorting directly would
8806 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008807 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008808 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8809 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008810 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008811 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008812 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008813 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008814 if (Cand->Function || Cand->IsSurrogate)
8815 Cands.push_back(Cand);
8816 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8817 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008818 }
8819 }
8820
John McCallad2587a2010-01-12 00:48:53 +00008821 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008822 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008823
John McCall0d1da222010-01-12 00:44:57 +00008824 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008825
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008826 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008827 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8828 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008829 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008830 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8831 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008832
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008833 // Set an arbitrary limit on the number of candidate functions we'll spam
8834 // the user with. FIXME: This limit should depend on details of the
8835 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008836 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008837 break;
8838 }
8839 ++CandsShown;
8840
John McCalld3224162010-01-08 00:58:21 +00008841 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008842 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008843 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008844 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008845 else {
8846 assert(Cand->Viable &&
8847 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008848 // Generally we only see ambiguities including viable builtin
8849 // operators if overload resolution got screwed up by an
8850 // ambiguous user-defined conversion.
8851 //
8852 // FIXME: It's quite possible for different conversions to see
8853 // different ambiguities, though.
8854 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008855 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008856 ReportedAmbiguousConversions = true;
8857 }
John McCalld3224162010-01-08 00:58:21 +00008858
John McCall0d1da222010-01-12 00:44:57 +00008859 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008860 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008862 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008863
8864 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008865 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008866}
8867
Douglas Gregorb491ed32011-02-19 21:32:49 +00008868// [PossiblyAFunctionType] --> [Return]
8869// NonFunctionType --> NonFunctionType
8870// R (A) --> R(A)
8871// R (*)(A) --> R (A)
8872// R (&)(A) --> R (A)
8873// R (S::*)(A) --> R (A)
8874QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8875 QualType Ret = PossiblyAFunctionType;
8876 if (const PointerType *ToTypePtr =
8877 PossiblyAFunctionType->getAs<PointerType>())
8878 Ret = ToTypePtr->getPointeeType();
8879 else if (const ReferenceType *ToTypeRef =
8880 PossiblyAFunctionType->getAs<ReferenceType>())
8881 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008882 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008883 PossiblyAFunctionType->getAs<MemberPointerType>())
8884 Ret = MemTypePtr->getPointeeType();
8885 Ret =
8886 Context.getCanonicalType(Ret).getUnqualifiedType();
8887 return Ret;
8888}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008889
Douglas Gregorb491ed32011-02-19 21:32:49 +00008890// A helper class to help with address of function resolution
8891// - allows us to avoid passing around all those ugly parameters
8892class AddressOfFunctionResolver
8893{
8894 Sema& S;
8895 Expr* SourceExpr;
8896 const QualType& TargetType;
8897 QualType TargetFunctionType; // Extracted function type from target type
8898
8899 bool Complain;
8900 //DeclAccessPair& ResultFunctionAccessPair;
8901 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008902
Douglas Gregorb491ed32011-02-19 21:32:49 +00008903 bool TargetTypeIsNonStaticMemberFunction;
8904 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008905
Douglas Gregorb491ed32011-02-19 21:32:49 +00008906 OverloadExpr::FindResult OvlExprInfo;
8907 OverloadExpr *OvlExpr;
8908 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008909 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008910
Douglas Gregorb491ed32011-02-19 21:32:49 +00008911public:
8912 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8913 const QualType& TargetType, bool Complain)
8914 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8915 Complain(Complain), Context(S.getASTContext()),
8916 TargetTypeIsNonStaticMemberFunction(
8917 !!TargetType->getAs<MemberPointerType>()),
8918 FoundNonTemplateFunction(false),
8919 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8920 OvlExpr(OvlExprInfo.Expression)
8921 {
8922 ExtractUnqualifiedFunctionTypeFromTargetType();
8923
8924 if (!TargetFunctionType->isFunctionType()) {
8925 if (OvlExpr->hasExplicitTemplateArgs()) {
8926 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008927 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008928 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008929
8930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8931 if (!Method->isStatic()) {
8932 // If the target type is a non-function type and the function
8933 // found is a non-static member function, pretend as if that was
8934 // the target, it's the only possible type to end up with.
8935 TargetTypeIsNonStaticMemberFunction = true;
8936
8937 // And skip adding the function if its not in the proper form.
8938 // We'll diagnose this due to an empty set of functions.
8939 if (!OvlExprInfo.HasFormOfMemberPointer)
8940 return;
8941 }
8942 }
8943
Douglas Gregorb491ed32011-02-19 21:32:49 +00008944 Matches.push_back(std::make_pair(dap,Fn));
8945 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008946 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008947 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008948 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008949
8950 if (OvlExpr->hasExplicitTemplateArgs())
8951 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008952
Douglas Gregorb491ed32011-02-19 21:32:49 +00008953 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8954 // C++ [over.over]p4:
8955 // If more than one function is selected, [...]
8956 if (Matches.size() > 1) {
8957 if (FoundNonTemplateFunction)
8958 EliminateAllTemplateMatches();
8959 else
8960 EliminateAllExceptMostSpecializedTemplate();
8961 }
8962 }
8963 }
8964
8965private:
8966 bool isTargetTypeAFunction() const {
8967 return TargetFunctionType->isFunctionType();
8968 }
8969
8970 // [ToType] [Return]
8971
8972 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8973 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8974 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8975 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8976 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8977 }
8978
8979 // return true if any matching specializations were found
8980 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8981 const DeclAccessPair& CurAccessFunPair) {
8982 if (CXXMethodDecl *Method
8983 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8984 // Skip non-static function templates when converting to pointer, and
8985 // static when converting to member pointer.
8986 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8987 return false;
8988 }
8989 else if (TargetTypeIsNonStaticMemberFunction)
8990 return false;
8991
8992 // C++ [over.over]p2:
8993 // If the name is a function template, template argument deduction is
8994 // done (14.8.2.2), and if the argument deduction succeeds, the
8995 // resulting template argument list is used to generate a single
8996 // function template specialization, which is added to the set of
8997 // overloaded functions considered.
8998 FunctionDecl *Specialization = 0;
8999 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
9000 if (Sema::TemplateDeductionResult Result
9001 = S.DeduceTemplateArguments(FunctionTemplate,
9002 &OvlExplicitTemplateArgs,
9003 TargetFunctionType, Specialization,
9004 Info)) {
9005 // FIXME: make a note of the failed deduction for diagnostics.
9006 (void)Result;
9007 return false;
9008 }
9009
9010 // Template argument deduction ensures that we have an exact match.
9011 // This function template specicalization works.
9012 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9013 assert(TargetFunctionType
9014 == Context.getCanonicalType(Specialization->getType()));
9015 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9016 return true;
9017 }
9018
9019 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9020 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009021 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009022 // Skip non-static functions when converting to pointer, and static
9023 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009024 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9025 return false;
9026 }
9027 else if (TargetTypeIsNonStaticMemberFunction)
9028 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009029
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009030 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009031 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009032 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9033 if (S.CheckCUDATarget(Caller, FunDecl))
9034 return false;
9035
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009036 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009037 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9038 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009039 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9040 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009041 Matches.push_back(std::make_pair(CurAccessFunPair,
9042 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009043 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009044 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009045 }
Mike Stump11289f42009-09-09 15:08:12 +00009046 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009047
9048 return false;
9049 }
9050
9051 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9052 bool Ret = false;
9053
9054 // If the overload expression doesn't have the form of a pointer to
9055 // member, don't try to convert it to a pointer-to-member type.
9056 if (IsInvalidFormOfPointerToMemberFunction())
9057 return false;
9058
9059 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9060 E = OvlExpr->decls_end();
9061 I != E; ++I) {
9062 // Look through any using declarations to find the underlying function.
9063 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9064
9065 // C++ [over.over]p3:
9066 // Non-member functions and static member functions match
9067 // targets of type "pointer-to-function" or "reference-to-function."
9068 // Nonstatic member functions match targets of
9069 // type "pointer-to-member-function."
9070 // Note that according to DR 247, the containing class does not matter.
9071 if (FunctionTemplateDecl *FunctionTemplate
9072 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9073 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9074 Ret = true;
9075 }
9076 // If we have explicit template arguments supplied, skip non-templates.
9077 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9078 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9079 Ret = true;
9080 }
9081 assert(Ret || Matches.empty());
9082 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009083 }
9084
Douglas Gregorb491ed32011-02-19 21:32:49 +00009085 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009086 // [...] and any given function template specialization F1 is
9087 // eliminated if the set contains a second function template
9088 // specialization whose function template is more specialized
9089 // than the function template of F1 according to the partial
9090 // ordering rules of 14.5.5.2.
9091
9092 // The algorithm specified above is quadratic. We instead use a
9093 // two-pass algorithm (similar to the one used to identify the
9094 // best viable function in an overload set) that identifies the
9095 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009096
9097 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9098 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9099 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009100
John McCall58cc69d2010-01-27 01:50:18 +00009101 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009102 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9103 TPOC_Other, 0, SourceExpr->getLocStart(),
9104 S.PDiag(),
9105 S.PDiag(diag::err_addr_ovl_ambiguous)
9106 << Matches[0].second->getDeclName(),
9107 S.PDiag(diag::note_ovl_candidate)
9108 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009109 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009110
Douglas Gregorb491ed32011-02-19 21:32:49 +00009111 if (Result != MatchesCopy.end()) {
9112 // Make it the first and only element
9113 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9114 Matches[0].second = cast<FunctionDecl>(*Result);
9115 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009116 }
9117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009118
Douglas Gregorb491ed32011-02-19 21:32:49 +00009119 void EliminateAllTemplateMatches() {
9120 // [...] any function template specializations in the set are
9121 // eliminated if the set also contains a non-template function, [...]
9122 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9123 if (Matches[I].second->getPrimaryTemplate() == 0)
9124 ++I;
9125 else {
9126 Matches[I] = Matches[--N];
9127 Matches.set_size(N);
9128 }
9129 }
9130 }
9131
9132public:
9133 void ComplainNoMatchesFound() const {
9134 assert(Matches.empty());
9135 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9136 << OvlExpr->getName() << TargetFunctionType
9137 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009138 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009139 }
9140
9141 bool IsInvalidFormOfPointerToMemberFunction() const {
9142 return TargetTypeIsNonStaticMemberFunction &&
9143 !OvlExprInfo.HasFormOfMemberPointer;
9144 }
9145
9146 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9147 // TODO: Should we condition this on whether any functions might
9148 // have matched, or is it more appropriate to do that in callers?
9149 // TODO: a fixit wouldn't hurt.
9150 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9151 << TargetType << OvlExpr->getSourceRange();
9152 }
9153
9154 void ComplainOfInvalidConversion() const {
9155 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9156 << OvlExpr->getName() << TargetType;
9157 }
9158
9159 void ComplainMultipleMatchesFound() const {
9160 assert(Matches.size() > 1);
9161 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9162 << OvlExpr->getName()
9163 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009164 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009165 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009166
9167 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9168
Douglas Gregorb491ed32011-02-19 21:32:49 +00009169 int getNumMatches() const { return Matches.size(); }
9170
9171 FunctionDecl* getMatchingFunctionDecl() const {
9172 if (Matches.size() != 1) return 0;
9173 return Matches[0].second;
9174 }
9175
9176 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9177 if (Matches.size() != 1) return 0;
9178 return &Matches[0].first;
9179 }
9180};
9181
9182/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9183/// an overloaded function (C++ [over.over]), where @p From is an
9184/// expression with overloaded function type and @p ToType is the type
9185/// we're trying to resolve to. For example:
9186///
9187/// @code
9188/// int f(double);
9189/// int f(int);
9190///
9191/// int (*pfd)(double) = f; // selects f(double)
9192/// @endcode
9193///
9194/// This routine returns the resulting FunctionDecl if it could be
9195/// resolved, and NULL otherwise. When @p Complain is true, this
9196/// routine will emit diagnostics if there is an error.
9197FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009198Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9199 QualType TargetType,
9200 bool Complain,
9201 DeclAccessPair &FoundResult,
9202 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009203 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009204
9205 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9206 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009207 int NumMatches = Resolver.getNumMatches();
9208 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009209 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009210 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9211 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9212 else
9213 Resolver.ComplainNoMatchesFound();
9214 }
9215 else if (NumMatches > 1 && Complain)
9216 Resolver.ComplainMultipleMatchesFound();
9217 else if (NumMatches == 1) {
9218 Fn = Resolver.getMatchingFunctionDecl();
9219 assert(Fn);
9220 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009221 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009222 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009223 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009224 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009225
9226 if (pHadMultipleCandidates)
9227 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009228 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009229}
9230
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009231/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009232/// resolve that overloaded function expression down to a single function.
9233///
9234/// This routine can only resolve template-ids that refer to a single function
9235/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009236/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009237/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009238FunctionDecl *
9239Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9240 bool Complain,
9241 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009242 // C++ [over.over]p1:
9243 // [...] [Note: any redundant set of parentheses surrounding the
9244 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009245 // C++ [over.over]p1:
9246 // [...] The overloaded function name can be preceded by the &
9247 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009248
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009249 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009250 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009251 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009252
9253 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009254 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009255
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009256 // Look through all of the overloaded functions, searching for one
9257 // whose type matches exactly.
9258 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009259 for (UnresolvedSetIterator I = ovl->decls_begin(),
9260 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009261 // C++0x [temp.arg.explicit]p3:
9262 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009263 // where deduction is not done, if a template argument list is
9264 // specified and it, along with any default template arguments,
9265 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009266 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009267 FunctionTemplateDecl *FunctionTemplate
9268 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009269
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009270 // C++ [over.over]p2:
9271 // If the name is a function template, template argument deduction is
9272 // done (14.8.2.2), and if the argument deduction succeeds, the
9273 // resulting template argument list is used to generate a single
9274 // function template specialization, which is added to the set of
9275 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009276 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009277 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009278 if (TemplateDeductionResult Result
9279 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9280 Specialization, Info)) {
9281 // FIXME: make a note of the failed deduction for diagnostics.
9282 (void)Result;
9283 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009284 }
9285
John McCall0009fcc2011-04-26 20:42:42 +00009286 assert(Specialization && "no specialization and no error?");
9287
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009288 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009289 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009290 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009291 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9292 << ovl->getName();
9293 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009294 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009295 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009296 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009297
John McCall0009fcc2011-04-26 20:42:42 +00009298 Matched = Specialization;
9299 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009301
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009302 return Matched;
9303}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009304
Douglas Gregor1beec452011-03-12 01:48:56 +00009305
9306
9307
John McCall50a2c2c2011-10-11 23:14:30 +00009308// Resolve and fix an overloaded expression that can be resolved
9309// because it identifies a single function template specialization.
9310//
Douglas Gregor1beec452011-03-12 01:48:56 +00009311// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009312//
9313// Return true if it was logically possible to so resolve the
9314// expression, regardless of whether or not it succeeded. Always
9315// returns true if 'complain' is set.
9316bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9317 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9318 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009319 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009320 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009321 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009322
John McCall50a2c2c2011-10-11 23:14:30 +00009323 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009324
John McCall0009fcc2011-04-26 20:42:42 +00009325 DeclAccessPair found;
9326 ExprResult SingleFunctionExpression;
9327 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9328 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009329 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009330 SrcExpr = ExprError();
9331 return true;
9332 }
John McCall0009fcc2011-04-26 20:42:42 +00009333
9334 // It is only correct to resolve to an instance method if we're
9335 // resolving a form that's permitted to be a pointer to member.
9336 // Otherwise we'll end up making a bound member expression, which
9337 // is illegal in all the contexts we resolve like this.
9338 if (!ovl.HasFormOfMemberPointer &&
9339 isa<CXXMethodDecl>(fn) &&
9340 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009341 if (!complain) return false;
9342
9343 Diag(ovl.Expression->getExprLoc(),
9344 diag::err_bound_member_function)
9345 << 0 << ovl.Expression->getSourceRange();
9346
9347 // TODO: I believe we only end up here if there's a mix of
9348 // static and non-static candidates (otherwise the expression
9349 // would have 'bound member' type, not 'overload' type).
9350 // Ideally we would note which candidate was chosen and why
9351 // the static candidates were rejected.
9352 SrcExpr = ExprError();
9353 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009354 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009355
John McCall0009fcc2011-04-26 20:42:42 +00009356 // Fix the expresion to refer to 'fn'.
9357 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009358 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009359
9360 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009361 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009362 SingleFunctionExpression =
9363 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009364 if (SingleFunctionExpression.isInvalid()) {
9365 SrcExpr = ExprError();
9366 return true;
9367 }
9368 }
John McCall0009fcc2011-04-26 20:42:42 +00009369 }
9370
9371 if (!SingleFunctionExpression.isUsable()) {
9372 if (complain) {
9373 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9374 << ovl.Expression->getName()
9375 << DestTypeForComplaining
9376 << OpRangeForComplaining
9377 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009378 NoteAllOverloadCandidates(SrcExpr.get());
9379
9380 SrcExpr = ExprError();
9381 return true;
9382 }
9383
9384 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009385 }
9386
John McCall50a2c2c2011-10-11 23:14:30 +00009387 SrcExpr = SingleFunctionExpression;
9388 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009389}
9390
Douglas Gregorcabea402009-09-22 15:41:20 +00009391/// \brief Add a single candidate to the overload set.
9392static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009393 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009394 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009395 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009396 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009397 bool PartialOverloading,
9398 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009399 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009400 if (isa<UsingShadowDecl>(Callee))
9401 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9402
Douglas Gregorcabea402009-09-22 15:41:20 +00009403 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009404 if (ExplicitTemplateArgs) {
9405 assert(!KnownValid && "Explicit template arguments?");
9406 return;
9407 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009408 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9409 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009410 return;
John McCalld14a8642009-11-21 08:51:07 +00009411 }
9412
9413 if (FunctionTemplateDecl *FuncTemplate
9414 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009415 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009416 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009417 return;
9418 }
9419
Richard Smith95ce4f62011-06-26 22:19:54 +00009420 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009421}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009422
Douglas Gregorcabea402009-09-22 15:41:20 +00009423/// \brief Add the overload candidates named by callee and/or found by argument
9424/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009425void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009426 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009427 OverloadCandidateSet &CandidateSet,
9428 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009429
9430#ifndef NDEBUG
9431 // Verify that ArgumentDependentLookup is consistent with the rules
9432 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009433 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009434 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9435 // and let Y be the lookup set produced by argument dependent
9436 // lookup (defined as follows). If X contains
9437 //
9438 // -- a declaration of a class member, or
9439 //
9440 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009441 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009442 //
9443 // -- a declaration that is neither a function or a function
9444 // template
9445 //
9446 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009447
John McCall57500772009-12-16 12:17:52 +00009448 if (ULE->requiresADL()) {
9449 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9450 E = ULE->decls_end(); I != E; ++I) {
9451 assert(!(*I)->getDeclContext()->isRecord());
9452 assert(isa<UsingShadowDecl>(*I) ||
9453 !(*I)->getDeclContext()->isFunctionOrMethod());
9454 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009455 }
9456 }
9457#endif
9458
John McCall57500772009-12-16 12:17:52 +00009459 // It would be nice to avoid this copy.
9460 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009461 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009462 if (ULE->hasExplicitTemplateArgs()) {
9463 ULE->copyTemplateArgumentsInto(TABuffer);
9464 ExplicitTemplateArgs = &TABuffer;
9465 }
9466
9467 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9468 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009469 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9470 CandidateSet, PartialOverloading,
9471 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009472
John McCall57500772009-12-16 12:17:52 +00009473 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009474 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009475 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009476 Args, ExplicitTemplateArgs,
9477 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009478 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009479}
John McCalld681c392009-12-16 08:11:27 +00009480
Richard Smith998a5912011-06-05 22:42:48 +00009481/// Attempt to recover from an ill-formed use of a non-dependent name in a
9482/// template, where the non-dependent name was declared after the template
9483/// was defined. This is common in code written for a compilers which do not
9484/// correctly implement two-stage name lookup.
9485///
9486/// Returns true if a viable candidate was found and a diagnostic was issued.
9487static bool
9488DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9489 const CXXScopeSpec &SS, LookupResult &R,
9490 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009491 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009492 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9493 return false;
9494
9495 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009496 if (DC->isTransparentContext())
9497 continue;
9498
Richard Smith998a5912011-06-05 22:42:48 +00009499 SemaRef.LookupQualifiedName(R, DC);
9500
9501 if (!R.empty()) {
9502 R.suppressDiagnostics();
9503
9504 if (isa<CXXRecordDecl>(DC)) {
9505 // Don't diagnose names we find in classes; we get much better
9506 // diagnostics for these from DiagnoseEmptyLookup.
9507 R.clear();
9508 return false;
9509 }
9510
9511 OverloadCandidateSet Candidates(FnLoc);
9512 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9513 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009514 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009515 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009516
9517 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009518 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009519 // No viable functions. Don't bother the user with notes for functions
9520 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009521 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009522 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009523 }
Richard Smith998a5912011-06-05 22:42:48 +00009524
9525 // Find the namespaces where ADL would have looked, and suggest
9526 // declaring the function there instead.
9527 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9528 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009529 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009530 AssociatedNamespaces,
9531 AssociatedClasses);
9532 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009533 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009534 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009535 for (Sema::AssociatedNamespaceSet::iterator
9536 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009537 end = AssociatedNamespaces.end(); it != end; ++it) {
9538 if (!Std->Encloses(*it))
9539 SuggestedNamespaces.insert(*it);
9540 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009541 } else {
9542 // Lacking the 'std::' namespace, use all of the associated namespaces.
9543 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009544 }
9545
9546 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9547 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009548 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009549 SemaRef.Diag(Best->Function->getLocation(),
9550 diag::note_not_found_by_two_phase_lookup)
9551 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009552 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009553 SemaRef.Diag(Best->Function->getLocation(),
9554 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009555 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009556 } else {
9557 // FIXME: It would be useful to list the associated namespaces here,
9558 // but the diagnostics infrastructure doesn't provide a way to produce
9559 // a localized representation of a list of items.
9560 SemaRef.Diag(Best->Function->getLocation(),
9561 diag::note_not_found_by_two_phase_lookup)
9562 << R.getLookupName() << 2;
9563 }
9564
9565 // Try to recover by calling this function.
9566 return true;
9567 }
9568
9569 R.clear();
9570 }
9571
9572 return false;
9573}
9574
9575/// Attempt to recover from ill-formed use of a non-dependent operator in a
9576/// template, where the non-dependent operator was declared after the template
9577/// was defined.
9578///
9579/// Returns true if a viable candidate was found and a diagnostic was issued.
9580static bool
9581DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9582 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009583 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009584 DeclarationName OpName =
9585 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9586 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9587 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009588 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009589}
9590
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009591namespace {
9592// Callback to limit the allowed keywords and to only accept typo corrections
9593// that are keywords or whose decls refer to functions (or template functions)
9594// that accept the given number of arguments.
9595class RecoveryCallCCC : public CorrectionCandidateCallback {
9596 public:
9597 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9598 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009599 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009600 WantRemainingKeywords = false;
9601 }
9602
9603 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9604 if (!candidate.getCorrectionDecl())
9605 return candidate.isKeyword();
9606
9607 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9608 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9609 FunctionDecl *FD = 0;
9610 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9611 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9612 FD = FTD->getTemplatedDecl();
9613 if (!HasExplicitTemplateArgs && !FD) {
9614 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9615 // If the Decl is neither a function nor a template function,
9616 // determine if it is a pointer or reference to a function. If so,
9617 // check against the number of arguments expected for the pointee.
9618 QualType ValType = cast<ValueDecl>(ND)->getType();
9619 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9620 ValType = ValType->getPointeeType();
9621 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9622 if (FPT->getNumArgs() == NumArgs)
9623 return true;
9624 }
9625 }
9626 if (FD && FD->getNumParams() >= NumArgs &&
9627 FD->getMinRequiredArguments() <= NumArgs)
9628 return true;
9629 }
9630 return false;
9631 }
9632
9633 private:
9634 unsigned NumArgs;
9635 bool HasExplicitTemplateArgs;
9636};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009637
9638// Callback that effectively disabled typo correction
9639class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9640 public:
9641 NoTypoCorrectionCCC() {
9642 WantTypeSpecifiers = false;
9643 WantExpressionKeywords = false;
9644 WantCXXNamedCasts = false;
9645 WantRemainingKeywords = false;
9646 }
9647
9648 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9649 return false;
9650 }
9651};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009652}
9653
John McCalld681c392009-12-16 08:11:27 +00009654/// Attempts to recover from a call where no functions were found.
9655///
9656/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009657static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009658BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009659 UnresolvedLookupExpr *ULE,
9660 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009661 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009662 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009663 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009664
9665 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009666 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009667 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009668
John McCall57500772009-12-16 12:17:52 +00009669 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009670 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009671 if (ULE->hasExplicitTemplateArgs()) {
9672 ULE->copyTemplateArgumentsInto(TABuffer);
9673 ExplicitTemplateArgs = &TABuffer;
9674 }
9675
John McCalld681c392009-12-16 08:11:27 +00009676 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9677 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009678 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009679 NoTypoCorrectionCCC RejectAll;
9680 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9681 (CorrectionCandidateCallback*)&Validator :
9682 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009683 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009684 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009685 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009686 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009687 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009688 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009689
John McCall57500772009-12-16 12:17:52 +00009690 assert(!R.empty() && "lookup results empty despite recovery");
9691
9692 // Build an implicit member call if appropriate. Just drop the
9693 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009694 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009695 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009696 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9697 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009698 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009699 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009700 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009701 else
9702 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9703
9704 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009705 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009706
9707 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009708 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009709 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009710 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009711 MultiExprArg(Args.data(), Args.size()),
9712 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009713}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009714
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009715/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009716/// (which eventually refers to the declaration Func) and the call
9717/// arguments Args/NumArgs, attempt to resolve the function call down
9718/// to a specific function. If overload resolution succeeds, returns
9719/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009720/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009721/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009722ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009723Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009724 SourceLocation LParenLoc,
9725 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009726 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009727 Expr *ExecConfig,
9728 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009729#ifndef NDEBUG
9730 if (ULE->requiresADL()) {
9731 // To do ADL, we must have found an unqualified name.
9732 assert(!ULE->getQualifier() && "qualified name with ADL");
9733
9734 // We don't perform ADL for implicit declarations of builtins.
9735 // Verify that this was correctly set up.
9736 FunctionDecl *F;
9737 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9738 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9739 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009740 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009741
John McCall57500772009-12-16 12:17:52 +00009742 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009743 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009744 } else
9745 assert(!ULE->isStdAssociatedNamespace() &&
9746 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009747#endif
9748
John McCall4124c492011-10-17 18:40:02 +00009749 UnbridgedCastsSet UnbridgedCasts;
9750 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9751 return ExprError();
9752
John McCallbc077cf2010-02-08 23:07:23 +00009753 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009754
John McCall57500772009-12-16 12:17:52 +00009755 // Add the functions denoted by the callee to the set of candidate
9756 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009757 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9758 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009759
9760 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009761 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9762 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009763 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009764 // In Microsoft mode, if we are inside a template class member function then
9765 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009766 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009767 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009768 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009769 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009770 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9771 Context.DependentTy, VK_RValue,
9772 RParenLoc);
9773 CE->setTypeDependent(true);
9774 return Owned(CE);
9775 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009776 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9777 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009778 RParenLoc, /*EmptyLookup=*/true,
9779 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009780 }
John McCalld681c392009-12-16 08:11:27 +00009781
John McCall4124c492011-10-17 18:40:02 +00009782 UnbridgedCasts.restore();
9783
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009784 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009785 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009786 case OR_Success: {
9787 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009788 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009789 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009790 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009791 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009792 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9793 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009794 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009795
Richard Smith998a5912011-06-05 22:42:48 +00009796 case OR_No_Viable_Function: {
9797 // Try to recover by looking for viable functions which the user might
9798 // have meant to call.
9799 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009800 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9801 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009802 /*EmptyLookup=*/false,
9803 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009804 if (!Recovery.isInvalid())
9805 return Recovery;
9806
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009807 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009808 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009809 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009810 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9811 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009812 break;
Richard Smith998a5912011-06-05 22:42:48 +00009813 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009814
9815 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009816 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009817 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009818 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9819 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009820 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009821
9822 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009823 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009824 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009825 << Best->Function->isDeleted()
9826 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009827 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009828 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009829 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9830 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009831
9832 // We emitted an error for the unvailable/deleted function call but keep
9833 // the call in the AST.
9834 FunctionDecl *FDecl = Best->Function;
9835 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9836 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9837 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009838 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009839 }
9840
Douglas Gregorb412e172010-07-25 18:17:45 +00009841 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009842 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009843}
9844
John McCall4c4c1df2010-01-26 03:27:55 +00009845static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009846 return Functions.size() > 1 ||
9847 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9848}
9849
Douglas Gregor084d8552009-03-13 23:49:33 +00009850/// \brief Create a unary operation that may resolve to an overloaded
9851/// operator.
9852///
9853/// \param OpLoc The location of the operator itself (e.g., '*').
9854///
9855/// \param OpcIn The UnaryOperator::Opcode that describes this
9856/// operator.
9857///
9858/// \param Functions The set of non-member functions that will be
9859/// considered by overload resolution. The caller needs to build this
9860/// set based on the context using, e.g.,
9861/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9862/// set should not contain any member functions; those will be added
9863/// by CreateOverloadedUnaryOp().
9864///
9865/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009866ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009867Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9868 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009869 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009870 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009871
9872 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9873 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9874 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009875 // TODO: provide better source location info.
9876 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009877
John McCall4124c492011-10-17 18:40:02 +00009878 if (checkPlaceholderForOverload(*this, Input))
9879 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009880
Douglas Gregor084d8552009-03-13 23:49:33 +00009881 Expr *Args[2] = { Input, 0 };
9882 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009883
Douglas Gregor084d8552009-03-13 23:49:33 +00009884 // For post-increment and post-decrement, add the implicit '0' as
9885 // the second argument, so that we know this is a post-increment or
9886 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009887 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009888 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009889 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9890 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009891 NumArgs = 2;
9892 }
9893
9894 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009895 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009896 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009897 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009898 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009899 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009900 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009901
John McCall58cc69d2010-01-27 01:50:18 +00009902 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009903 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009904 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009905 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009906 /*ADL*/ true, IsOverloaded(Fns),
9907 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009908 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009909 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009910 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009911 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009912 OpLoc));
9913 }
9914
9915 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009916 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009917
9918 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009919 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9920 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009921
9922 // Add operator candidates that are member functions.
9923 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9924
John McCall4c4c1df2010-01-26 03:27:55 +00009925 // Add candidates from ADL.
9926 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009927 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009928 /*ExplicitTemplateArgs*/ 0,
9929 CandidateSet);
9930
Douglas Gregor084d8552009-03-13 23:49:33 +00009931 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009932 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009933
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009934 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9935
Douglas Gregor084d8552009-03-13 23:49:33 +00009936 // Perform overload resolution.
9937 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009938 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009939 case OR_Success: {
9940 // We found a built-in operator or an overloaded operator.
9941 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009942
Douglas Gregor084d8552009-03-13 23:49:33 +00009943 if (FnDecl) {
9944 // We matched an overloaded operator. Build a call to that
9945 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009946
Eli Friedmanfa0df832012-02-02 03:46:19 +00009947 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009948
Douglas Gregor084d8552009-03-13 23:49:33 +00009949 // Convert the arguments.
9950 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009951 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009952
John Wiegley01296292011-04-08 18:41:53 +00009953 ExprResult InputRes =
9954 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9955 Best->FoundDecl, Method);
9956 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009957 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009958 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009959 } else {
9960 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009961 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009962 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009963 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009964 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009965 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009966 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009967 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009968 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009969 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009970 }
9971
John McCall4fa0d5f2010-05-06 18:15:07 +00009972 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9973
John McCall7decc9e2010-11-18 06:31:45 +00009974 // Determine the result type.
9975 QualType ResultTy = FnDecl->getResultType();
9976 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9977 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009978
Douglas Gregor084d8552009-03-13 23:49:33 +00009979 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009980 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009981 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009982 if (FnExpr.isInvalid())
9983 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009984
Eli Friedman030eee42009-11-18 03:58:17 +00009985 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009986 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009987 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009988 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009990 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009991 FnDecl))
9992 return ExprError();
9993
John McCallb268a282010-08-23 23:25:46 +00009994 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009995 } else {
9996 // We matched a built-in operator. Convert the arguments, then
9997 // break out so that we will build the appropriate built-in
9998 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009999 ExprResult InputRes =
10000 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10001 Best->Conversions[0], AA_Passing);
10002 if (InputRes.isInvalid())
10003 return ExprError();
10004 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010005 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010006 }
John Wiegley01296292011-04-08 18:41:53 +000010007 }
10008
10009 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010010 // This is an erroneous use of an operator which can be overloaded by
10011 // a non-member function. Check for non-member operators which were
10012 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010013 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10014 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010015 // FIXME: Recover by calling the found function.
10016 return ExprError();
10017
John Wiegley01296292011-04-08 18:41:53 +000010018 // No viable function; fall through to handling this as a
10019 // built-in operator, which will produce an error message for us.
10020 break;
10021
10022 case OR_Ambiguous:
10023 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10024 << UnaryOperator::getOpcodeStr(Opc)
10025 << Input->getType()
10026 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010027 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10028 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010029 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10030 return ExprError();
10031
10032 case OR_Deleted:
10033 Diag(OpLoc, diag::err_ovl_deleted_oper)
10034 << Best->Function->isDeleted()
10035 << UnaryOperator::getOpcodeStr(Opc)
10036 << getDeletedOrUnavailableSuffix(Best->Function)
10037 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010038 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10039 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010040 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010041 return ExprError();
10042 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010043
10044 // Either we found no viable overloaded operator or we matched a
10045 // built-in operator. In either case, fall through to trying to
10046 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010047 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010048}
10049
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010050/// \brief Create a binary operation that may resolve to an overloaded
10051/// operator.
10052///
10053/// \param OpLoc The location of the operator itself (e.g., '+').
10054///
10055/// \param OpcIn The BinaryOperator::Opcode that describes this
10056/// operator.
10057///
10058/// \param Functions The set of non-member functions that will be
10059/// considered by overload resolution. The caller needs to build this
10060/// set based on the context using, e.g.,
10061/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10062/// set should not contain any member functions; those will be added
10063/// by CreateOverloadedBinOp().
10064///
10065/// \param LHS Left-hand argument.
10066/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010067ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010068Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010069 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010070 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010071 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010072 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010073 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010074
10075 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10076 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10077 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10078
10079 // If either side is type-dependent, create an appropriate dependent
10080 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010081 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010082 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010083 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010084 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010085 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010086 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010087 Context.DependentTy,
10088 VK_RValue, OK_Ordinary,
10089 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010090
Douglas Gregor5287f092009-11-05 00:51:44 +000010091 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10092 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010093 VK_LValue,
10094 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010095 Context.DependentTy,
10096 Context.DependentTy,
10097 OpLoc));
10098 }
John McCall4c4c1df2010-01-26 03:27:55 +000010099
10100 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010101 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010102 // TODO: provide better source location info in DNLoc component.
10103 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010104 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010105 = UnresolvedLookupExpr::Create(Context, NamingClass,
10106 NestedNameSpecifierLoc(), OpNameInfo,
10107 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010108 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010109 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +000010110 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010111 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010112 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010113 OpLoc));
10114 }
10115
John McCall4124c492011-10-17 18:40:02 +000010116 // Always do placeholder-like conversions on the RHS.
10117 if (checkPlaceholderForOverload(*this, Args[1]))
10118 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010119
John McCall526ab472011-10-25 17:37:35 +000010120 // Do placeholder-like conversion on the LHS; note that we should
10121 // not get here with a PseudoObject LHS.
10122 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010123 if (checkPlaceholderForOverload(*this, Args[0]))
10124 return ExprError();
10125
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010126 // If this is the assignment operator, we only perform overload resolution
10127 // if the left-hand side is a class or enumeration type. This is actually
10128 // a hack. The standard requires that we do overload resolution between the
10129 // various built-in candidates, but as DR507 points out, this can lead to
10130 // problems. So we do it this way, which pretty much follows what GCC does.
10131 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010132 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010133 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010134
John McCalle26a8722010-12-04 08:14:53 +000010135 // If this is the .* operator, which is not overloadable, just
10136 // create a built-in binary operator.
10137 if (Opc == BO_PtrMemD)
10138 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10139
Douglas Gregor084d8552009-03-13 23:49:33 +000010140 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010141 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010142
10143 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010144 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010145
10146 // Add operator candidates that are member functions.
10147 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10148
John McCall4c4c1df2010-01-26 03:27:55 +000010149 // Add candidates from ADL.
10150 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010151 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010152 /*ExplicitTemplateArgs*/ 0,
10153 CandidateSet);
10154
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010155 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010156 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010157
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010158 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10159
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010160 // Perform overload resolution.
10161 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010162 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010163 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010164 // We found a built-in operator or an overloaded operator.
10165 FunctionDecl *FnDecl = Best->Function;
10166
10167 if (FnDecl) {
10168 // We matched an overloaded operator. Build a call to that
10169 // operator.
10170
Eli Friedmanfa0df832012-02-02 03:46:19 +000010171 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010172
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010173 // Convert the arguments.
10174 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010175 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010176 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010177
Chandler Carruth8e543b32010-12-12 08:17:55 +000010178 ExprResult Arg1 =
10179 PerformCopyInitialization(
10180 InitializedEntity::InitializeParameter(Context,
10181 FnDecl->getParamDecl(0)),
10182 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010183 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010184 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010185
John Wiegley01296292011-04-08 18:41:53 +000010186 ExprResult Arg0 =
10187 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10188 Best->FoundDecl, Method);
10189 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010190 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010191 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010192 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010193 } else {
10194 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010195 ExprResult Arg0 = PerformCopyInitialization(
10196 InitializedEntity::InitializeParameter(Context,
10197 FnDecl->getParamDecl(0)),
10198 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010199 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010200 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010201
Chandler Carruth8e543b32010-12-12 08:17:55 +000010202 ExprResult Arg1 =
10203 PerformCopyInitialization(
10204 InitializedEntity::InitializeParameter(Context,
10205 FnDecl->getParamDecl(1)),
10206 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010207 if (Arg1.isInvalid())
10208 return ExprError();
10209 Args[0] = LHS = Arg0.takeAs<Expr>();
10210 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010211 }
10212
John McCall4fa0d5f2010-05-06 18:15:07 +000010213 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10214
John McCall7decc9e2010-11-18 06:31:45 +000010215 // Determine the result type.
10216 QualType ResultTy = FnDecl->getResultType();
10217 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10218 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010219
10220 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010221 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10222 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010223 if (FnExpr.isInvalid())
10224 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010225
John McCallb268a282010-08-23 23:25:46 +000010226 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010227 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010228 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010229
10230 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010231 FnDecl))
10232 return ExprError();
10233
John McCallb268a282010-08-23 23:25:46 +000010234 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010235 } else {
10236 // We matched a built-in operator. Convert the arguments, then
10237 // break out so that we will build the appropriate built-in
10238 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010239 ExprResult ArgsRes0 =
10240 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10241 Best->Conversions[0], AA_Passing);
10242 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010243 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010244 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010245
John Wiegley01296292011-04-08 18:41:53 +000010246 ExprResult ArgsRes1 =
10247 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10248 Best->Conversions[1], AA_Passing);
10249 if (ArgsRes1.isInvalid())
10250 return ExprError();
10251 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010252 break;
10253 }
10254 }
10255
Douglas Gregor66950a32009-09-30 21:46:01 +000010256 case OR_No_Viable_Function: {
10257 // C++ [over.match.oper]p9:
10258 // If the operator is the operator , [...] and there are no
10259 // viable functions, then the operator is assumed to be the
10260 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010261 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010262 break;
10263
Chandler Carruth8e543b32010-12-12 08:17:55 +000010264 // For class as left operand for assignment or compound assigment
10265 // operator do not fall through to handling in built-in, but report that
10266 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010267 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010268 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010269 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010270 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10271 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010272 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010273 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010274 // This is an erroneous use of an operator which can be overloaded by
10275 // a non-member function. Check for non-member operators which were
10276 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010277 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010278 // FIXME: Recover by calling the found function.
10279 return ExprError();
10280
Douglas Gregor66950a32009-09-30 21:46:01 +000010281 // No viable function; try to create a built-in operation, which will
10282 // produce an error. Then, show the non-viable candidates.
10283 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010285 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010286 "C++ binary operator overloading is missing candidates!");
10287 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010288 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010289 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010290 return move(Result);
10291 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010292
10293 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010294 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010295 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010296 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010297 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010298 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010299 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010300 return ExprError();
10301
10302 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010303 if (isImplicitlyDeleted(Best->Function)) {
10304 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10305 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10306 << getSpecialMember(Method)
10307 << BinaryOperator::getOpcodeStr(Opc)
10308 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010309
10310 if (getSpecialMember(Method) != CXXInvalid) {
10311 // The user probably meant to call this special member. Just
10312 // explain why it's deleted.
10313 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010314 return ExprError();
10315 }
10316 } else {
10317 Diag(OpLoc, diag::err_ovl_deleted_oper)
10318 << Best->Function->isDeleted()
10319 << BinaryOperator::getOpcodeStr(Opc)
10320 << getDeletedOrUnavailableSuffix(Best->Function)
10321 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10322 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010323 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010324 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010325 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010326 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010327
Douglas Gregor66950a32009-09-30 21:46:01 +000010328 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010329 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010330}
10331
John McCalldadc5752010-08-24 06:29:42 +000010332ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010333Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10334 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010335 Expr *Base, Expr *Idx) {
10336 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010337 DeclarationName OpName =
10338 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10339
10340 // If either side is type-dependent, create an appropriate dependent
10341 // expression.
10342 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10343
John McCall58cc69d2010-01-27 01:50:18 +000010344 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010345 // CHECKME: no 'operator' keyword?
10346 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10347 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010348 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010349 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010350 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010351 /*ADL*/ true, /*Overloaded*/ false,
10352 UnresolvedSetIterator(),
10353 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010354 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010355
Sebastian Redladba46e2009-10-29 20:17:01 +000010356 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10357 Args, 2,
10358 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010359 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010360 RLoc));
10361 }
10362
John McCall4124c492011-10-17 18:40:02 +000010363 // Handle placeholders on both operands.
10364 if (checkPlaceholderForOverload(*this, Args[0]))
10365 return ExprError();
10366 if (checkPlaceholderForOverload(*this, Args[1]))
10367 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010368
Sebastian Redladba46e2009-10-29 20:17:01 +000010369 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010370 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010371
10372 // Subscript can only be overloaded as a member function.
10373
10374 // Add operator candidates that are member functions.
10375 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10376
10377 // Add builtin operator candidates.
10378 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10379
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010380 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10381
Sebastian Redladba46e2009-10-29 20:17:01 +000010382 // Perform overload resolution.
10383 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010384 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010385 case OR_Success: {
10386 // We found a built-in operator or an overloaded operator.
10387 FunctionDecl *FnDecl = Best->Function;
10388
10389 if (FnDecl) {
10390 // We matched an overloaded operator. Build a call to that
10391 // operator.
10392
Eli Friedmanfa0df832012-02-02 03:46:19 +000010393 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010394
John McCalla0296f72010-03-19 07:35:19 +000010395 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010396 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010397
Sebastian Redladba46e2009-10-29 20:17:01 +000010398 // Convert the arguments.
10399 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010400 ExprResult Arg0 =
10401 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10402 Best->FoundDecl, Method);
10403 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010404 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010405 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010406
Anders Carlssona68e51e2010-01-29 18:37:50 +000010407 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010408 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010409 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010410 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010411 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010412 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010413 Owned(Args[1]));
10414 if (InputInit.isInvalid())
10415 return ExprError();
10416
10417 Args[1] = InputInit.takeAs<Expr>();
10418
Sebastian Redladba46e2009-10-29 20:17:01 +000010419 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010420 QualType ResultTy = FnDecl->getResultType();
10421 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10422 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010423
10424 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010425 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10426 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010427 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10428 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010429 OpLocInfo.getLoc(),
10430 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010431 if (FnExpr.isInvalid())
10432 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010433
John McCallb268a282010-08-23 23:25:46 +000010434 CXXOperatorCallExpr *TheCall =
10435 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010436 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010437 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010438
John McCallb268a282010-08-23 23:25:46 +000010439 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010440 FnDecl))
10441 return ExprError();
10442
John McCallb268a282010-08-23 23:25:46 +000010443 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010444 } else {
10445 // We matched a built-in operator. Convert the arguments, then
10446 // break out so that we will build the appropriate built-in
10447 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010448 ExprResult ArgsRes0 =
10449 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10450 Best->Conversions[0], AA_Passing);
10451 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010452 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010453 Args[0] = ArgsRes0.take();
10454
10455 ExprResult ArgsRes1 =
10456 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10457 Best->Conversions[1], AA_Passing);
10458 if (ArgsRes1.isInvalid())
10459 return ExprError();
10460 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010461
10462 break;
10463 }
10464 }
10465
10466 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010467 if (CandidateSet.empty())
10468 Diag(LLoc, diag::err_ovl_no_oper)
10469 << Args[0]->getType() << /*subscript*/ 0
10470 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10471 else
10472 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10473 << Args[0]->getType()
10474 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010475 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010476 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010477 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010478 }
10479
10480 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010481 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010482 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010483 << Args[0]->getType() << Args[1]->getType()
10484 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010485 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010486 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010487 return ExprError();
10488
10489 case OR_Deleted:
10490 Diag(LLoc, diag::err_ovl_deleted_oper)
10491 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010492 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010493 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010494 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010495 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010496 return ExprError();
10497 }
10498
10499 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010500 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010501}
10502
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010503/// BuildCallToMemberFunction - Build a call to a member
10504/// function. MemExpr is the expression that refers to the member
10505/// function (and includes the object parameter), Args/NumArgs are the
10506/// arguments to the function call (not including the object
10507/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010508/// expression refers to a non-static member function or an overloaded
10509/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010510ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010511Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10512 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010513 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010514 assert(MemExprE->getType() == Context.BoundMemberTy ||
10515 MemExprE->getType() == Context.OverloadTy);
10516
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010517 // Dig out the member expression. This holds both the object
10518 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010519 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010520
John McCall0009fcc2011-04-26 20:42:42 +000010521 // Determine whether this is a call to a pointer-to-member function.
10522 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10523 assert(op->getType() == Context.BoundMemberTy);
10524 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10525
10526 QualType fnType =
10527 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10528
10529 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10530 QualType resultType = proto->getCallResultType(Context);
10531 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10532
10533 // Check that the object type isn't more qualified than the
10534 // member function we're calling.
10535 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10536
10537 QualType objectType = op->getLHS()->getType();
10538 if (op->getOpcode() == BO_PtrMemI)
10539 objectType = objectType->castAs<PointerType>()->getPointeeType();
10540 Qualifiers objectQuals = objectType.getQualifiers();
10541
10542 Qualifiers difference = objectQuals - funcQuals;
10543 difference.removeObjCGCAttr();
10544 difference.removeAddressSpace();
10545 if (difference) {
10546 std::string qualsString = difference.getAsString();
10547 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10548 << fnType.getUnqualifiedType()
10549 << qualsString
10550 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10551 }
10552
10553 CXXMemberCallExpr *call
10554 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10555 resultType, valueKind, RParenLoc);
10556
10557 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010558 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010559 call, 0))
10560 return ExprError();
10561
10562 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10563 return ExprError();
10564
10565 return MaybeBindToTemporary(call);
10566 }
10567
John McCall4124c492011-10-17 18:40:02 +000010568 UnbridgedCastsSet UnbridgedCasts;
10569 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10570 return ExprError();
10571
John McCall10eae182009-11-30 22:42:35 +000010572 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010573 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010574 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010575 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010576 if (isa<MemberExpr>(NakedMemExpr)) {
10577 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010578 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010579 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010580 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010581 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010582 } else {
10583 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010584 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010585
John McCall6e9f8f62009-12-03 04:06:58 +000010586 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010587 Expr::Classification ObjectClassification
10588 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10589 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010590
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010591 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010592 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010593
John McCall2d74de92009-12-01 22:10:20 +000010594 // FIXME: avoid copy.
10595 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10596 if (UnresExpr->hasExplicitTemplateArgs()) {
10597 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10598 TemplateArgs = &TemplateArgsBuffer;
10599 }
10600
John McCall10eae182009-11-30 22:42:35 +000010601 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10602 E = UnresExpr->decls_end(); I != E; ++I) {
10603
John McCall6e9f8f62009-12-03 04:06:58 +000010604 NamedDecl *Func = *I;
10605 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10606 if (isa<UsingShadowDecl>(Func))
10607 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10608
Douglas Gregor02824322011-01-26 19:30:28 +000010609
Francois Pichet64225792011-01-18 05:04:39 +000010610 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010611 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010612 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10613 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010614 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010615 // If explicit template arguments were provided, we can't call a
10616 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010617 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010618 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010619
John McCalla0296f72010-03-19 07:35:19 +000010620 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010621 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010622 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010623 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010624 } else {
John McCall10eae182009-11-30 22:42:35 +000010625 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010626 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010627 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010628 llvm::makeArrayRef(Args, NumArgs),
10629 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010630 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010631 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010632 }
Mike Stump11289f42009-09-09 15:08:12 +000010633
John McCall10eae182009-11-30 22:42:35 +000010634 DeclarationName DeclName = UnresExpr->getMemberName();
10635
John McCall4124c492011-10-17 18:40:02 +000010636 UnbridgedCasts.restore();
10637
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010638 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010639 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010640 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010641 case OR_Success:
10642 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010643 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010644 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010645 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010646 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010647 break;
10648
10649 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010650 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010651 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010652 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010653 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10654 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010655 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010656 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010657
10658 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010659 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010660 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10662 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010663 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010664 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010665
10666 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010667 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010668 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010669 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010670 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010671 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010672 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10673 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010674 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010675 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010676 }
10677
John McCall16df1e52010-03-30 21:47:33 +000010678 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010679
John McCall2d74de92009-12-01 22:10:20 +000010680 // If overload resolution picked a static member, build a
10681 // non-member call based on that function.
10682 if (Method->isStatic()) {
10683 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10684 Args, NumArgs, RParenLoc);
10685 }
10686
John McCall10eae182009-11-30 22:42:35 +000010687 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010688 }
10689
John McCall7decc9e2010-11-18 06:31:45 +000010690 QualType ResultType = Method->getResultType();
10691 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10692 ResultType = ResultType.getNonLValueExprType(Context);
10693
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010694 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010695 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010696 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010697 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010698
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010699 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010700 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010701 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010702 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010703
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010704 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010705 // We only need to do this if there was actually an overload; otherwise
10706 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010707 if (!Method->isStatic()) {
10708 ExprResult ObjectArg =
10709 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10710 FoundDecl, Method);
10711 if (ObjectArg.isInvalid())
10712 return ExprError();
10713 MemExpr->setBase(ObjectArg.take());
10714 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010715
10716 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010717 const FunctionProtoType *Proto =
10718 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010719 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010720 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010721 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010722
Eli Friedmanff4b4072012-02-18 04:48:30 +000010723 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10724
John McCallb268a282010-08-23 23:25:46 +000010725 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010726 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010727
Anders Carlsson47061ee2011-05-06 14:25:31 +000010728 if ((isa<CXXConstructorDecl>(CurContext) ||
10729 isa<CXXDestructorDecl>(CurContext)) &&
10730 TheCall->getMethodDecl()->isPure()) {
10731 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10732
Chandler Carruth59259262011-06-27 08:31:58 +000010733 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010734 Diag(MemExpr->getLocStart(),
10735 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10736 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10737 << MD->getParent()->getDeclName();
10738
10739 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010740 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010741 }
John McCallb268a282010-08-23 23:25:46 +000010742 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010743}
10744
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010745/// BuildCallToObjectOfClassType - Build a call to an object of class
10746/// type (C++ [over.call.object]), which can end up invoking an
10747/// overloaded function call operator (@c operator()) or performing a
10748/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010749ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010750Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010751 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010752 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010753 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010754 if (checkPlaceholderForOverload(*this, Obj))
10755 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010756 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010757
10758 UnbridgedCastsSet UnbridgedCasts;
10759 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10760 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010761
John Wiegley01296292011-04-08 18:41:53 +000010762 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10763 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010764
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010765 // C++ [over.call.object]p1:
10766 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010767 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010768 // candidate functions includes at least the function call
10769 // operators of T. The function call operators of T are obtained by
10770 // ordinary lookup of the name operator() in the context of
10771 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010772 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010773 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010774
John Wiegley01296292011-04-08 18:41:53 +000010775 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010776 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010777 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010778
John McCall27b18f82009-11-17 02:14:36 +000010779 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10780 LookupQualifiedName(R, Record->getDecl());
10781 R.suppressDiagnostics();
10782
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010783 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010784 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010785 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10786 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010787 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010789
Douglas Gregorab7897a2008-11-19 22:57:39 +000010790 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010791 // In addition, for each (non-explicit in C++0x) conversion function
10792 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010793 //
10794 // operator conversion-type-id () cv-qualifier;
10795 //
10796 // where cv-qualifier is the same cv-qualification as, or a
10797 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010798 // denotes the type "pointer to function of (P1,...,Pn) returning
10799 // R", or the type "reference to pointer to function of
10800 // (P1,...,Pn) returning R", or the type "reference to function
10801 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010802 // is also considered as a candidate function. Similarly,
10803 // surrogate call functions are added to the set of candidate
10804 // functions for each conversion function declared in an
10805 // accessible base class provided the function is not hidden
10806 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010807 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010808 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010809 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010810 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010811 NamedDecl *D = *I;
10812 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10813 if (isa<UsingShadowDecl>(D))
10814 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010815
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010816 // Skip over templated conversion functions; they aren't
10817 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010818 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010819 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010820
John McCall6e9f8f62009-12-03 04:06:58 +000010821 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010822 if (!Conv->isExplicit()) {
10823 // Strip the reference type (if any) and then the pointer type (if
10824 // any) to get down to what might be a function type.
10825 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10826 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10827 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010828
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010829 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10830 {
10831 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010832 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10833 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010834 }
10835 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010836 }
Mike Stump11289f42009-09-09 15:08:12 +000010837
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010838 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10839
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010840 // Perform overload resolution.
10841 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010842 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010843 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010844 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010845 // Overload resolution succeeded; we'll build the appropriate call
10846 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010847 break;
10848
10849 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010850 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010851 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010852 << Object.get()->getType() << /*call*/ 1
10853 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010854 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010855 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010856 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010857 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010858 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10859 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010860 break;
10861
10862 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010863 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010864 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010865 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010866 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10867 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010868 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010869
10870 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010871 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010872 diag::err_ovl_deleted_object_call)
10873 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010874 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010875 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010876 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010877 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10878 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010879 break;
Mike Stump11289f42009-09-09 15:08:12 +000010880 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010881
Douglas Gregorb412e172010-07-25 18:17:45 +000010882 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010883 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010884
John McCall4124c492011-10-17 18:40:02 +000010885 UnbridgedCasts.restore();
10886
Douglas Gregorab7897a2008-11-19 22:57:39 +000010887 if (Best->Function == 0) {
10888 // Since there is no function declaration, this is one of the
10889 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010890 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010891 = cast<CXXConversionDecl>(
10892 Best->Conversions[0].UserDefined.ConversionFunction);
10893
John Wiegley01296292011-04-08 18:41:53 +000010894 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010895 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010896
Douglas Gregorab7897a2008-11-19 22:57:39 +000010897 // We selected one of the surrogate functions that converts the
10898 // object parameter to a function pointer. Perform the conversion
10899 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010900
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010901 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010902 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010903 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10904 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010905 if (Call.isInvalid())
10906 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010907 // Record usage of conversion in an implicit cast.
10908 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10909 CK_UserDefinedConversion,
10910 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010911
Douglas Gregor668443e2011-01-20 00:18:04 +000010912 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010913 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010914 }
10915
Eli Friedmanfa0df832012-02-02 03:46:19 +000010916 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010917 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010918 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010919
Douglas Gregorab7897a2008-11-19 22:57:39 +000010920 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10921 // that calls this method, using Object for the implicit object
10922 // parameter and passing along the remaining arguments.
10923 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010924 const FunctionProtoType *Proto =
10925 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010926
10927 unsigned NumArgsInProto = Proto->getNumArgs();
10928 unsigned NumArgsToCheck = NumArgs;
10929
10930 // Build the full argument list for the method call (the
10931 // implicit object parameter is placed at the beginning of the
10932 // list).
10933 Expr **MethodArgs;
10934 if (NumArgs < NumArgsInProto) {
10935 NumArgsToCheck = NumArgsInProto;
10936 MethodArgs = new Expr*[NumArgsInProto + 1];
10937 } else {
10938 MethodArgs = new Expr*[NumArgs + 1];
10939 }
John Wiegley01296292011-04-08 18:41:53 +000010940 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010941 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10942 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010943
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010944 DeclarationNameInfo OpLocInfo(
10945 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10946 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010947 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010948 HadMultipleCandidates,
10949 OpLocInfo.getLoc(),
10950 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010951 if (NewFn.isInvalid())
10952 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010953
10954 // Once we've built TheCall, all of the expressions are properly
10955 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010956 QualType ResultTy = Method->getResultType();
10957 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10958 ResultTy = ResultTy.getNonLValueExprType(Context);
10959
John McCallb268a282010-08-23 23:25:46 +000010960 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010961 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010962 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010963 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010964 delete [] MethodArgs;
10965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010966 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010967 Method))
10968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010969
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010970 // We may have default arguments. If so, we need to allocate more
10971 // slots in the call for them.
10972 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010973 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010974 else if (NumArgs > NumArgsInProto)
10975 NumArgsToCheck = NumArgsInProto;
10976
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010977 bool IsError = false;
10978
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010979 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010980 ExprResult ObjRes =
10981 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10982 Best->FoundDecl, Method);
10983 if (ObjRes.isInvalid())
10984 IsError = true;
10985 else
10986 Object = move(ObjRes);
10987 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010988
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010989 // Check the argument types.
10990 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010991 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010992 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010993 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010994
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010995 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010996
John McCalldadc5752010-08-24 06:29:42 +000010997 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010998 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010999 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011000 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011001 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011002
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011003 IsError |= InputInit.isInvalid();
11004 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011005 } else {
John McCalldadc5752010-08-24 06:29:42 +000011006 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011007 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11008 if (DefArg.isInvalid()) {
11009 IsError = true;
11010 break;
11011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011012
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011013 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011014 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011015
11016 TheCall->setArg(i + 1, Arg);
11017 }
11018
11019 // If this is a variadic call, handle args passed through "...".
11020 if (Proto->isVariadic()) {
11021 // Promote the arguments (C99 6.5.2.2p7).
11022 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011023 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11024 IsError |= Arg.isInvalid();
11025 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011026 }
11027 }
11028
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011029 if (IsError) return true;
11030
Eli Friedmanff4b4072012-02-18 04:48:30 +000011031 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11032
John McCallb268a282010-08-23 23:25:46 +000011033 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011034 return true;
11035
John McCalle172be52010-08-24 06:09:16 +000011036 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011037}
11038
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011039/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011040/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011041/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011042ExprResult
John McCallb268a282010-08-23 23:25:46 +000011043Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011044 assert(Base->getType()->isRecordType() &&
11045 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011046
John McCall4124c492011-10-17 18:40:02 +000011047 if (checkPlaceholderForOverload(*this, Base))
11048 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011049
John McCallbc077cf2010-02-08 23:07:23 +000011050 SourceLocation Loc = Base->getExprLoc();
11051
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011052 // C++ [over.ref]p1:
11053 //
11054 // [...] An expression x->m is interpreted as (x.operator->())->m
11055 // for a class object x of type T if T::operator->() exists and if
11056 // the operator is selected as the best match function by the
11057 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011058 DeclarationName OpName =
11059 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011060 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011061 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011062
John McCallbc077cf2010-02-08 23:07:23 +000011063 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011064 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011065 return ExprError();
11066
John McCall27b18f82009-11-17 02:14:36 +000011067 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11068 LookupQualifiedName(R, BaseRecord->getDecl());
11069 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011070
11071 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011072 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011073 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11074 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011075 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011076
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011077 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11078
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011079 // Perform overload resolution.
11080 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011081 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011082 case OR_Success:
11083 // Overload resolution succeeded; we'll build the call below.
11084 break;
11085
11086 case OR_No_Viable_Function:
11087 if (CandidateSet.empty())
11088 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011089 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011090 else
11091 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011092 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011093 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011094 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011095
11096 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011097 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11098 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011099 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011100 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011101
11102 case OR_Deleted:
11103 Diag(OpLoc, diag::err_ovl_deleted_oper)
11104 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011105 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011106 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011107 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011108 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011109 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011110 }
11111
Eli Friedmanfa0df832012-02-02 03:46:19 +000011112 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011113 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011114 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011115
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011116 // Convert the object parameter.
11117 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011118 ExprResult BaseResult =
11119 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11120 Best->FoundDecl, Method);
11121 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011122 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011123 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011124
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011125 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011126 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011127 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011128 if (FnExpr.isInvalid())
11129 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011130
John McCall7decc9e2010-11-18 06:31:45 +000011131 QualType ResultTy = Method->getResultType();
11132 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11133 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011134 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011135 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000011136 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011137
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011138 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011139 Method))
11140 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011141
11142 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011143}
11144
Richard Smithbcc22fc2012-03-09 08:00:36 +000011145/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11146/// a literal operator described by the provided lookup results.
11147ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11148 DeclarationNameInfo &SuffixInfo,
11149 ArrayRef<Expr*> Args,
11150 SourceLocation LitEndLoc,
11151 TemplateArgumentListInfo *TemplateArgs) {
11152 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011153
Richard Smithbcc22fc2012-03-09 08:00:36 +000011154 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11155 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11156 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011157
Richard Smithbcc22fc2012-03-09 08:00:36 +000011158 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11159
Richard Smithbcc22fc2012-03-09 08:00:36 +000011160 // Perform overload resolution. This will usually be trivial, but might need
11161 // to perform substitutions for a literal operator template.
11162 OverloadCandidateSet::iterator Best;
11163 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11164 case OR_Success:
11165 case OR_Deleted:
11166 break;
11167
11168 case OR_No_Viable_Function:
11169 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11170 << R.getLookupName();
11171 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11172 return ExprError();
11173
11174 case OR_Ambiguous:
11175 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11176 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11177 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011178 }
11179
Richard Smithbcc22fc2012-03-09 08:00:36 +000011180 FunctionDecl *FD = Best->Function;
11181 MarkFunctionReferenced(UDSuffixLoc, FD);
11182 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011183
Richard Smithbcc22fc2012-03-09 08:00:36 +000011184 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11185 SuffixInfo.getLoc(),
11186 SuffixInfo.getInfo());
11187 if (Fn.isInvalid())
11188 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011189
11190 // Check the argument types. This should almost always be a no-op, except
11191 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011192 Expr *ConvArgs[2];
11193 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11194 ExprResult InputInit = PerformCopyInitialization(
11195 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11196 SourceLocation(), Args[ArgIdx]);
11197 if (InputInit.isInvalid())
11198 return true;
11199 ConvArgs[ArgIdx] = InputInit.take();
11200 }
11201
Richard Smithc67fdd42012-03-07 08:35:16 +000011202 QualType ResultTy = FD->getResultType();
11203 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11204 ResultTy = ResultTy.getNonLValueExprType(Context);
11205
Richard Smithc67fdd42012-03-07 08:35:16 +000011206 UserDefinedLiteral *UDL =
11207 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11208 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11209
11210 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11211 return ExprError();
11212
11213 if (CheckFunctionCall(FD, UDL))
11214 return ExprError();
11215
11216 return MaybeBindToTemporary(UDL);
11217}
11218
Douglas Gregorcd695e52008-11-10 20:40:00 +000011219/// FixOverloadedFunctionReference - E is an expression that refers to
11220/// a C++ overloaded function (possibly with some parentheses and
11221/// perhaps a '&' around it). We have resolved the overloaded function
11222/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011223/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011224Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011225 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011226 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011227 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11228 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011229 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011230 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011231
Douglas Gregor51c538b2009-11-20 19:42:02 +000011232 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011233 }
11234
Douglas Gregor51c538b2009-11-20 19:42:02 +000011235 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011236 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11237 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011238 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011239 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011240 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011241 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011242 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011243 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011244
11245 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011246 ICE->getCastKind(),
11247 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011248 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011249 }
11250
Douglas Gregor51c538b2009-11-20 19:42:02 +000011251 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011252 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011253 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011254 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11255 if (Method->isStatic()) {
11256 // Do nothing: static member functions aren't any different
11257 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011258 } else {
John McCalle66edc12009-11-24 19:00:30 +000011259 // Fix the sub expression, which really has to be an
11260 // UnresolvedLookupExpr holding an overloaded member function
11261 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011262 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11263 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011264 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011265 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011266
John McCalld14a8642009-11-21 08:51:07 +000011267 assert(isa<DeclRefExpr>(SubExpr)
11268 && "fixed to something other than a decl ref");
11269 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11270 && "fixed to a member ref with no nested name qualifier");
11271
11272 // We have taken the address of a pointer to member
11273 // function. Perform the computation here so that we get the
11274 // appropriate pointer to member type.
11275 QualType ClassType
11276 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11277 QualType MemPtrType
11278 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11279
John McCall7decc9e2010-11-18 06:31:45 +000011280 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11281 VK_RValue, OK_Ordinary,
11282 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011283 }
11284 }
John McCall16df1e52010-03-30 21:47:33 +000011285 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11286 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011287 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011288 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011289
John McCalle3027922010-08-25 11:45:40 +000011290 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011291 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011292 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011293 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011294 }
John McCalld14a8642009-11-21 08:51:07 +000011295
11296 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011297 // FIXME: avoid copy.
11298 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011299 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011300 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11301 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011302 }
11303
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011304 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11305 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011306 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011307 Fn,
John McCall113bee02012-03-10 09:33:50 +000011308 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011309 ULE->getNameLoc(),
11310 Fn->getType(),
11311 VK_LValue,
11312 Found.getDecl(),
11313 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011314 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011315 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11316 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011317 }
11318
John McCall10eae182009-11-30 22:42:35 +000011319 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011320 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011321 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11322 if (MemExpr->hasExplicitTemplateArgs()) {
11323 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11324 TemplateArgs = &TemplateArgsBuffer;
11325 }
John McCall6b51f282009-11-23 01:53:49 +000011326
John McCall2d74de92009-12-01 22:10:20 +000011327 Expr *Base;
11328
John McCall7decc9e2010-11-18 06:31:45 +000011329 // If we're filling in a static method where we used to have an
11330 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011331 if (MemExpr->isImplicitAccess()) {
11332 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011333 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11334 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011335 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011336 Fn,
John McCall113bee02012-03-10 09:33:50 +000011337 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011338 MemExpr->getMemberLoc(),
11339 Fn->getType(),
11340 VK_LValue,
11341 Found.getDecl(),
11342 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011343 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011344 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11345 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011346 } else {
11347 SourceLocation Loc = MemExpr->getMemberLoc();
11348 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011349 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011350 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011351 Base = new (Context) CXXThisExpr(Loc,
11352 MemExpr->getBaseType(),
11353 /*isImplicit=*/true);
11354 }
John McCall2d74de92009-12-01 22:10:20 +000011355 } else
John McCallc3007a22010-10-26 07:05:15 +000011356 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011357
John McCall4adb38c2011-04-27 00:36:17 +000011358 ExprValueKind valueKind;
11359 QualType type;
11360 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11361 valueKind = VK_LValue;
11362 type = Fn->getType();
11363 } else {
11364 valueKind = VK_RValue;
11365 type = Context.BoundMemberTy;
11366 }
11367
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011368 MemberExpr *ME = MemberExpr::Create(Context, Base,
11369 MemExpr->isArrow(),
11370 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011371 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011372 Fn,
11373 Found,
11374 MemExpr->getMemberNameInfo(),
11375 TemplateArgs,
11376 type, valueKind, OK_Ordinary);
11377 ME->setHadMultipleCandidates(true);
11378 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011380
John McCallc3007a22010-10-26 07:05:15 +000011381 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011382}
11383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011384ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011385 DeclAccessPair Found,
11386 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011387 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011388}
11389
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011390} // end namespace clang