blob: 44ff3a505e459e5d034998e5d307990f549e98c3 [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
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
John McCall7decc9e2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000053 return E;
John McCall7decc9e2010-11-18 06:31:45 +000054}
55
John McCall5c32be02010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000061
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000204}
205
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000244bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith66e05fe2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000408 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 break;
John McCall0d1da222010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000513 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520}
521
John McCall0d1da222010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
539 // template parameter and template argument information.
540 struct DFIParamWithArguments {
541 TemplateParameter Param;
542 TemplateArgument FirstArg;
543 TemplateArgument SecondArg;
544 };
545}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000550static MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000552 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 OverloadCandidate::DeductionFailureInfo Result;
554 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000556 Result.Data = 0;
557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000570 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000571 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Saved->Param = Info.Param;
575 Saved->FirstArg = Info.FirstArg;
576 Saved->SecondArg = Info.SecondArg;
577 Result.Data = Saved;
578 break;
579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000582 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000583 if (Info.hasSFINAEDiagnostic()) {
584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585 SourceLocation(), PartialDiagnostic::NullDiagnostic());
586 Info.takeSFINAEDiagnostic(*Diag);
587 Result.HasDiagnostic = true;
588 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000611 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000612 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 Data = 0;
614 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000615
616 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000617 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620 Diag->~PartialDiagnosticAt();
621 HasDiagnostic = false;
622 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor461761d2010-05-08 18:20:53 +0000625 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
628 break;
629 }
630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Richard Smith9ca64612012-05-07 09:03:25 +0000632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636 return 0;
637}
638
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000645 case Sema::TDK_TooManyArguments:
646 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000651 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653
654 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 case Sema::TDK_FailedOverloadResolution:
661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregord09efd42010-05-08 20:07:26 +0000667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregord09efd42010-05-08 20:07:26 +0000672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 return 0;
680
681 case Sema::TDK_SubstitutionFailure:
682 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregord09efd42010-05-08 20:07:26 +0000684 // Unhandled
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 break;
688 }
689
690 return 0;
691}
692
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 return 0;
704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000706 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708
Douglas Gregor461761d2010-05-08 18:20:53 +0000709 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711 case Sema::TDK_FailedOverloadResolution:
712 break;
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
Douglas Gregor461761d2010-05-08 18:20:53 +0000735 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737 case Sema::TDK_FailedOverloadResolution:
738 break;
739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000741 return 0;
742}
743
Benjamin Kramer97e59492012-10-09 15:52:25 +0000744void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000745 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749 i->DeductionFailure.Destroy();
750 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000751}
752
753void OverloadCandidateSet::clear() {
754 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000755 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000756 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757 Functions.clear();
758}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759
John McCall4124c492011-10-17 18:40:02 +0000760namespace {
761 class UnbridgedCastsSet {
762 struct Entry {
763 Expr **Addr;
764 Expr *Saved;
765 };
766 SmallVector<Entry, 2> Entries;
767
768 public:
769 void save(Sema &S, Expr *&E) {
770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771 Entry entry = { &E, E };
772 Entries.push_back(entry);
773 E = S.stripARCUnbridgedCast(E);
774 }
775
776 void restore() {
777 for (SmallVectorImpl<Entry>::iterator
778 i = Entries.begin(), e = Entries.end(); i != e; ++i)
779 *i->Addr = i->Saved;
780 }
781 };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788/// without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
794 // We can't handle overloaded expressions here because overload
795 // resolution might reasonably tweak them.
796 if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798 // If the context potentially accepts unbridged ARC casts, strip
799 // the unbridged cast and add it to the collection for later restoration.
800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801 unbridgedCasts) {
802 unbridgedCasts->save(S, E);
803 return false;
804 }
805
806 // Go ahead and check everything else.
807 ExprResult result = S.CheckPlaceholderExpr(E);
808 if (result.isInvalid())
809 return true;
810
811 E = result.take();
812 return false;
813 }
814
815 // Nothing to do.
816 return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822 unsigned numArgs,
823 UnbridgedCastsSet &unbridged) {
824 for (unsigned i = 0; i != numArgs; ++i)
825 if (checkPlaceholderForOverload(S, args[i], &unbridged))
826 return true;
827
828 return false;
829}
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with. This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839//
840// Example: Given the following input:
841//
842// void f(int, float); // #1
843// void f(int, int); // #2
844// int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000847// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848//
John McCall3d988d92009-12-02 08:47:38 +0000849// When we process #2, Old contains only the FunctionDecl for #1. By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853//
John McCall3d988d92009-12-02 08:47:38 +0000854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration. The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000865Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000868 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000869 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000870 NamedDecl *OldD = *I;
871
872 bool OldIsUsingDecl = false;
873 if (isa<UsingShadowDecl>(OldD)) {
874 OldIsUsingDecl = true;
875
876 // We can always introduce two using declarations into the same
877 // context, even if they have identical signatures.
878 if (NewIsUsingDecl) continue;
879
880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881 }
882
883 // If either declaration was introduced by a using declaration,
884 // we'll need to use slightly different rules for matching.
885 // Essentially, these rules are the normal rules, except that
886 // function templates hide function templates with different
887 // return types or template parameter lists.
888 bool UseMemberUsingDeclRules =
889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
John McCall3d988d92009-12-02 08:47:38 +0000891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895 continue;
896 }
897
John McCalldaa3d6b2009-12-09 03:35:25 +0000898 Match = *I;
899 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900 }
John McCall3d988d92009-12-02 08:47:38 +0000901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905 continue;
906 }
907
John McCalldaa3d6b2009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000910 }
John McCalla8987a2942010-11-10 03:01:53 +0000911 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000912 // We can overload with these, which can show up when doing
913 // redeclaration checks for UsingDecls.
914 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000915 } else if (isa<TagDecl>(OldD)) {
916 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918 // Optimistically assume that an unresolved using decl will
919 // overload; if it doesn't, we'll have to diagnose during
920 // template instantiation.
921 } else {
John McCall1f82f242009-11-18 22:49:29 +0000922 // (C++ 13p1):
923 // Only function declarations can be overloaded; object and type
924 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000925 Match = *I;
926 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000927 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928 }
John McCall1f82f242009-11-18 22:49:29 +0000929
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000931}
932
Rafael Espindola576127d2012-12-28 14:21:58 +0000933static bool canBeOverloaded(const FunctionDecl &D) {
934 if (D.getAttr<OverloadableAttr>())
935 return true;
936 if (D.hasCLanguageLinkage())
937 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000938
939 // Main cannot be overloaded (basic.start.main).
940 if (D.isMain())
941 return false;
942
Rafael Espindola576127d2012-12-28 14:21:58 +0000943 return true;
944}
945
John McCalle9cccd82010-06-16 08:42:20 +0000946bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
947 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000948 // If both of the functions are extern "C", then they are not
949 // overloads.
Rafael Espindola576127d2012-12-28 14:21:58 +0000950 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall8246e352010-08-12 07:09:11 +0000951 return false;
952
John McCall1f82f242009-11-18 22:49:29 +0000953 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
954 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
955
956 // C++ [temp.fct]p2:
957 // A function template can be overloaded with other function templates
958 // and with normal (non-template) functions.
959 if ((OldTemplate == 0) != (NewTemplate == 0))
960 return true;
961
962 // Is the function New an overload of the function Old?
963 QualType OldQType = Context.getCanonicalType(Old->getType());
964 QualType NewQType = Context.getCanonicalType(New->getType());
965
966 // Compare the signatures (C++ 1.3.10) of the two functions to
967 // determine whether they are overloads. If we find any mismatch
968 // in the signature, they are overloads.
969
970 // If either of these functions is a K&R-style function (no
971 // prototype), then we consider them to have matching signatures.
972 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
973 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
974 return false;
975
John McCall424cec92011-01-19 06:33:43 +0000976 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
977 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000978
979 // The signature of a function includes the types of its
980 // parameters (C++ 1.3.10), which includes the presence or absence
981 // of the ellipsis; see C++ DR 357).
982 if (OldQType != NewQType &&
983 (OldType->getNumArgs() != NewType->getNumArgs() ||
984 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000985 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000986 return true;
987
988 // C++ [temp.over.link]p4:
989 // The signature of a function template consists of its function
990 // signature, its return type and its template parameter list. The names
991 // of the template parameters are significant only for establishing the
992 // relationship between the template parameters and the rest of the
993 // signature.
994 //
995 // We check the return type and template parameter lists for function
996 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000997 //
998 // However, we don't consider either of these when deciding whether
999 // a member introduced by a shadow declaration is hidden.
1000 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +00001001 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1002 OldTemplate->getTemplateParameters(),
1003 false, TPL_TemplateMatch) ||
1004 OldType->getResultType() != NewType->getResultType()))
1005 return true;
1006
1007 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001008 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001009 //
1010 // As part of this, also check whether one of the member functions
1011 // is static, in which case they are not overloads (C++
1012 // 13.1p2). While not part of the definition of the signature,
1013 // this check is important to determine whether these functions
1014 // can be overloaded.
1015 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1016 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1017 if (OldMethod && NewMethod &&
1018 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001019 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +00001020 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1021 if (!UseUsingDeclRules &&
1022 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1023 (OldMethod->getRefQualifier() == RQ_None ||
1024 NewMethod->getRefQualifier() == RQ_None)) {
1025 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026 // - Member function declarations with the same name and the same
1027 // parameter-type-list as well as member function template
1028 // declarations with the same name, the same parameter-type-list, and
1029 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001030 // them, but not all, have a ref-qualifier (8.3.5).
1031 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1032 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1033 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
John McCall1f82f242009-11-18 22:49:29 +00001036 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038
John McCall1f82f242009-11-18 22:49:29 +00001039 // The signatures match; this is not an overload.
1040 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001041}
1042
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001043/// \brief Checks availability of the function depending on the current
1044/// function context. Inside an unavailable function, unavailability is ignored.
1045///
1046/// \returns true if \arg FD is unavailable and current context is inside
1047/// an available function, false otherwise.
1048bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1049 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1050}
1051
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001052/// \brief Tries a user-defined conversion from From to ToType.
1053///
1054/// Produces an implicit conversion sequence for when a standard conversion
1055/// is not an option. See TryImplicitConversion for more information.
1056static ImplicitConversionSequence
1057TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1058 bool SuppressUserConversions,
1059 bool AllowExplicit,
1060 bool InOverloadResolution,
1061 bool CStyle,
1062 bool AllowObjCWritebackConversion) {
1063 ImplicitConversionSequence ICS;
1064
1065 if (SuppressUserConversions) {
1066 // We're not in the case above, so there is no conversion that
1067 // we can perform.
1068 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1069 return ICS;
1070 }
1071
1072 // Attempt user-defined conversion.
1073 OverloadCandidateSet Conversions(From->getExprLoc());
1074 OverloadingResult UserDefResult
1075 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1076 AllowExplicit);
1077
1078 if (UserDefResult == OR_Success) {
1079 ICS.setUserDefined();
1080 // C++ [over.ics.user]p4:
1081 // A conversion of an expression of class type to the same class
1082 // type is given Exact Match rank, and a conversion of an
1083 // expression of class type to a base class of that type is
1084 // given Conversion rank, in spite of the fact that a copy
1085 // constructor (i.e., a user-defined conversion function) is
1086 // called for those cases.
1087 if (CXXConstructorDecl *Constructor
1088 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1089 QualType FromCanon
1090 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1091 QualType ToCanon
1092 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1093 if (Constructor->isCopyConstructor() &&
1094 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1095 // Turn this into a "standard" conversion sequence, so that it
1096 // gets ranked with standard conversion sequences.
1097 ICS.setStandard();
1098 ICS.Standard.setAsIdentityConversion();
1099 ICS.Standard.setFromType(From->getType());
1100 ICS.Standard.setAllToTypes(ToType);
1101 ICS.Standard.CopyConstructor = Constructor;
1102 if (ToCanon != FromCanon)
1103 ICS.Standard.Second = ICK_Derived_To_Base;
1104 }
1105 }
1106
1107 // C++ [over.best.ics]p4:
1108 // However, when considering the argument of a user-defined
1109 // conversion function that is a candidate by 13.3.1.3 when
1110 // invoked for the copying of the temporary in the second step
1111 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1112 // 13.3.1.6 in all cases, only standard conversion sequences and
1113 // ellipsis conversion sequences are allowed.
1114 if (SuppressUserConversions && ICS.isUserDefined()) {
1115 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1116 }
1117 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1118 ICS.setAmbiguous();
1119 ICS.Ambiguous.setFromType(From->getType());
1120 ICS.Ambiguous.setToType(ToType);
1121 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1122 Cand != Conversions.end(); ++Cand)
1123 if (Cand->Viable)
1124 ICS.Ambiguous.addConversion(Cand->Function);
1125 } else {
1126 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1127 }
1128
1129 return ICS;
1130}
1131
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001132/// TryImplicitConversion - Attempt to perform an implicit conversion
1133/// from the given expression (Expr) to the given type (ToType). This
1134/// function returns an implicit conversion sequence that can be used
1135/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001136///
1137/// void f(float f);
1138/// void g(int i) { f(i); }
1139///
1140/// this routine would produce an implicit conversion sequence to
1141/// describe the initialization of f from i, which will be a standard
1142/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1143/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1144//
1145/// Note that this routine only determines how the conversion can be
1146/// performed; it does not actually perform the conversion. As such,
1147/// it will not produce any diagnostics if no conversion is available,
1148/// but will instead return an implicit conversion sequence of kind
1149/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001150///
1151/// If @p SuppressUserConversions, then user-defined conversions are
1152/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001153/// If @p AllowExplicit, then explicit user-defined conversions are
1154/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001155///
1156/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1157/// writeback conversion, which allows __autoreleasing id* parameters to
1158/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001159static ImplicitConversionSequence
1160TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1161 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001162 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001163 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001164 bool CStyle,
1165 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001167 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001168 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001169 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001170 return ICS;
1171 }
1172
David Blaikiebbafb8a2012-03-11 07:00:24 +00001173 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001174 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001175 return ICS;
1176 }
1177
Douglas Gregor836a7e82010-08-11 02:15:33 +00001178 // C++ [over.ics.user]p4:
1179 // A conversion of an expression of class type to the same class
1180 // type is given Exact Match rank, and a conversion of an
1181 // expression of class type to a base class of that type is
1182 // given Conversion rank, in spite of the fact that a copy/move
1183 // constructor (i.e., a user-defined conversion function) is
1184 // called for those cases.
1185 QualType FromType = From->getType();
1186 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001187 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1188 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001189 ICS.setStandard();
1190 ICS.Standard.setAsIdentityConversion();
1191 ICS.Standard.setFromType(FromType);
1192 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193
Douglas Gregor5ab11652010-04-17 22:01:05 +00001194 // We don't actually check at this point whether there is a valid
1195 // copy/move constructor, since overloading just assumes that it
1196 // exists. When we actually perform initialization, we'll find the
1197 // appropriate constructor to copy the returned object, if needed.
1198 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199
Douglas Gregor5ab11652010-04-17 22:01:05 +00001200 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001201 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001202 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203
Douglas Gregor836a7e82010-08-11 02:15:33 +00001204 return ICS;
1205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001207 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1208 AllowExplicit, InOverloadResolution, CStyle,
1209 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001210}
1211
John McCall31168b02011-06-15 23:02:42 +00001212ImplicitConversionSequence
1213Sema::TryImplicitConversion(Expr *From, QualType ToType,
1214 bool SuppressUserConversions,
1215 bool AllowExplicit,
1216 bool InOverloadResolution,
1217 bool CStyle,
1218 bool AllowObjCWritebackConversion) {
1219 return clang::TryImplicitConversion(*this, From, ToType,
1220 SuppressUserConversions, AllowExplicit,
1221 InOverloadResolution, CStyle,
1222 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001223}
1224
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001225/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001226/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001227/// converted expression. Flavor is the kind of conversion we're
1228/// performing, used in the error message. If @p AllowExplicit,
1229/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001230ExprResult
1231Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001232 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001233 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001234 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001235}
1236
John Wiegley01296292011-04-08 18:41:53 +00001237ExprResult
1238Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001239 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001240 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001241 if (checkPlaceholderForOverload(*this, From))
1242 return ExprError();
1243
John McCall31168b02011-06-15 23:02:42 +00001244 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1245 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001246 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001247 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001248
John McCall5c32be02010-08-24 20:38:10 +00001249 ICS = clang::TryImplicitConversion(*this, From, ToType,
1250 /*SuppressUserConversions=*/false,
1251 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001252 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001253 /*CStyle=*/false,
1254 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001255 return PerformImplicitConversion(From, ToType, ICS, Action);
1256}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257
1258/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001259/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001260bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1261 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001262 if (Context.hasSameUnqualifiedType(FromType, ToType))
1263 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
John McCall991eb4b2010-12-21 00:44:39 +00001265 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1266 // where F adds one of the following at most once:
1267 // - a pointer
1268 // - a member pointer
1269 // - a block pointer
1270 CanQualType CanTo = Context.getCanonicalType(ToType);
1271 CanQualType CanFrom = Context.getCanonicalType(FromType);
1272 Type::TypeClass TyClass = CanTo->getTypeClass();
1273 if (TyClass != CanFrom->getTypeClass()) return false;
1274 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1275 if (TyClass == Type::Pointer) {
1276 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1277 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1278 } else if (TyClass == Type::BlockPointer) {
1279 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1280 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1281 } else if (TyClass == Type::MemberPointer) {
1282 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1283 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1284 } else {
1285 return false;
1286 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001287
John McCall991eb4b2010-12-21 00:44:39 +00001288 TyClass = CanTo->getTypeClass();
1289 if (TyClass != CanFrom->getTypeClass()) return false;
1290 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1291 return false;
1292 }
1293
1294 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1295 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1296 if (!EInfo.getNoReturn()) return false;
1297
1298 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1299 assert(QualType(FromFn, 0).isCanonical());
1300 if (QualType(FromFn, 0) != CanTo) return false;
1301
1302 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001303 return true;
1304}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305
Douglas Gregor46188682010-05-18 22:42:18 +00001306/// \brief Determine whether the conversion from FromType to ToType is a valid
1307/// vector conversion.
1308///
1309/// \param ICK Will be set to the vector conversion kind, if this is a vector
1310/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1312 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001313 // We need at least one of these types to be a vector type to have a vector
1314 // conversion.
1315 if (!ToType->isVectorType() && !FromType->isVectorType())
1316 return false;
1317
1318 // Identical types require no conversions.
1319 if (Context.hasSameUnqualifiedType(FromType, ToType))
1320 return false;
1321
1322 // There are no conversions between extended vector types, only identity.
1323 if (ToType->isExtVectorType()) {
1324 // There are no conversions between extended vector types other than the
1325 // identity conversion.
1326 if (FromType->isExtVectorType())
1327 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregor46188682010-05-18 22:42:18 +00001329 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001330 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001331 ICK = ICK_Vector_Splat;
1332 return true;
1333 }
1334 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001335
1336 // We can perform the conversion between vector types in the following cases:
1337 // 1)vector types are equivalent AltiVec and GCC vector types
1338 // 2)lax vector conversions are permitted and the vector types are of the
1339 // same size
1340 if (ToType->isVectorType() && FromType->isVectorType()) {
1341 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001342 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001343 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001344 ICK = ICK_Vector_Conversion;
1345 return true;
1346 }
Douglas Gregor46188682010-05-18 22:42:18 +00001347 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001348
Douglas Gregor46188682010-05-18 22:42:18 +00001349 return false;
1350}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001352static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1353 bool InOverloadResolution,
1354 StandardConversionSequence &SCS,
1355 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001356
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001357/// IsStandardConversion - Determines whether there is a standard
1358/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1359/// expression From to the type ToType. Standard conversion sequences
1360/// only consider non-class types; for conversions that involve class
1361/// types, use TryImplicitConversion. If a conversion exists, SCS will
1362/// contain the standard conversion sequence required to perform this
1363/// conversion and this routine will return true. Otherwise, this
1364/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001365static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1366 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001367 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001368 bool CStyle,
1369 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001370 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001372 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001373 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001374 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001375 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001376 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001377 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001378
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001379 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001380 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001381 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001382 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001383 return false;
1384
Mike Stump11289f42009-09-09 15:08:12 +00001385 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001386 }
1387
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001388 // The first conversion can be an lvalue-to-rvalue conversion,
1389 // array-to-pointer conversion, or function-to-pointer conversion
1390 // (C++ 4p1).
1391
John McCall5c32be02010-08-24 20:38:10 +00001392 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001393 DeclAccessPair AccessPair;
1394 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001396 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001397 // We were able to resolve the address of the overloaded function,
1398 // so we can convert to the type of that function.
1399 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001400
1401 // we can sometimes resolve &foo<int> regardless of ToType, so check
1402 // if the type matches (identity) or we are converting to bool
1403 if (!S.Context.hasSameUnqualifiedType(
1404 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1405 QualType resultTy;
1406 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001407 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001408 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1409 // otherwise, only a boolean conversion is standard
1410 if (!ToType->isBooleanType())
1411 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
Chandler Carruthffce2452011-03-29 08:08:18 +00001414 // Check if the "from" expression is taking the address of an overloaded
1415 // function and recompute the FromType accordingly. Take advantage of the
1416 // fact that non-static member functions *must* have such an address-of
1417 // expression.
1418 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1419 if (Method && !Method->isStatic()) {
1420 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1421 "Non-unary operator on non-static member address");
1422 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1423 == UO_AddrOf &&
1424 "Non-address-of operator on non-static member address");
1425 const Type *ClassType
1426 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1427 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001428 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1429 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1430 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001431 "Non-address-of operator for overloaded function expression");
1432 FromType = S.Context.getPointerType(FromType);
1433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor980fb162010-04-29 18:24:40 +00001435 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001436 assert(S.Context.hasSameType(
1437 FromType,
1438 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001439 } else {
1440 return false;
1441 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001442 }
John McCall154a2fd2011-08-30 00:57:29 +00001443 // Lvalue-to-rvalue conversion (C++11 4.1):
1444 // A glvalue (3.10) of a non-function, non-array type T can
1445 // be converted to a prvalue.
1446 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001447 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001448 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001449 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001450 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001451
Douglas Gregorc79862f2012-04-12 17:51:55 +00001452 // C11 6.3.2.1p2:
1453 // ... if the lvalue has atomic type, the value has the non-atomic version
1454 // of the type of the lvalue ...
1455 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1456 FromType = Atomic->getValueType();
1457
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458 // If T is a non-class type, the type of the rvalue is the
1459 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001460 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1461 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001463 } else if (FromType->isArrayType()) {
1464 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001465 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001466
1467 // An lvalue or rvalue of type "array of N T" or "array of unknown
1468 // bound of T" can be converted to an rvalue of type "pointer to
1469 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001470 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471
John McCall5c32be02010-08-24 20:38:10 +00001472 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001474 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475
1476 // For the purpose of ranking in overload resolution
1477 // (13.3.3.1.1), this conversion is considered an
1478 // array-to-pointer conversion followed by a qualification
1479 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001480 SCS.Second = ICK_Identity;
1481 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001482 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001483 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485 }
John McCall086a4642010-11-24 05:12:34 +00001486 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001487 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001489
1490 // An lvalue of function type T can be converted to an rvalue of
1491 // type "pointer to T." The result is a pointer to the
1492 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001493 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001494 } else {
1495 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001498 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001499
1500 // The second conversion can be an integral promotion, floating
1501 // point promotion, integral conversion, floating point conversion,
1502 // floating-integral conversion, pointer conversion,
1503 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001504 // For overloading in C, this can also be a "compatible-type"
1505 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001506 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001507 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001508 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509 // The unqualified versions of the types are the same: there's no
1510 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001512 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001513 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001515 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001516 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001517 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001520 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001522 SCS.Second = ICK_Complex_Promotion;
1523 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001524 } else if (ToType->isBooleanType() &&
1525 (FromType->isArithmeticType() ||
1526 FromType->isAnyPointerType() ||
1527 FromType->isBlockPointerType() ||
1528 FromType->isMemberPointerType() ||
1529 FromType->isNullPtrType())) {
1530 // Boolean conversions (C++ 4.12).
1531 SCS.Second = ICK_Boolean_Conversion;
1532 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001533 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001534 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001535 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001538 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001539 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001540 SCS.Second = ICK_Complex_Conversion;
1541 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001542 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1543 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001544 // Complex-real conversions (C99 6.3.1.7)
1545 SCS.Second = ICK_Complex_Real;
1546 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001547 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001548 // Floating point conversions (C++ 4.8).
1549 SCS.Second = ICK_Floating_Conversion;
1550 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001552 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001553 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001554 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001555 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001558 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001559 SCS.Second = ICK_Block_Pointer_Conversion;
1560 } else if (AllowObjCWritebackConversion &&
1561 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1562 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001563 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1564 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001567 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001568 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001570 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001571 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001572 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001573 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001574 SCS.Second = SecondICK;
1575 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001577 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001578 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001579 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001580 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001581 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001582 // Treat a conversion that strips "noreturn" as an identity conversion.
1583 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001584 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1585 InOverloadResolution,
1586 SCS, CStyle)) {
1587 SCS.Second = ICK_TransparentUnionConversion;
1588 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001589 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1590 CStyle)) {
1591 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001592 // appropriately.
1593 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 } else {
1595 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001598 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001600 QualType CanonFrom;
1601 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001603 bool ObjCLifetimeConversion;
1604 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1605 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001606 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001607 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001609 CanonFrom = S.Context.getCanonicalType(FromType);
1610 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611 } else {
1612 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001613 SCS.Third = ICK_Identity;
1614
Mike Stump11289f42009-09-09 15:08:12 +00001615 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001616 // [...] Any difference in top-level cv-qualification is
1617 // subsumed by the initialization itself and does not constitute
1618 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001619 CanonFrom = S.Context.getCanonicalType(FromType);
1620 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001622 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001623 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001624 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1625 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001626 FromType = ToType;
1627 CanonFrom = CanonTo;
1628 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001630 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631
1632 // If we have not converted the argument type to the parameter type,
1633 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001634 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001639
1640static bool
1641IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1642 QualType &ToType,
1643 bool InOverloadResolution,
1644 StandardConversionSequence &SCS,
1645 bool CStyle) {
1646
1647 const RecordType *UT = ToType->getAsUnionType();
1648 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1649 return false;
1650 // The field to initialize within the transparent union.
1651 RecordDecl *UD = UT->getDecl();
1652 // It's compatible if the expression matches any of the fields.
1653 for (RecordDecl::field_iterator it = UD->field_begin(),
1654 itend = UD->field_end();
1655 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001656 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1657 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001658 ToType = it->getType();
1659 return true;
1660 }
1661 }
1662 return false;
1663}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664
1665/// IsIntegralPromotion - Determines whether the conversion from the
1666/// expression From (whose potentially-adjusted type is FromType) to
1667/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1668/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001669bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001670 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001671 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001672 if (!To) {
1673 return false;
1674 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675
1676 // An rvalue of type char, signed char, unsigned char, short int, or
1677 // unsigned short int can be converted to an rvalue of type int if
1678 // int can represent all the values of the source type; otherwise,
1679 // the source rvalue can be converted to an rvalue of type unsigned
1680 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001681 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1682 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 if (// We can promote any signed, promotable integer type to an int
1684 (FromType->isSignedIntegerType() ||
1685 // We can promote any unsigned integer type whose size is
1686 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001687 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001688 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001690 }
1691
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692 return To->getKind() == BuiltinType::UInt;
1693 }
1694
Richard Smithb9c5a602012-09-13 21:18:54 +00001695 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696 // A prvalue of an unscoped enumeration type whose underlying type is not
1697 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1698 // following types that can represent all the values of the enumeration
1699 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1700 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001701 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001703 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 // with lowest integer conversion rank (4.13) greater than the rank of long
1705 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001706 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001707 // C++11 [conv.prom]p4:
1708 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1709 // can be converted to a prvalue of its underlying type. Moreover, if
1710 // integral promotion can be applied to its underlying type, a prvalue of an
1711 // unscoped enumeration type whose underlying type is fixed can also be
1712 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001713 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1714 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1715 // provided for a scoped enumeration.
1716 if (FromEnumType->getDecl()->isScoped())
1717 return false;
1718
Richard Smithb9c5a602012-09-13 21:18:54 +00001719 // We can perform an integral promotion to the underlying type of the enum,
1720 // even if that's not the promoted type.
1721 if (FromEnumType->getDecl()->isFixed()) {
1722 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1723 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1724 IsIntegralPromotion(From, Underlying, ToType);
1725 }
1726
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001727 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001729 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001730 return Context.hasSameUnqualifiedType(ToType,
1731 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001732 }
John McCall56774992009-12-09 09:09:27 +00001733
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001734 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1736 // to an rvalue a prvalue of the first of the following types that can
1737 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001738 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001740 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001742 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001744 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745 // Determine whether the type we're converting from is signed or
1746 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001747 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001749
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001750 // The types we'll try to promote to, in the appropriate
1751 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001752 QualType PromoteTypes[6] = {
1753 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001754 Context.LongTy, Context.UnsignedLongTy ,
1755 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001757 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1759 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001760 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001761 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1762 // We found the type that we can promote to. If this is the
1763 // type we wanted, we have a promotion. Otherwise, no
1764 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001765 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 }
1767 }
1768 }
1769
1770 // An rvalue for an integral bit-field (9.6) can be converted to an
1771 // rvalue of type int if int can represent all the values of the
1772 // bit-field; otherwise, it can be converted to unsigned int if
1773 // unsigned int can represent all the values of the bit-field. If
1774 // the bit-field is larger yet, no integral promotion applies to
1775 // it. If the bit-field has an enumerated type, it is treated as any
1776 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001777 // FIXME: We should delay checking of bit-fields until we actually perform the
1778 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001779 using llvm::APSInt;
1780 if (From)
1781 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001782 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001783 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001784 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1785 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1786 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001788 // Are we promoting to an int from a bitfield that fits in an int?
1789 if (BitWidth < ToSize ||
1790 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1791 return To->getKind() == BuiltinType::Int;
1792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001794 // Are we promoting to an unsigned int from an unsigned bitfield
1795 // that fits into an unsigned int?
1796 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1797 return To->getKind() == BuiltinType::UInt;
1798 }
Mike Stump11289f42009-09-09 15:08:12 +00001799
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001800 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001801 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001802 }
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001804 // An rvalue of type bool can be converted to an rvalue of type int,
1805 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001806 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001807 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001808 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001809
1810 return false;
1811}
1812
1813/// IsFloatingPointPromotion - Determines whether the conversion from
1814/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1815/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001816bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001817 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1818 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001819 /// An rvalue of type float can be converted to an rvalue of type
1820 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821 if (FromBuiltin->getKind() == BuiltinType::Float &&
1822 ToBuiltin->getKind() == BuiltinType::Double)
1823 return true;
1824
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001825 // C99 6.3.1.5p1:
1826 // When a float is promoted to double or long double, or a
1827 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001828 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001829 (FromBuiltin->getKind() == BuiltinType::Float ||
1830 FromBuiltin->getKind() == BuiltinType::Double) &&
1831 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1832 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001833
1834 // Half can be promoted to float.
1835 if (FromBuiltin->getKind() == BuiltinType::Half &&
1836 ToBuiltin->getKind() == BuiltinType::Float)
1837 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001838 }
1839
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840 return false;
1841}
1842
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001843/// \brief Determine if a conversion is a complex promotion.
1844///
1845/// A complex promotion is defined as a complex -> complex conversion
1846/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001847/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001848bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001849 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001850 if (!FromComplex)
1851 return false;
1852
John McCall9dd450b2009-09-21 23:43:11 +00001853 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001854 if (!ToComplex)
1855 return false;
1856
1857 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001858 ToComplex->getElementType()) ||
1859 IsIntegralPromotion(0, FromComplex->getElementType(),
1860 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001861}
1862
Douglas Gregor237f96c2008-11-26 23:31:11 +00001863/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1864/// the pointer type FromPtr to a pointer to type ToPointee, with the
1865/// same type qualifiers as FromPtr has on its pointee type. ToType,
1866/// if non-empty, will be a pointer to ToType that may or may not have
1867/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001868///
Mike Stump11289f42009-09-09 15:08:12 +00001869static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001870BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001871 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001872 ASTContext &Context,
1873 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001874 assert((FromPtr->getTypeClass() == Type::Pointer ||
1875 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1876 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001877
John McCall31168b02011-06-15 23:02:42 +00001878 /// Conversions to 'id' subsume cv-qualifier conversions.
1879 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001880 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
1882 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001883 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001884 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001885 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001886
John McCall31168b02011-06-15 23:02:42 +00001887 if (StripObjCLifetime)
1888 Quals.removeObjCLifetime();
1889
Mike Stump11289f42009-09-09 15:08:12 +00001890 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001891 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001892 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001893 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001894 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001895
1896 // Build a pointer to ToPointee. It has the right qualifiers
1897 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001898 if (isa<ObjCObjectPointerType>(ToType))
1899 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001900 return Context.getPointerType(ToPointee);
1901 }
1902
1903 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001904 QualType QualifiedCanonToPointee
1905 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001907 if (isa<ObjCObjectPointerType>(ToType))
1908 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1909 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001910}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
Mike Stump11289f42009-09-09 15:08:12 +00001912static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001913 bool InOverloadResolution,
1914 ASTContext &Context) {
1915 // Handle value-dependent integral null pointer constants correctly.
1916 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1917 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001918 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001919 return !InOverloadResolution;
1920
Douglas Gregor56751b52009-09-25 04:25:58 +00001921 return Expr->isNullPointerConstant(Context,
1922 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1923 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001924}
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001926/// IsPointerConversion - Determines whether the conversion of the
1927/// expression From, which has the (possibly adjusted) type FromType,
1928/// can be converted to the type ToType via a pointer conversion (C++
1929/// 4.10). If so, returns true and places the converted type (that
1930/// might differ from ToType in its cv-qualifiers at some level) into
1931/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001932///
Douglas Gregora29dc052008-11-27 01:19:21 +00001933/// This routine also supports conversions to and from block pointers
1934/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1935/// pointers to interfaces. FIXME: Once we've determined the
1936/// appropriate overloading rules for Objective-C, we may want to
1937/// split the Objective-C checks into a different routine; however,
1938/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001939/// conversions, so for now they live here. IncompatibleObjC will be
1940/// set if the conversion is an allowed Objective-C conversion that
1941/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001943 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001944 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001945 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001946 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001947 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1948 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001949 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001950
Mike Stump11289f42009-09-09 15:08:12 +00001951 // Conversion from a null pointer constant to any Objective-C pointer type.
1952 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001953 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001954 ConvertedType = ToType;
1955 return true;
1956 }
1957
Douglas Gregor231d1c62008-11-27 00:15:41 +00001958 // Blocks: Block pointers can be converted to void*.
1959 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001960 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001961 ConvertedType = ToType;
1962 return true;
1963 }
1964 // Blocks: A null pointer constant can be converted to a block
1965 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001966 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001967 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001968 ConvertedType = ToType;
1969 return true;
1970 }
1971
Sebastian Redl576fd422009-05-10 18:38:11 +00001972 // If the left-hand-side is nullptr_t, the right side can be a null
1973 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001974 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001975 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001976 ConvertedType = ToType;
1977 return true;
1978 }
1979
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001980 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001981 if (!ToTypePtr)
1982 return false;
1983
1984 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001985 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001986 ConvertedType = ToType;
1987 return true;
1988 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001991 // , including objective-c pointers.
1992 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001993 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001994 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001995 ConvertedType = BuildSimilarlyQualifiedPointerType(
1996 FromType->getAs<ObjCObjectPointerType>(),
1997 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001998 ToType, Context);
1999 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002000 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002001 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002002 if (!FromTypePtr)
2003 return false;
2004
2005 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002006
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002008 // pointer conversion, so don't do all of the work below.
2009 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2010 return false;
2011
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012 // An rvalue of type "pointer to cv T," where T is an object type,
2013 // can be converted to an rvalue of type "pointer to cv void" (C++
2014 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002015 if (FromPointeeType->isIncompleteOrObjectType() &&
2016 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002018 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002019 ToType, Context,
2020 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002021 return true;
2022 }
2023
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002024 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002025 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002026 ToPointeeType->isVoidType()) {
2027 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2028 ToPointeeType,
2029 ToType, Context);
2030 return true;
2031 }
2032
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002033 // When we're overloading in C, we allow a special kind of pointer
2034 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002035 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002036 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002038 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002039 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002040 return true;
2041 }
2042
Douglas Gregor5c407d92008-10-23 00:40:37 +00002043 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002044 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002045 // An rvalue of type "pointer to cv D," where D is a class type,
2046 // can be converted to an rvalue of type "pointer to cv B," where
2047 // B is a base class (clause 10) of D. If B is an inaccessible
2048 // (clause 11) or ambiguous (10.2) base class of D, a program that
2049 // necessitates this conversion is ill-formed. The result of the
2050 // conversion is a pointer to the base class sub-object of the
2051 // derived class object. The null pointer value is converted to
2052 // the null pointer value of the destination type.
2053 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002054 // Note that we do not check for ambiguity or inaccessibility
2055 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002056 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002057 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002058 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002059 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002060 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002062 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002063 ToType, Context);
2064 return true;
2065 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002066
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002067 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2068 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2070 ToPointeeType,
2071 ToType, Context);
2072 return true;
2073 }
2074
Douglas Gregora119f102008-12-19 19:13:09 +00002075 return false;
2076}
Douglas Gregoraec25842011-04-26 23:16:46 +00002077
2078/// \brief Adopt the given qualifiers for the given type.
2079static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2080 Qualifiers TQs = T.getQualifiers();
2081
2082 // Check whether qualifiers already match.
2083 if (TQs == Qs)
2084 return T;
2085
2086 if (Qs.compatiblyIncludes(TQs))
2087 return Context.getQualifiedType(T, Qs);
2088
2089 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2090}
Douglas Gregora119f102008-12-19 19:13:09 +00002091
2092/// isObjCPointerConversion - Determines whether this is an
2093/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2094/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002095bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002096 QualType& ConvertedType,
2097 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002098 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002099 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
Douglas Gregoraec25842011-04-26 23:16:46 +00002101 // The set of qualifiers on the type we're converting from.
2102 Qualifiers FromQualifiers = FromType.getQualifiers();
2103
Steve Naroff7cae42b2009-07-10 23:34:53 +00002104 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002105 const ObjCObjectPointerType* ToObjCPtr =
2106 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002107 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002108 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002109
Steve Naroff7cae42b2009-07-10 23:34:53 +00002110 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002111 // If the pointee types are the same (ignoring qualifications),
2112 // then this is not a pointer conversion.
2113 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2114 FromObjCPtr->getPointeeType()))
2115 return false;
2116
Douglas Gregoraec25842011-04-26 23:16:46 +00002117 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002118 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002119 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002120 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002121 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002122 return true;
2123 }
2124 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002125 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002126 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002127 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002128 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002129 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002130 return true;
2131 }
2132 // Objective C++: We're able to convert from a pointer to an
2133 // interface to a pointer to a different interface.
2134 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002135 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2136 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002137 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002138 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2139 FromObjCPtr->getPointeeType()))
2140 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002142 ToObjCPtr->getPointeeType(),
2143 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002144 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002145 return true;
2146 }
2147
2148 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2149 // Okay: this is some kind of implicit downcast of Objective-C
2150 // interfaces, which is permitted. However, we're going to
2151 // complain about it.
2152 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002154 ToObjCPtr->getPointeeType(),
2155 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002156 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002157 return true;
2158 }
Mike Stump11289f42009-09-09 15:08:12 +00002159 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002160 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002161 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002162 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002163 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002165 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002166 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002167 // to a block pointer type.
2168 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002169 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002170 return true;
2171 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002172 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002174 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002175 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002177 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002178 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002179 return true;
2180 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002181 else
Douglas Gregora119f102008-12-19 19:13:09 +00002182 return false;
2183
Douglas Gregor033f56d2008-12-23 00:53:59 +00002184 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002185 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002187 else if (const BlockPointerType *FromBlockPtr =
2188 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002189 FromPointeeType = FromBlockPtr->getPointeeType();
2190 else
Douglas Gregora119f102008-12-19 19:13:09 +00002191 return false;
2192
Douglas Gregora119f102008-12-19 19:13:09 +00002193 // If we have pointers to pointers, recursively check whether this
2194 // is an Objective-C conversion.
2195 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2196 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2197 IncompatibleObjC)) {
2198 // We always complain about this conversion.
2199 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002200 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002201 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002202 return true;
2203 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002204 // Allow conversion of pointee being objective-c pointer to another one;
2205 // as in I* to id.
2206 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2207 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2208 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2209 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002210
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002211 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002213 return true;
2214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002215
Douglas Gregor033f56d2008-12-23 00:53:59 +00002216 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002217 // differences in the argument and result types are in Objective-C
2218 // pointer conversions. If so, we permit the conversion (but
2219 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002220 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002221 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002222 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002223 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002224 if (FromFunctionType && ToFunctionType) {
2225 // If the function types are exactly the same, this isn't an
2226 // Objective-C pointer conversion.
2227 if (Context.getCanonicalType(FromPointeeType)
2228 == Context.getCanonicalType(ToPointeeType))
2229 return false;
2230
2231 // Perform the quick checks that will tell us whether these
2232 // function types are obviously different.
2233 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2234 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2235 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2236 return false;
2237
2238 bool HasObjCConversion = false;
2239 if (Context.getCanonicalType(FromFunctionType->getResultType())
2240 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2241 // Okay, the types match exactly. Nothing to do.
2242 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2243 ToFunctionType->getResultType(),
2244 ConvertedType, IncompatibleObjC)) {
2245 // Okay, we have an Objective-C pointer conversion.
2246 HasObjCConversion = true;
2247 } else {
2248 // Function types are too different. Abort.
2249 return false;
2250 }
Mike Stump11289f42009-09-09 15:08:12 +00002251
Douglas Gregora119f102008-12-19 19:13:09 +00002252 // Check argument types.
2253 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2254 ArgIdx != NumArgs; ++ArgIdx) {
2255 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2256 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2257 if (Context.getCanonicalType(FromArgType)
2258 == Context.getCanonicalType(ToArgType)) {
2259 // Okay, the types match exactly. Nothing to do.
2260 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2261 ConvertedType, IncompatibleObjC)) {
2262 // Okay, we have an Objective-C pointer conversion.
2263 HasObjCConversion = true;
2264 } else {
2265 // Argument types are too different. Abort.
2266 return false;
2267 }
2268 }
2269
2270 if (HasObjCConversion) {
2271 // We had an Objective-C conversion. Allow this pointer
2272 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002273 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002274 IncompatibleObjC = true;
2275 return true;
2276 }
2277 }
2278
Sebastian Redl72b597d2009-01-25 19:43:20 +00002279 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002280}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281
John McCall31168b02011-06-15 23:02:42 +00002282/// \brief Determine whether this is an Objective-C writeback conversion,
2283/// used for parameter passing when performing automatic reference counting.
2284///
2285/// \param FromType The type we're converting form.
2286///
2287/// \param ToType The type we're converting to.
2288///
2289/// \param ConvertedType The type that will be produced after applying
2290/// this conversion.
2291bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2292 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002293 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002294 Context.hasSameUnqualifiedType(FromType, ToType))
2295 return false;
2296
2297 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2298 QualType ToPointee;
2299 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2300 ToPointee = ToPointer->getPointeeType();
2301 else
2302 return false;
2303
2304 Qualifiers ToQuals = ToPointee.getQualifiers();
2305 if (!ToPointee->isObjCLifetimeType() ||
2306 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002307 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002308 return false;
2309
2310 // Argument must be a pointer to __strong to __weak.
2311 QualType FromPointee;
2312 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2313 FromPointee = FromPointer->getPointeeType();
2314 else
2315 return false;
2316
2317 Qualifiers FromQuals = FromPointee.getQualifiers();
2318 if (!FromPointee->isObjCLifetimeType() ||
2319 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2320 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2321 return false;
2322
2323 // Make sure that we have compatible qualifiers.
2324 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2325 if (!ToQuals.compatiblyIncludes(FromQuals))
2326 return false;
2327
2328 // Remove qualifiers from the pointee type we're converting from; they
2329 // aren't used in the compatibility check belong, and we'll be adding back
2330 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2331 FromPointee = FromPointee.getUnqualifiedType();
2332
2333 // The unqualified form of the pointee types must be compatible.
2334 ToPointee = ToPointee.getUnqualifiedType();
2335 bool IncompatibleObjC;
2336 if (Context.typesAreCompatible(FromPointee, ToPointee))
2337 FromPointee = ToPointee;
2338 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2339 IncompatibleObjC))
2340 return false;
2341
2342 /// \brief Construct the type we're converting to, which is a pointer to
2343 /// __autoreleasing pointee.
2344 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2345 ConvertedType = Context.getPointerType(FromPointee);
2346 return true;
2347}
2348
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002349bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2350 QualType& ConvertedType) {
2351 QualType ToPointeeType;
2352 if (const BlockPointerType *ToBlockPtr =
2353 ToType->getAs<BlockPointerType>())
2354 ToPointeeType = ToBlockPtr->getPointeeType();
2355 else
2356 return false;
2357
2358 QualType FromPointeeType;
2359 if (const BlockPointerType *FromBlockPtr =
2360 FromType->getAs<BlockPointerType>())
2361 FromPointeeType = FromBlockPtr->getPointeeType();
2362 else
2363 return false;
2364 // We have pointer to blocks, check whether the only
2365 // differences in the argument and result types are in Objective-C
2366 // pointer conversions. If so, we permit the conversion.
2367
2368 const FunctionProtoType *FromFunctionType
2369 = FromPointeeType->getAs<FunctionProtoType>();
2370 const FunctionProtoType *ToFunctionType
2371 = ToPointeeType->getAs<FunctionProtoType>();
2372
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002373 if (!FromFunctionType || !ToFunctionType)
2374 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002375
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002376 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002377 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002378
2379 // Perform the quick checks that will tell us whether these
2380 // function types are obviously different.
2381 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2382 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2383 return false;
2384
2385 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2386 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2387 if (FromEInfo != ToEInfo)
2388 return false;
2389
2390 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002391 if (Context.hasSameType(FromFunctionType->getResultType(),
2392 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002393 // Okay, the types match exactly. Nothing to do.
2394 } else {
2395 QualType RHS = FromFunctionType->getResultType();
2396 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002397 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002398 !RHS.hasQualifiers() && LHS.hasQualifiers())
2399 LHS = LHS.getUnqualifiedType();
2400
2401 if (Context.hasSameType(RHS,LHS)) {
2402 // OK exact match.
2403 } else if (isObjCPointerConversion(RHS, LHS,
2404 ConvertedType, IncompatibleObjC)) {
2405 if (IncompatibleObjC)
2406 return false;
2407 // Okay, we have an Objective-C pointer conversion.
2408 }
2409 else
2410 return false;
2411 }
2412
2413 // Check argument types.
2414 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2415 ArgIdx != NumArgs; ++ArgIdx) {
2416 IncompatibleObjC = false;
2417 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2418 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2419 if (Context.hasSameType(FromArgType, ToArgType)) {
2420 // Okay, the types match exactly. Nothing to do.
2421 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2422 ConvertedType, IncompatibleObjC)) {
2423 if (IncompatibleObjC)
2424 return false;
2425 // Okay, we have an Objective-C pointer conversion.
2426 } else
2427 // Argument types are too different. Abort.
2428 return false;
2429 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002430 if (LangOpts.ObjCAutoRefCount &&
2431 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2432 ToFunctionType))
2433 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002434
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002435 ConvertedType = ToType;
2436 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002437}
2438
Richard Trieucaff2472011-11-23 22:32:32 +00002439enum {
2440 ft_default,
2441 ft_different_class,
2442 ft_parameter_arity,
2443 ft_parameter_mismatch,
2444 ft_return_type,
2445 ft_qualifer_mismatch
2446};
2447
2448/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2449/// function types. Catches different number of parameter, mismatch in
2450/// parameter types, and different return types.
2451void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2452 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002453 // If either type is not valid, include no extra info.
2454 if (FromType.isNull() || ToType.isNull()) {
2455 PDiag << ft_default;
2456 return;
2457 }
2458
Richard Trieucaff2472011-11-23 22:32:32 +00002459 // Get the function type from the pointers.
2460 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2461 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2462 *ToMember = ToType->getAs<MemberPointerType>();
2463 if (FromMember->getClass() != ToMember->getClass()) {
2464 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2465 << QualType(FromMember->getClass(), 0);
2466 return;
2467 }
2468 FromType = FromMember->getPointeeType();
2469 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002470 }
2471
Richard Trieu96ed5b62011-12-13 23:19:45 +00002472 if (FromType->isPointerType())
2473 FromType = FromType->getPointeeType();
2474 if (ToType->isPointerType())
2475 ToType = ToType->getPointeeType();
2476
2477 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002478 FromType = FromType.getNonReferenceType();
2479 ToType = ToType.getNonReferenceType();
2480
Richard Trieucaff2472011-11-23 22:32:32 +00002481 // Don't print extra info for non-specialized template functions.
2482 if (FromType->isInstantiationDependentType() &&
2483 !FromType->getAs<TemplateSpecializationType>()) {
2484 PDiag << ft_default;
2485 return;
2486 }
2487
Richard Trieu96ed5b62011-12-13 23:19:45 +00002488 // No extra info for same types.
2489 if (Context.hasSameType(FromType, ToType)) {
2490 PDiag << ft_default;
2491 return;
2492 }
2493
Richard Trieucaff2472011-11-23 22:32:32 +00002494 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2495 *ToFunction = ToType->getAs<FunctionProtoType>();
2496
2497 // Both types need to be function types.
2498 if (!FromFunction || !ToFunction) {
2499 PDiag << ft_default;
2500 return;
2501 }
2502
2503 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2504 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2505 << FromFunction->getNumArgs();
2506 return;
2507 }
2508
2509 // Handle different parameter types.
2510 unsigned ArgPos;
2511 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2512 PDiag << ft_parameter_mismatch << ArgPos + 1
2513 << ToFunction->getArgType(ArgPos)
2514 << FromFunction->getArgType(ArgPos);
2515 return;
2516 }
2517
2518 // Handle different return type.
2519 if (!Context.hasSameType(FromFunction->getResultType(),
2520 ToFunction->getResultType())) {
2521 PDiag << ft_return_type << ToFunction->getResultType()
2522 << FromFunction->getResultType();
2523 return;
2524 }
2525
2526 unsigned FromQuals = FromFunction->getTypeQuals(),
2527 ToQuals = ToFunction->getTypeQuals();
2528 if (FromQuals != ToQuals) {
2529 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2530 return;
2531 }
2532
2533 // Unable to find a difference, so add no extra info.
2534 PDiag << ft_default;
2535}
2536
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002537/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002538/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002539/// they have same number of arguments. This routine assumes that Objective-C
2540/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002541/// If the parameters are different, ArgPos will have the parameter index
Richard Trieucaff2472011-11-23 22:32:32 +00002542/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002543bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002544 const FunctionProtoType *NewType,
2545 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002546 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002547 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2548 N = NewType->arg_type_begin(),
2549 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2550 if (!Context.hasSameType(*O, *N)) {
2551 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2552 return false;
2553 }
2554 }
2555 return true;
2556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002558 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2559 N = NewType->arg_type_begin(),
2560 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2561 QualType ToType = (*O);
2562 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002563 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002564 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2565 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002566 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2567 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2568 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2569 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002570 continue;
2571 }
John McCall8b07ec22010-05-15 11:32:37 +00002572 else if (const ObjCObjectPointerType *PTTo =
2573 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002575 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002576 if (Context.hasSameUnqualifiedType(
2577 PTTo->getObjectType()->getBaseType(),
2578 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002579 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002580 }
Richard Trieucaff2472011-11-23 22:32:32 +00002581 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002583 }
2584 }
2585 return true;
2586}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002587
Douglas Gregor39c16d42008-10-24 04:54:22 +00002588/// CheckPointerConversion - Check the pointer conversion from the
2589/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002590/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002591/// conversions for which IsPointerConversion has already returned
2592/// true. It returns true and produces a diagnostic if there was an
2593/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002594bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002595 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002596 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002597 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002598 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002599 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002600
John McCall8cb679e2010-11-15 09:13:47 +00002601 Kind = CK_BitCast;
2602
David Blaikie1c7c8f72012-08-08 17:33:31 +00002603 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2604 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2605 Expr::NPCK_ZeroExpression) {
2606 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2607 DiagRuntimeBehavior(From->getExprLoc(), From,
2608 PDiag(diag::warn_impcast_bool_to_null_pointer)
2609 << ToType << From->getSourceRange());
2610 else if (!isUnevaluatedContext())
2611 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2612 << ToType << From->getSourceRange();
2613 }
John McCall9320b872011-09-09 05:25:32 +00002614 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2615 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002616 QualType FromPointeeType = FromPtrType->getPointeeType(),
2617 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002618
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002619 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2620 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002621 // We must have a derived-to-base conversion. Check an
2622 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002623 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2624 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002625 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002626 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002627 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002628
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002629 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002630 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002631 }
2632 }
John McCall9320b872011-09-09 05:25:32 +00002633 } else if (const ObjCObjectPointerType *ToPtrType =
2634 ToType->getAs<ObjCObjectPointerType>()) {
2635 if (const ObjCObjectPointerType *FromPtrType =
2636 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002637 // Objective-C++ conversions are always okay.
2638 // FIXME: We should have a different class of conversions for the
2639 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002640 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002641 return false;
John McCall9320b872011-09-09 05:25:32 +00002642 } else if (FromType->isBlockPointerType()) {
2643 Kind = CK_BlockPointerToObjCPointerCast;
2644 } else {
2645 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002646 }
John McCall9320b872011-09-09 05:25:32 +00002647 } else if (ToType->isBlockPointerType()) {
2648 if (!FromType->isBlockPointerType())
2649 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002650 }
John McCall8cb679e2010-11-15 09:13:47 +00002651
2652 // We shouldn't fall into this case unless it's valid for other
2653 // reasons.
2654 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2655 Kind = CK_NullToPointer;
2656
Douglas Gregor39c16d42008-10-24 04:54:22 +00002657 return false;
2658}
2659
Sebastian Redl72b597d2009-01-25 19:43:20 +00002660/// IsMemberPointerConversion - Determines whether the conversion of the
2661/// expression From, which has the (possibly adjusted) type FromType, can be
2662/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2663/// If so, returns true and places the converted type (that might differ from
2664/// ToType in its cv-qualifiers at some level) into ConvertedType.
2665bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002666 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002667 bool InOverloadResolution,
2668 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002669 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002670 if (!ToTypePtr)
2671 return false;
2672
2673 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002674 if (From->isNullPointerConstant(Context,
2675 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2676 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677 ConvertedType = ToType;
2678 return true;
2679 }
2680
2681 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002682 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002683 if (!FromTypePtr)
2684 return false;
2685
2686 // A pointer to member of B can be converted to a pointer to member of D,
2687 // where D is derived from B (C++ 4.11p2).
2688 QualType FromClass(FromTypePtr->getClass(), 0);
2689 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002690
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002691 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002692 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002693 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2695 ToClass.getTypePtr());
2696 return true;
2697 }
2698
2699 return false;
2700}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701
Sebastian Redl72b597d2009-01-25 19:43:20 +00002702/// CheckMemberPointerConversion - Check the member pointer conversion from the
2703/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002704/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002705/// for which IsMemberPointerConversion has already returned true. It returns
2706/// true and produces a diagnostic if there was an error, or returns false
2707/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002708bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002709 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002710 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002711 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002712 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002713 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002714 if (!FromPtrType) {
2715 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002717 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002718 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002719 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002720 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002721 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002722
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002723 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002724 assert(ToPtrType && "No member pointer cast has a target type "
2725 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726
Sebastian Redled8f2002009-01-28 18:33:18 +00002727 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2728 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002729
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 // FIXME: What about dependent types?
2731 assert(FromClass->isRecordType() && "Pointer into non-class.");
2732 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002733
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002735 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002736 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2737 assert(DerivationOkay &&
2738 "Should not have been called if derivation isn't OK.");
2739 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002740
Sebastian Redled8f2002009-01-28 18:33:18 +00002741 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2742 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002743 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2744 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2745 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2746 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002747 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002748
Douglas Gregor89ee6822009-02-28 01:32:25 +00002749 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002750 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2751 << FromClass << ToClass << QualType(VBase, 0)
2752 << From->getSourceRange();
2753 return true;
2754 }
2755
John McCall5b0829a2010-02-10 09:31:12 +00002756 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002757 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2758 Paths.front(),
2759 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002760
Anders Carlssond7923c62009-08-22 23:33:40 +00002761 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002762 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002763 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002764 return false;
2765}
2766
Douglas Gregor9a657932008-10-21 23:43:52 +00002767/// IsQualificationConversion - Determines whether the conversion from
2768/// an rvalue of type FromType to ToType is a qualification conversion
2769/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002770///
2771/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2772/// when the qualification conversion involves a change in the Objective-C
2773/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002774bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002776 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002777 FromType = Context.getCanonicalType(FromType);
2778 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002779 ObjCLifetimeConversion = false;
2780
Douglas Gregor9a657932008-10-21 23:43:52 +00002781 // If FromType and ToType are the same type, this is not a
2782 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002783 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002784 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002785
Douglas Gregor9a657932008-10-21 23:43:52 +00002786 // (C++ 4.4p4):
2787 // A conversion can add cv-qualifiers at levels other than the first
2788 // in multi-level pointers, subject to the following rules: [...]
2789 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002791 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002792 // Within each iteration of the loop, we check the qualifiers to
2793 // determine if this still looks like a qualification
2794 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002795 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 // until there are no more pointers or pointers-to-members left to
2797 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002798 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002799
Douglas Gregor90609aa2011-04-25 18:40:17 +00002800 Qualifiers FromQuals = FromType.getQualifiers();
2801 Qualifiers ToQuals = ToType.getQualifiers();
2802
John McCall31168b02011-06-15 23:02:42 +00002803 // Objective-C ARC:
2804 // Check Objective-C lifetime conversions.
2805 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2806 UnwrappedAnyPointer) {
2807 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2808 ObjCLifetimeConversion = true;
2809 FromQuals.removeObjCLifetime();
2810 ToQuals.removeObjCLifetime();
2811 } else {
2812 // Qualification conversions cannot cast between different
2813 // Objective-C lifetime qualifiers.
2814 return false;
2815 }
2816 }
2817
Douglas Gregorf30053d2011-05-08 06:09:53 +00002818 // Allow addition/removal of GC attributes but not changing GC attributes.
2819 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2820 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2821 FromQuals.removeObjCGCAttr();
2822 ToQuals.removeObjCGCAttr();
2823 }
2824
Douglas Gregor9a657932008-10-21 23:43:52 +00002825 // -- for every j > 0, if const is in cv 1,j then const is in cv
2826 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002827 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002828 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002829
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 // -- if the cv 1,j and cv 2,j are different, then const is in
2831 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002832 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002833 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002834 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002835
Douglas Gregor9a657932008-10-21 23:43:52 +00002836 // Keep track of whether all prior cv-qualifiers in the "to" type
2837 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002838 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002839 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002840 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002841
2842 // We are left with FromType and ToType being the pointee types
2843 // after unwrapping the original FromType and ToType the same number
2844 // of types. If we unwrapped any pointers, and if FromType and
2845 // ToType have the same unqualified type (since we checked
2846 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002847 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002848}
2849
Douglas Gregorc79862f2012-04-12 17:51:55 +00002850/// \brief - Determine whether this is a conversion from a scalar type to an
2851/// atomic type.
2852///
2853/// If successful, updates \c SCS's second and third steps in the conversion
2854/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002855static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2856 bool InOverloadResolution,
2857 StandardConversionSequence &SCS,
2858 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002859 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2860 if (!ToAtomic)
2861 return false;
2862
2863 StandardConversionSequence InnerSCS;
2864 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2865 InOverloadResolution, InnerSCS,
2866 CStyle, /*AllowObjCWritebackConversion=*/false))
2867 return false;
2868
2869 SCS.Second = InnerSCS.Second;
2870 SCS.setToType(1, InnerSCS.getToType(1));
2871 SCS.Third = InnerSCS.Third;
2872 SCS.QualificationIncludesObjCLifetime
2873 = InnerSCS.QualificationIncludesObjCLifetime;
2874 SCS.setToType(2, InnerSCS.getToType(2));
2875 return true;
2876}
2877
Sebastian Redle5417162012-03-27 18:33:03 +00002878static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2879 CXXConstructorDecl *Constructor,
2880 QualType Type) {
2881 const FunctionProtoType *CtorType =
2882 Constructor->getType()->getAs<FunctionProtoType>();
2883 if (CtorType->getNumArgs() > 0) {
2884 QualType FirstArg = CtorType->getArgType(0);
2885 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2886 return true;
2887 }
2888 return false;
2889}
2890
Sebastian Redl82ace982012-02-11 23:51:08 +00002891static OverloadingResult
2892IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2893 CXXRecordDecl *To,
2894 UserDefinedConversionSequence &User,
2895 OverloadCandidateSet &CandidateSet,
2896 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002897 DeclContext::lookup_result R = S.LookupConstructors(To);
2898 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002899 Con != ConEnd; ++Con) {
2900 NamedDecl *D = *Con;
2901 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2902
2903 // Find the constructor (which may be a template).
2904 CXXConstructorDecl *Constructor = 0;
2905 FunctionTemplateDecl *ConstructorTmpl
2906 = dyn_cast<FunctionTemplateDecl>(D);
2907 if (ConstructorTmpl)
2908 Constructor
2909 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2910 else
2911 Constructor = cast<CXXConstructorDecl>(D);
2912
2913 bool Usable = !Constructor->isInvalidDecl() &&
2914 S.isInitListConstructor(Constructor) &&
2915 (AllowExplicit || !Constructor->isExplicit());
2916 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002917 // If the first argument is (a reference to) the target type,
2918 // suppress conversions.
2919 bool SuppressUserConversions =
2920 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002921 if (ConstructorTmpl)
2922 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2923 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002924 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002925 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002926 else
2927 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002928 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002929 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002930 }
2931 }
2932
2933 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2934
2935 OverloadCandidateSet::iterator Best;
2936 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2937 case OR_Success: {
2938 // Record the standard conversion we used and the conversion function.
2939 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002940 QualType ThisType = Constructor->getThisType(S.Context);
2941 // Initializer lists don't have conversions as such.
2942 User.Before.setAsIdentityConversion();
2943 User.HadMultipleCandidates = HadMultipleCandidates;
2944 User.ConversionFunction = Constructor;
2945 User.FoundConversionFunction = Best->FoundDecl;
2946 User.After.setAsIdentityConversion();
2947 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2948 User.After.setAllToTypes(ToType);
2949 return OR_Success;
2950 }
2951
2952 case OR_No_Viable_Function:
2953 return OR_No_Viable_Function;
2954 case OR_Deleted:
2955 return OR_Deleted;
2956 case OR_Ambiguous:
2957 return OR_Ambiguous;
2958 }
2959
2960 llvm_unreachable("Invalid OverloadResult!");
2961}
2962
Douglas Gregor576e98c2009-01-30 23:27:23 +00002963/// Determines whether there is a user-defined conversion sequence
2964/// (C++ [over.ics.user]) that converts expression From to the type
2965/// ToType. If such a conversion exists, User will contain the
2966/// user-defined conversion sequence that performs such a conversion
2967/// and this routine will return true. Otherwise, this routine returns
2968/// false and User is unspecified.
2969///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002970/// \param AllowExplicit true if the conversion should consider C++0x
2971/// "explicit" conversion functions as well as non-explicit conversion
2972/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002973static OverloadingResult
2974IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002975 UserDefinedConversionSequence &User,
2976 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002977 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002978 // Whether we will only visit constructors.
2979 bool ConstructorsOnly = false;
2980
2981 // If the type we are conversion to is a class type, enumerate its
2982 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002983 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002984 // C++ [over.match.ctor]p1:
2985 // When objects of class type are direct-initialized (8.5), or
2986 // copy-initialized from an expression of the same or a
2987 // derived class type (8.5), overload resolution selects the
2988 // constructor. [...] For copy-initialization, the candidate
2989 // functions are all the converting constructors (12.3.1) of
2990 // that class. The argument list is the expression-list within
2991 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002992 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002993 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002994 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002995 ConstructorsOnly = true;
2996
Benjamin Kramer90633e32012-11-23 17:04:52 +00002997 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002998 // RequireCompleteType may have returned true due to some invalid decl
2999 // during template instantiation, but ToType may be complete enough now
3000 // to try to recover.
3001 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003002 // We're not going to find any constructors.
3003 } else if (CXXRecordDecl *ToRecordDecl
3004 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003005
3006 Expr **Args = &From;
3007 unsigned NumArgs = 1;
3008 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003009 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00003010 // But first, see if there is an init-list-contructor that will work.
3011 OverloadingResult Result = IsInitializerListConstructorConversion(
3012 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3013 if (Result != OR_No_Viable_Function)
3014 return Result;
3015 // Never mind.
3016 CandidateSet.clear();
3017
3018 // If we're list-initializing, we pass the individual elements as
3019 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003020 Args = InitList->getInits();
3021 NumArgs = InitList->getNumInits();
3022 ListInitializing = true;
3023 }
3024
David Blaikieff7d47a2012-12-19 00:45:41 +00003025 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3026 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003027 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003028 NamedDecl *D = *Con;
3029 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3030
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003031 // Find the constructor (which may be a template).
3032 CXXConstructorDecl *Constructor = 0;
3033 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003034 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003035 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003036 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003037 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3038 else
John McCalla0296f72010-03-19 07:35:19 +00003039 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003041 bool Usable = !Constructor->isInvalidDecl();
3042 if (ListInitializing)
3043 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3044 else
3045 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3046 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003047 bool SuppressUserConversions = !ConstructorsOnly;
3048 if (SuppressUserConversions && ListInitializing) {
3049 SuppressUserConversions = false;
3050 if (NumArgs == 1) {
3051 // If the first argument is (a reference to) the target type,
3052 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003053 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3054 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003055 }
3056 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003057 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003058 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3059 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003060 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003061 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003062 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003063 // Allow one user-defined conversion when user specifies a
3064 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003065 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003066 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003067 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003068 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003069 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003070 }
3071 }
3072
Douglas Gregor5ab11652010-04-17 22:01:05 +00003073 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003074 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003075 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003076 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003077 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003078 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003079 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003080 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3081 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003082 std::pair<CXXRecordDecl::conversion_iterator,
3083 CXXRecordDecl::conversion_iterator>
3084 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3085 for (CXXRecordDecl::conversion_iterator
3086 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003087 DeclAccessPair FoundDecl = I.getPair();
3088 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003089 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3090 if (isa<UsingShadowDecl>(D))
3091 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3092
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003093 CXXConversionDecl *Conv;
3094 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003095 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3096 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003097 else
John McCallda4458e2010-03-31 01:36:47 +00003098 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003099
3100 if (AllowExplicit || !Conv->isExplicit()) {
3101 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003102 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3103 ActingContext, From, ToType,
3104 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003105 else
John McCall5c32be02010-08-24 20:38:10 +00003106 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3107 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003108 }
3109 }
3110 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003111 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003112
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003113 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3114
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003115 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003116 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003117 case OR_Success:
3118 // Record the standard conversion we used and the conversion function.
3119 if (CXXConstructorDecl *Constructor
3120 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3121 // C++ [over.ics.user]p1:
3122 // If the user-defined conversion is specified by a
3123 // constructor (12.3.1), the initial standard conversion
3124 // sequence converts the source type to the type required by
3125 // the argument of the constructor.
3126 //
3127 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003128 if (isa<InitListExpr>(From)) {
3129 // Initializer lists don't have conversions as such.
3130 User.Before.setAsIdentityConversion();
3131 } else {
3132 if (Best->Conversions[0].isEllipsis())
3133 User.EllipsisConversion = true;
3134 else {
3135 User.Before = Best->Conversions[0].Standard;
3136 User.EllipsisConversion = false;
3137 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003138 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003139 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003140 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003141 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003142 User.After.setAsIdentityConversion();
3143 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3144 User.After.setAllToTypes(ToType);
3145 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003146 }
3147 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003148 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3149 // C++ [over.ics.user]p1:
3150 //
3151 // [...] If the user-defined conversion is specified by a
3152 // conversion function (12.3.2), the initial standard
3153 // conversion sequence converts the source type to the
3154 // implicit object parameter of the conversion function.
3155 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003156 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003157 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003158 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003159 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003160
John McCall5c32be02010-08-24 20:38:10 +00003161 // C++ [over.ics.user]p2:
3162 // The second standard conversion sequence converts the
3163 // result of the user-defined conversion to the target type
3164 // for the sequence. Since an implicit conversion sequence
3165 // is an initialization, the special rules for
3166 // initialization by user-defined conversion apply when
3167 // selecting the best user-defined conversion for a
3168 // user-defined conversion sequence (see 13.3.3 and
3169 // 13.3.3.1).
3170 User.After = Best->FinalConversion;
3171 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003172 }
David Blaikie8a40f702012-01-17 06:56:22 +00003173 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003174
John McCall5c32be02010-08-24 20:38:10 +00003175 case OR_No_Viable_Function:
3176 return OR_No_Viable_Function;
3177 case OR_Deleted:
3178 // No conversion here! We're done.
3179 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
John McCall5c32be02010-08-24 20:38:10 +00003181 case OR_Ambiguous:
3182 return OR_Ambiguous;
3183 }
3184
David Blaikie8a40f702012-01-17 06:56:22 +00003185 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003186}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003188bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003189Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003190 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003191 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003193 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003194 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003195 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003196 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003197 diag::err_typecheck_ambiguous_condition)
3198 << From->getType() << ToType << From->getSourceRange();
3199 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003200 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003201 diag::err_typecheck_nonviable_condition)
3202 << From->getType() << ToType << From->getSourceRange();
3203 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003204 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003205 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003207}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003208
Douglas Gregor2837aa22012-02-22 17:32:19 +00003209/// \brief Compare the user-defined conversion functions or constructors
3210/// of two user-defined conversion sequences to determine whether any ordering
3211/// is possible.
3212static ImplicitConversionSequence::CompareKind
3213compareConversionFunctions(Sema &S,
3214 FunctionDecl *Function1,
3215 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003216 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003217 return ImplicitConversionSequence::Indistinguishable;
3218
3219 // Objective-C++:
3220 // If both conversion functions are implicitly-declared conversions from
3221 // a lambda closure type to a function pointer and a block pointer,
3222 // respectively, always prefer the conversion to a function pointer,
3223 // because the function pointer is more lightweight and is more likely
3224 // to keep code working.
3225 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3226 if (!Conv1)
3227 return ImplicitConversionSequence::Indistinguishable;
3228
3229 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3230 if (!Conv2)
3231 return ImplicitConversionSequence::Indistinguishable;
3232
3233 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3234 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3235 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3236 if (Block1 != Block2)
3237 return Block1? ImplicitConversionSequence::Worse
3238 : ImplicitConversionSequence::Better;
3239 }
3240
3241 return ImplicitConversionSequence::Indistinguishable;
3242}
3243
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003244/// CompareImplicitConversionSequences - Compare two implicit
3245/// conversion sequences to determine whether one is better than the
3246/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003247static ImplicitConversionSequence::CompareKind
3248CompareImplicitConversionSequences(Sema &S,
3249 const ImplicitConversionSequence& ICS1,
3250 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003251{
3252 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3253 // conversion sequences (as defined in 13.3.3.1)
3254 // -- a standard conversion sequence (13.3.3.1.1) is a better
3255 // conversion sequence than a user-defined conversion sequence or
3256 // an ellipsis conversion sequence, and
3257 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3258 // conversion sequence than an ellipsis conversion sequence
3259 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003260 //
John McCall0d1da222010-01-12 00:44:57 +00003261 // C++0x [over.best.ics]p10:
3262 // For the purpose of ranking implicit conversion sequences as
3263 // described in 13.3.3.2, the ambiguous conversion sequence is
3264 // treated as a user-defined sequence that is indistinguishable
3265 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003266 if (ICS1.getKindRank() < ICS2.getKindRank())
3267 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003268 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003269 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003270
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003271 // The following checks require both conversion sequences to be of
3272 // the same kind.
3273 if (ICS1.getKind() != ICS2.getKind())
3274 return ImplicitConversionSequence::Indistinguishable;
3275
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003276 ImplicitConversionSequence::CompareKind Result =
3277 ImplicitConversionSequence::Indistinguishable;
3278
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003279 // Two implicit conversion sequences of the same form are
3280 // indistinguishable conversion sequences unless one of the
3281 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003282 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003283 Result = CompareStandardConversionSequences(S,
3284 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003285 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003286 // User-defined conversion sequence U1 is a better conversion
3287 // sequence than another user-defined conversion sequence U2 if
3288 // they contain the same user-defined conversion function or
3289 // constructor and if the second standard conversion sequence of
3290 // U1 is better than the second standard conversion sequence of
3291 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003292 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003293 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003294 Result = CompareStandardConversionSequences(S,
3295 ICS1.UserDefined.After,
3296 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003297 else
3298 Result = compareConversionFunctions(S,
3299 ICS1.UserDefined.ConversionFunction,
3300 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003301 }
3302
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003303 // List-initialization sequence L1 is a better conversion sequence than
3304 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3305 // for some X and L2 does not.
3306 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003307 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003308 ICS1.isListInitializationSequence() &&
3309 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003310 if (ICS1.isStdInitializerListElement() &&
3311 !ICS2.isStdInitializerListElement())
3312 return ImplicitConversionSequence::Better;
3313 if (!ICS1.isStdInitializerListElement() &&
3314 ICS2.isStdInitializerListElement())
3315 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003316 }
3317
3318 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003319}
3320
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003321static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3322 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3323 Qualifiers Quals;
3324 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003328 return Context.hasSameUnqualifiedType(T1, T2);
3329}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003331// Per 13.3.3.2p3, compare the given standard conversion sequences to
3332// determine if one is a proper subset of the other.
3333static ImplicitConversionSequence::CompareKind
3334compareStandardConversionSubsets(ASTContext &Context,
3335 const StandardConversionSequence& SCS1,
3336 const StandardConversionSequence& SCS2) {
3337 ImplicitConversionSequence::CompareKind Result
3338 = ImplicitConversionSequence::Indistinguishable;
3339
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003341 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003342 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3343 return ImplicitConversionSequence::Better;
3344 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3345 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003347 if (SCS1.Second != SCS2.Second) {
3348 if (SCS1.Second == ICK_Identity)
3349 Result = ImplicitConversionSequence::Better;
3350 else if (SCS2.Second == ICK_Identity)
3351 Result = ImplicitConversionSequence::Worse;
3352 else
3353 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003354 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003355 return ImplicitConversionSequence::Indistinguishable;
3356
3357 if (SCS1.Third == SCS2.Third) {
3358 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3359 : ImplicitConversionSequence::Indistinguishable;
3360 }
3361
3362 if (SCS1.Third == ICK_Identity)
3363 return Result == ImplicitConversionSequence::Worse
3364 ? ImplicitConversionSequence::Indistinguishable
3365 : ImplicitConversionSequence::Better;
3366
3367 if (SCS2.Third == ICK_Identity)
3368 return Result == ImplicitConversionSequence::Better
3369 ? ImplicitConversionSequence::Indistinguishable
3370 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003372 return ImplicitConversionSequence::Indistinguishable;
3373}
3374
Douglas Gregore696ebb2011-01-26 14:52:12 +00003375/// \brief Determine whether one of the given reference bindings is better
3376/// than the other based on what kind of bindings they are.
3377static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3378 const StandardConversionSequence &SCS2) {
3379 // C++0x [over.ics.rank]p3b4:
3380 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3381 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003383 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003385 // reference*.
3386 //
3387 // FIXME: Rvalue references. We're going rogue with the above edits,
3388 // because the semantics in the current C++0x working paper (N3225 at the
3389 // time of this writing) break the standard definition of std::forward
3390 // and std::reference_wrapper when dealing with references to functions.
3391 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003392 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3393 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3394 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Douglas Gregore696ebb2011-01-26 14:52:12 +00003396 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3397 SCS2.IsLvalueReference) ||
3398 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3399 !SCS2.IsLvalueReference);
3400}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402/// CompareStandardConversionSequences - Compare two standard
3403/// conversion sequences to determine whether one is better than the
3404/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003405static ImplicitConversionSequence::CompareKind
3406CompareStandardConversionSequences(Sema &S,
3407 const StandardConversionSequence& SCS1,
3408 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003409{
3410 // Standard conversion sequence S1 is a better conversion sequence
3411 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3412
3413 // -- S1 is a proper subsequence of S2 (comparing the conversion
3414 // sequences in the canonical form defined by 13.3.3.1.1,
3415 // excluding any Lvalue Transformation; the identity conversion
3416 // sequence is considered to be a subsequence of any
3417 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003418 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003419 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003421
3422 // -- the rank of S1 is better than the rank of S2 (by the rules
3423 // defined below), or, if not that,
3424 ImplicitConversionRank Rank1 = SCS1.getRank();
3425 ImplicitConversionRank Rank2 = SCS2.getRank();
3426 if (Rank1 < Rank2)
3427 return ImplicitConversionSequence::Better;
3428 else if (Rank2 < Rank1)
3429 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003430
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003431 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3432 // are indistinguishable unless one of the following rules
3433 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003434
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003435 // A conversion that is not a conversion of a pointer, or
3436 // pointer to member, to bool is better than another conversion
3437 // that is such a conversion.
3438 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3439 return SCS2.isPointerConversionToBool()
3440 ? ImplicitConversionSequence::Better
3441 : ImplicitConversionSequence::Worse;
3442
Douglas Gregor5c407d92008-10-23 00:40:37 +00003443 // C++ [over.ics.rank]p4b2:
3444 //
3445 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003446 // conversion of B* to A* is better than conversion of B* to
3447 // void*, and conversion of A* to void* is better than conversion
3448 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003449 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003450 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003451 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003452 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003453 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3454 // Exactly one of the conversion sequences is a conversion to
3455 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003456 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3457 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003458 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3459 // Neither conversion sequence converts to a void pointer; compare
3460 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003461 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003462 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003463 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003464 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3465 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003466 // Both conversion sequences are conversions to void
3467 // pointers. Compare the source types to determine if there's an
3468 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003469 QualType FromType1 = SCS1.getFromType();
3470 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003471
3472 // Adjust the types we're converting from via the array-to-pointer
3473 // conversion, if we need to.
3474 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003475 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003476 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003477 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003478
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003479 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3480 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003481
John McCall5c32be02010-08-24 20:38:10 +00003482 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003483 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003484 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003485 return ImplicitConversionSequence::Worse;
3486
3487 // Objective-C++: If one interface is more specific than the
3488 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003489 const ObjCObjectPointerType* FromObjCPtr1
3490 = FromType1->getAs<ObjCObjectPointerType>();
3491 const ObjCObjectPointerType* FromObjCPtr2
3492 = FromType2->getAs<ObjCObjectPointerType>();
3493 if (FromObjCPtr1 && FromObjCPtr2) {
3494 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3495 FromObjCPtr2);
3496 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3497 FromObjCPtr1);
3498 if (AssignLeft != AssignRight) {
3499 return AssignLeft? ImplicitConversionSequence::Better
3500 : ImplicitConversionSequence::Worse;
3501 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003502 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003503 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003504
3505 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3506 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003507 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003508 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003509 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003510
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003512 // Check for a better reference binding based on the kind of bindings.
3513 if (isBetterReferenceBindingKind(SCS1, SCS2))
3514 return ImplicitConversionSequence::Better;
3515 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3516 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Sebastian Redlb28b4072009-03-22 23:49:27 +00003518 // C++ [over.ics.rank]p3b4:
3519 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3520 // which the references refer are the same type except for
3521 // top-level cv-qualifiers, and the type to which the reference
3522 // initialized by S2 refers is more cv-qualified than the type
3523 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003524 QualType T1 = SCS1.getToType(2);
3525 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003526 T1 = S.Context.getCanonicalType(T1);
3527 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003528 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003529 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3530 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003531 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003532 // Objective-C++ ARC: If the references refer to objects with different
3533 // lifetimes, prefer bindings that don't change lifetime.
3534 if (SCS1.ObjCLifetimeConversionBinding !=
3535 SCS2.ObjCLifetimeConversionBinding) {
3536 return SCS1.ObjCLifetimeConversionBinding
3537 ? ImplicitConversionSequence::Worse
3538 : ImplicitConversionSequence::Better;
3539 }
3540
Chandler Carruth8e543b32010-12-12 08:17:55 +00003541 // If the type is an array type, promote the element qualifiers to the
3542 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003543 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003544 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003545 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003546 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003547 if (T2.isMoreQualifiedThan(T1))
3548 return ImplicitConversionSequence::Better;
3549 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003550 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003551 }
3552 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003553
Francois Pichet08d2fa02011-09-18 21:37:37 +00003554 // In Microsoft mode, prefer an integral conversion to a
3555 // floating-to-integral conversion if the integral conversion
3556 // is between types of the same size.
3557 // For example:
3558 // void f(float);
3559 // void f(int);
3560 // int main {
3561 // long a;
3562 // f(a);
3563 // }
3564 // Here, MSVC will call f(int) instead of generating a compile error
3565 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003567 SCS1.Second == ICK_Integral_Conversion &&
3568 SCS2.Second == ICK_Floating_Integral &&
3569 S.Context.getTypeSize(SCS1.getFromType()) ==
3570 S.Context.getTypeSize(SCS1.getToType(2)))
3571 return ImplicitConversionSequence::Better;
3572
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003573 return ImplicitConversionSequence::Indistinguishable;
3574}
3575
3576/// CompareQualificationConversions - Compares two standard conversion
3577/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003578/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3579ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003580CompareQualificationConversions(Sema &S,
3581 const StandardConversionSequence& SCS1,
3582 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003583 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003584 // -- S1 and S2 differ only in their qualification conversion and
3585 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3586 // cv-qualification signature of type T1 is a proper subset of
3587 // the cv-qualification signature of type T2, and S1 is not the
3588 // deprecated string literal array-to-pointer conversion (4.2).
3589 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3590 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3591 return ImplicitConversionSequence::Indistinguishable;
3592
3593 // FIXME: the example in the standard doesn't use a qualification
3594 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003595 QualType T1 = SCS1.getToType(2);
3596 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003597 T1 = S.Context.getCanonicalType(T1);
3598 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003600 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3601 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003602
3603 // If the types are the same, we won't learn anything by unwrapped
3604 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003605 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003606 return ImplicitConversionSequence::Indistinguishable;
3607
Chandler Carruth607f38e2009-12-29 07:16:59 +00003608 // If the type is an array type, promote the element qualifiers to the type
3609 // for comparison.
3610 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003611 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003612 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003613 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003614
Mike Stump11289f42009-09-09 15:08:12 +00003615 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003616 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003617
3618 // Objective-C++ ARC:
3619 // Prefer qualification conversions not involving a change in lifetime
3620 // to qualification conversions that do not change lifetime.
3621 if (SCS1.QualificationIncludesObjCLifetime !=
3622 SCS2.QualificationIncludesObjCLifetime) {
3623 Result = SCS1.QualificationIncludesObjCLifetime
3624 ? ImplicitConversionSequence::Worse
3625 : ImplicitConversionSequence::Better;
3626 }
3627
John McCall5c32be02010-08-24 20:38:10 +00003628 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003629 // Within each iteration of the loop, we check the qualifiers to
3630 // determine if this still looks like a qualification
3631 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003632 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003633 // until there are no more pointers or pointers-to-members left
3634 // to unwrap. This essentially mimics what
3635 // IsQualificationConversion does, but here we're checking for a
3636 // strict subset of qualifiers.
3637 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3638 // The qualifiers are the same, so this doesn't tell us anything
3639 // about how the sequences rank.
3640 ;
3641 else if (T2.isMoreQualifiedThan(T1)) {
3642 // T1 has fewer qualifiers, so it could be the better sequence.
3643 if (Result == ImplicitConversionSequence::Worse)
3644 // Neither has qualifiers that are a subset of the other's
3645 // qualifiers.
3646 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003647
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003648 Result = ImplicitConversionSequence::Better;
3649 } else if (T1.isMoreQualifiedThan(T2)) {
3650 // T2 has fewer qualifiers, so it could be the better sequence.
3651 if (Result == ImplicitConversionSequence::Better)
3652 // Neither has qualifiers that are a subset of the other's
3653 // qualifiers.
3654 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003655
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003656 Result = ImplicitConversionSequence::Worse;
3657 } else {
3658 // Qualifiers are disjoint.
3659 return ImplicitConversionSequence::Indistinguishable;
3660 }
3661
3662 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003663 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003665 }
3666
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003667 // Check that the winning standard conversion sequence isn't using
3668 // the deprecated string literal array to pointer conversion.
3669 switch (Result) {
3670 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003671 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003672 Result = ImplicitConversionSequence::Indistinguishable;
3673 break;
3674
3675 case ImplicitConversionSequence::Indistinguishable:
3676 break;
3677
3678 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003679 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003680 Result = ImplicitConversionSequence::Indistinguishable;
3681 break;
3682 }
3683
3684 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003685}
3686
Douglas Gregor5c407d92008-10-23 00:40:37 +00003687/// CompareDerivedToBaseConversions - Compares two standard conversion
3688/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003689/// various kinds of derived-to-base conversions (C++
3690/// [over.ics.rank]p4b3). As part of these checks, we also look at
3691/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003692ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003693CompareDerivedToBaseConversions(Sema &S,
3694 const StandardConversionSequence& SCS1,
3695 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003696 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003697 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003698 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003699 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003700
3701 // Adjust the types we're converting from via the array-to-pointer
3702 // conversion, if we need to.
3703 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003704 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003705 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003706 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003707
3708 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003709 FromType1 = S.Context.getCanonicalType(FromType1);
3710 ToType1 = S.Context.getCanonicalType(ToType1);
3711 FromType2 = S.Context.getCanonicalType(FromType2);
3712 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003713
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003714 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003715 //
3716 // If class B is derived directly or indirectly from class A and
3717 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003718 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003719 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003720 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003721 SCS2.Second == ICK_Pointer_Conversion &&
3722 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3723 FromType1->isPointerType() && FromType2->isPointerType() &&
3724 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003725 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003726 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003727 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003728 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003729 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003730 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003731 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003732 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003733
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003734 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003735 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003736 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003737 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003738 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003739 return ImplicitConversionSequence::Worse;
3740 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003741
3742 // -- conversion of B* to A* is better than conversion of C* to A*,
3743 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003744 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003745 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003746 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003747 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003748 }
3749 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3750 SCS2.Second == ICK_Pointer_Conversion) {
3751 const ObjCObjectPointerType *FromPtr1
3752 = FromType1->getAs<ObjCObjectPointerType>();
3753 const ObjCObjectPointerType *FromPtr2
3754 = FromType2->getAs<ObjCObjectPointerType>();
3755 const ObjCObjectPointerType *ToPtr1
3756 = ToType1->getAs<ObjCObjectPointerType>();
3757 const ObjCObjectPointerType *ToPtr2
3758 = ToType2->getAs<ObjCObjectPointerType>();
3759
3760 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3761 // Apply the same conversion ranking rules for Objective-C pointer types
3762 // that we do for C++ pointers to class types. However, we employ the
3763 // Objective-C pseudo-subtyping relationship used for assignment of
3764 // Objective-C pointer types.
3765 bool FromAssignLeft
3766 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3767 bool FromAssignRight
3768 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3769 bool ToAssignLeft
3770 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3771 bool ToAssignRight
3772 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3773
3774 // A conversion to an a non-id object pointer type or qualified 'id'
3775 // type is better than a conversion to 'id'.
3776 if (ToPtr1->isObjCIdType() &&
3777 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3778 return ImplicitConversionSequence::Worse;
3779 if (ToPtr2->isObjCIdType() &&
3780 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3781 return ImplicitConversionSequence::Better;
3782
3783 // A conversion to a non-id object pointer type is better than a
3784 // conversion to a qualified 'id' type
3785 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3786 return ImplicitConversionSequence::Worse;
3787 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3788 return ImplicitConversionSequence::Better;
3789
3790 // A conversion to an a non-Class object pointer type or qualified 'Class'
3791 // type is better than a conversion to 'Class'.
3792 if (ToPtr1->isObjCClassType() &&
3793 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3794 return ImplicitConversionSequence::Worse;
3795 if (ToPtr2->isObjCClassType() &&
3796 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3797 return ImplicitConversionSequence::Better;
3798
3799 // A conversion to a non-Class object pointer type is better than a
3800 // conversion to a qualified 'Class' type.
3801 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3802 return ImplicitConversionSequence::Worse;
3803 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3804 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003805
Douglas Gregor058d3de2011-01-31 18:51:41 +00003806 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3807 if (S.Context.hasSameType(FromType1, FromType2) &&
3808 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3809 (ToAssignLeft != ToAssignRight))
3810 return ToAssignLeft? ImplicitConversionSequence::Worse
3811 : ImplicitConversionSequence::Better;
3812
3813 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3814 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3815 (FromAssignLeft != FromAssignRight))
3816 return FromAssignLeft? ImplicitConversionSequence::Better
3817 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003818 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003819 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003820
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003821 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003822 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3823 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3824 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003826 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003828 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003830 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003831 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003832 ToType2->getAs<MemberPointerType>();
3833 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3834 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3835 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3836 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3837 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3838 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3839 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3840 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003841 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003842 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003843 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003844 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003845 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003846 return ImplicitConversionSequence::Better;
3847 }
3848 // conversion of B::* to C::* is better than conversion of A::* to C::*
3849 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003850 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003851 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003852 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003853 return ImplicitConversionSequence::Worse;
3854 }
3855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856
Douglas Gregor5ab11652010-04-17 22:01:05 +00003857 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003858 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003859 // -- binding of an expression of type C to a reference of type
3860 // B& is better than binding an expression of type C to a
3861 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003862 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3863 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3864 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003865 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003866 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003867 return ImplicitConversionSequence::Worse;
3868 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003869
Douglas Gregor2fe98832008-11-03 19:09:14 +00003870 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003871 // -- binding of an expression of type B to a reference of type
3872 // A& is better than binding an expression of type C to a
3873 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003874 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3875 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3876 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003877 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003878 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003879 return ImplicitConversionSequence::Worse;
3880 }
3881 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003882
Douglas Gregor5c407d92008-10-23 00:40:37 +00003883 return ImplicitConversionSequence::Indistinguishable;
3884}
3885
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003886/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3887/// determine whether they are reference-related,
3888/// reference-compatible, reference-compatible with added
3889/// qualification, or incompatible, for use in C++ initialization by
3890/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3891/// type, and the first type (T1) is the pointee type of the reference
3892/// type being initialized.
3893Sema::ReferenceCompareResult
3894Sema::CompareReferenceRelationship(SourceLocation Loc,
3895 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003896 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003897 bool &ObjCConversion,
3898 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003899 assert(!OrigT1->isReferenceType() &&
3900 "T1 must be the pointee type of the reference type");
3901 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3902
3903 QualType T1 = Context.getCanonicalType(OrigT1);
3904 QualType T2 = Context.getCanonicalType(OrigT2);
3905 Qualifiers T1Quals, T2Quals;
3906 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3907 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3908
3909 // C++ [dcl.init.ref]p4:
3910 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3911 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3912 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003913 DerivedToBase = false;
3914 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003915 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003916 if (UnqualT1 == UnqualT2) {
3917 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003918 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003919 IsDerivedFrom(UnqualT2, UnqualT1))
3920 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003921 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3922 UnqualT2->isObjCObjectOrInterfaceType() &&
3923 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3924 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003925 else
3926 return Ref_Incompatible;
3927
3928 // At this point, we know that T1 and T2 are reference-related (at
3929 // least).
3930
3931 // If the type is an array type, promote the element qualifiers to the type
3932 // for comparison.
3933 if (isa<ArrayType>(T1) && T1Quals)
3934 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3935 if (isa<ArrayType>(T2) && T2Quals)
3936 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3937
3938 // C++ [dcl.init.ref]p4:
3939 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3940 // reference-related to T2 and cv1 is the same cv-qualification
3941 // as, or greater cv-qualification than, cv2. For purposes of
3942 // overload resolution, cases for which cv1 is greater
3943 // cv-qualification than cv2 are identified as
3944 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003945 //
3946 // Note that we also require equivalence of Objective-C GC and address-space
3947 // qualifiers when performing these computations, so that e.g., an int in
3948 // address space 1 is not reference-compatible with an int in address
3949 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003950 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3951 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3952 T1Quals.removeObjCLifetime();
3953 T2Quals.removeObjCLifetime();
3954 ObjCLifetimeConversion = true;
3955 }
3956
Douglas Gregord517d552011-04-28 17:56:11 +00003957 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003958 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003959 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003960 return Ref_Compatible_With_Added_Qualification;
3961 else
3962 return Ref_Related;
3963}
3964
Douglas Gregor836a7e82010-08-11 02:15:33 +00003965/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003966/// with DeclType. Return true if something definite is found.
3967static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003968FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3969 QualType DeclType, SourceLocation DeclLoc,
3970 Expr *Init, QualType T2, bool AllowRvalues,
3971 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003972 assert(T2->isRecordType() && "Can only find conversions of record types.");
3973 CXXRecordDecl *T2RecordDecl
3974 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3975
3976 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003977 std::pair<CXXRecordDecl::conversion_iterator,
3978 CXXRecordDecl::conversion_iterator>
3979 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3980 for (CXXRecordDecl::conversion_iterator
3981 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003982 NamedDecl *D = *I;
3983 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3984 if (isa<UsingShadowDecl>(D))
3985 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3986
3987 FunctionTemplateDecl *ConvTemplate
3988 = dyn_cast<FunctionTemplateDecl>(D);
3989 CXXConversionDecl *Conv;
3990 if (ConvTemplate)
3991 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3992 else
3993 Conv = cast<CXXConversionDecl>(D);
3994
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003996 // explicit conversions, skip it.
3997 if (!AllowExplicit && Conv->isExplicit())
3998 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999
Douglas Gregor836a7e82010-08-11 02:15:33 +00004000 if (AllowRvalues) {
4001 bool DerivedToBase = false;
4002 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004003 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004004
4005 // If we are initializing an rvalue reference, don't permit conversion
4006 // functions that return lvalues.
4007 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4008 const ReferenceType *RefType
4009 = Conv->getConversionType()->getAs<LValueReferenceType>();
4010 if (RefType && !RefType->getPointeeType()->isFunctionType())
4011 continue;
4012 }
4013
Douglas Gregor836a7e82010-08-11 02:15:33 +00004014 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004015 S.CompareReferenceRelationship(
4016 DeclLoc,
4017 Conv->getConversionType().getNonReferenceType()
4018 .getUnqualifiedType(),
4019 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004020 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004021 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004022 continue;
4023 } else {
4024 // If the conversion function doesn't return a reference type,
4025 // it can't be considered for this conversion. An rvalue reference
4026 // is only acceptable if its referencee is a function type.
4027
4028 const ReferenceType *RefType =
4029 Conv->getConversionType()->getAs<ReferenceType>();
4030 if (!RefType ||
4031 (!RefType->isLValueReferenceType() &&
4032 !RefType->getPointeeType()->isFunctionType()))
4033 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Douglas Gregor836a7e82010-08-11 02:15:33 +00004036 if (ConvTemplate)
4037 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004038 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004039 else
4040 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004041 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00004042 }
4043
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004044 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4045
Sebastian Redld92badf2010-06-30 18:13:39 +00004046 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004047 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004048 case OR_Success:
4049 // C++ [over.ics.ref]p1:
4050 //
4051 // [...] If the parameter binds directly to the result of
4052 // applying a conversion function to the argument
4053 // expression, the implicit conversion sequence is a
4054 // user-defined conversion sequence (13.3.3.1.2), with the
4055 // second standard conversion sequence either an identity
4056 // conversion or, if the conversion function returns an
4057 // entity of a type that is a derived class of the parameter
4058 // type, a derived-to-base Conversion.
4059 if (!Best->FinalConversion.DirectBinding)
4060 return false;
4061
4062 ICS.setUserDefined();
4063 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4064 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004065 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004066 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004067 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004068 ICS.UserDefined.EllipsisConversion = false;
4069 assert(ICS.UserDefined.After.ReferenceBinding &&
4070 ICS.UserDefined.After.DirectBinding &&
4071 "Expected a direct reference binding!");
4072 return true;
4073
4074 case OR_Ambiguous:
4075 ICS.setAmbiguous();
4076 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4077 Cand != CandidateSet.end(); ++Cand)
4078 if (Cand->Viable)
4079 ICS.Ambiguous.addConversion(Cand->Function);
4080 return true;
4081
4082 case OR_No_Viable_Function:
4083 case OR_Deleted:
4084 // There was no suitable conversion, or we found a deleted
4085 // conversion; continue with other checks.
4086 return false;
4087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
David Blaikie8a40f702012-01-17 06:56:22 +00004089 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004090}
4091
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004092/// \brief Compute an implicit conversion sequence for reference
4093/// initialization.
4094static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004095TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004096 SourceLocation DeclLoc,
4097 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004098 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4100
4101 // Most paths end in a failed conversion.
4102 ImplicitConversionSequence ICS;
4103 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4104
4105 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4106 QualType T2 = Init->getType();
4107
4108 // If the initializer is the address of an overloaded function, try
4109 // to resolve the overloaded function. If all goes well, T2 is the
4110 // type of the resulting function.
4111 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4112 DeclAccessPair Found;
4113 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4114 false, Found))
4115 T2 = Fn->getType();
4116 }
4117
4118 // Compute some basic properties of the types and the initializer.
4119 bool isRValRef = DeclType->isRValueReferenceType();
4120 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004121 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004122 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004123 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004124 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004125 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004126 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004127
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004128
Sebastian Redld92badf2010-06-30 18:13:39 +00004129 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004130 // A reference to type "cv1 T1" is initialized by an expression
4131 // of type "cv2 T2" as follows:
4132
Sebastian Redld92badf2010-06-30 18:13:39 +00004133 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004134 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004135 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4136 // reference-compatible with "cv2 T2," or
4137 //
4138 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4139 if (InitCategory.isLValue() &&
4140 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004141 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004142 // When a parameter of reference type binds directly (8.5.3)
4143 // to an argument expression, the implicit conversion sequence
4144 // is the identity conversion, unless the argument expression
4145 // has a type that is a derived class of the parameter type,
4146 // in which case the implicit conversion sequence is a
4147 // derived-to-base Conversion (13.3.3.1).
4148 ICS.setStandard();
4149 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004150 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4151 : ObjCConversion? ICK_Compatible_Conversion
4152 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004153 ICS.Standard.Third = ICK_Identity;
4154 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4155 ICS.Standard.setToType(0, T2);
4156 ICS.Standard.setToType(1, T1);
4157 ICS.Standard.setToType(2, T1);
4158 ICS.Standard.ReferenceBinding = true;
4159 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004160 ICS.Standard.IsLvalueReference = !isRValRef;
4161 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4162 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004163 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004164 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004165 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004166
Sebastian Redld92badf2010-06-30 18:13:39 +00004167 // Nothing more to do: the inaccessibility/ambiguity check for
4168 // derived-to-base conversions is suppressed when we're
4169 // computing the implicit conversion sequence (C++
4170 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004171 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004172 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004173
Sebastian Redld92badf2010-06-30 18:13:39 +00004174 // -- has a class type (i.e., T2 is a class type), where T1 is
4175 // not reference-related to T2, and can be implicitly
4176 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4177 // is reference-compatible with "cv3 T3" 92) (this
4178 // conversion is selected by enumerating the applicable
4179 // conversion functions (13.3.1.6) and choosing the best
4180 // one through overload resolution (13.3)),
4181 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004183 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004184 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4185 Init, T2, /*AllowRvalues=*/false,
4186 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004187 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004188 }
4189 }
4190
Sebastian Redld92badf2010-06-30 18:13:39 +00004191 // -- Otherwise, the reference shall be an lvalue reference to a
4192 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004193 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004195 // We actually handle one oddity of C++ [over.ics.ref] at this
4196 // point, which is that, due to p2 (which short-circuits reference
4197 // binding by only attempting a simple conversion for non-direct
4198 // bindings) and p3's strange wording, we allow a const volatile
4199 // reference to bind to an rvalue. Hence the check for the presence
4200 // of "const" rather than checking for "const" being the only
4201 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 // This is also the point where rvalue references and lvalue inits no longer
4203 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004204 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004205 return ICS;
4206
Douglas Gregorf143cd52011-01-24 16:14:37 +00004207 // -- If the initializer expression
4208 //
4209 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004210 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004211 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4212 (InitCategory.isXValue() ||
4213 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4214 (InitCategory.isLValue() && T2->isFunctionType()))) {
4215 ICS.setStandard();
4216 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004218 : ObjCConversion? ICK_Compatible_Conversion
4219 : ICK_Identity;
4220 ICS.Standard.Third = ICK_Identity;
4221 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4222 ICS.Standard.setToType(0, T2);
4223 ICS.Standard.setToType(1, T1);
4224 ICS.Standard.setToType(2, T1);
4225 ICS.Standard.ReferenceBinding = true;
4226 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4227 // binding unless we're binding to a class prvalue.
4228 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4229 // allow the use of rvalue references in C++98/03 for the benefit of
4230 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004232 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004233 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004234 ICS.Standard.IsLvalueReference = !isRValRef;
4235 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004237 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004238 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004239 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregorf143cd52011-01-24 16:14:37 +00004243 // -- has a class type (i.e., T2 is a class type), where T1 is not
4244 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 // an xvalue, class prvalue, or function lvalue of type
4246 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004247 // "cv3 T3",
4248 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004250 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004252 // class subobject).
4253 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004255 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4256 Init, T2, /*AllowRvalues=*/true,
4257 AllowExplicit)) {
4258 // In the second case, if the reference is an rvalue reference
4259 // and the second standard conversion sequence of the
4260 // user-defined conversion sequence includes an lvalue-to-rvalue
4261 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004263 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4264 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4265
Douglas Gregor95273c32011-01-21 16:36:05 +00004266 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004269 // -- Otherwise, a temporary of type "cv1 T1" is created and
4270 // initialized from the initializer expression using the
4271 // rules for a non-reference copy initialization (8.5). The
4272 // reference is then bound to the temporary. If T1 is
4273 // reference-related to T2, cv1 must be the same
4274 // cv-qualification as, or greater cv-qualification than,
4275 // cv2; otherwise, the program is ill-formed.
4276 if (RefRelationship == Sema::Ref_Related) {
4277 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4278 // we would be reference-compatible or reference-compatible with
4279 // added qualification. But that wasn't the case, so the reference
4280 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004281 //
4282 // Note that we only want to check address spaces and cvr-qualifiers here.
4283 // ObjC GC and lifetime qualifiers aren't important.
4284 Qualifiers T1Quals = T1.getQualifiers();
4285 Qualifiers T2Quals = T2.getQualifiers();
4286 T1Quals.removeObjCGCAttr();
4287 T1Quals.removeObjCLifetime();
4288 T2Quals.removeObjCGCAttr();
4289 T2Quals.removeObjCLifetime();
4290 if (!T1Quals.compatiblyIncludes(T2Quals))
4291 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004292 }
4293
4294 // If at least one of the types is a class type, the types are not
4295 // related, and we aren't allowed any user conversions, the
4296 // reference binding fails. This case is important for breaking
4297 // recursion, since TryImplicitConversion below will attempt to
4298 // create a temporary through the use of a copy constructor.
4299 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4300 (T1->isRecordType() || T2->isRecordType()))
4301 return ICS;
4302
Douglas Gregorcba72b12011-01-21 05:18:22 +00004303 // If T1 is reference-related to T2 and the reference is an rvalue
4304 // reference, the initializer expression shall not be an lvalue.
4305 if (RefRelationship >= Sema::Ref_Related &&
4306 isRValRef && Init->Classify(S.Context).isLValue())
4307 return ICS;
4308
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004309 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310 // When a parameter of reference type is not bound directly to
4311 // an argument expression, the conversion sequence is the one
4312 // required to convert the argument expression to the
4313 // underlying type of the reference according to
4314 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4315 // to copy-initializing a temporary of the underlying type with
4316 // the argument expression. Any difference in top-level
4317 // cv-qualification is subsumed by the initialization itself
4318 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004319 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4320 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004321 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004322 /*CStyle=*/false,
4323 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004324
4325 // Of course, that's still a reference binding.
4326 if (ICS.isStandard()) {
4327 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004328 ICS.Standard.IsLvalueReference = !isRValRef;
4329 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4330 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004331 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004332 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004333 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004334 // Don't allow rvalue references to bind to lvalues.
4335 if (DeclType->isRValueReferenceType()) {
4336 if (const ReferenceType *RefType
4337 = ICS.UserDefined.ConversionFunction->getResultType()
4338 ->getAs<LValueReferenceType>()) {
4339 if (!RefType->getPointeeType()->isFunctionType()) {
4340 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4341 DeclType);
4342 return ICS;
4343 }
4344 }
4345 }
4346
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004347 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004348 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4349 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4350 ICS.UserDefined.After.BindsToRvalue = true;
4351 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4352 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004353 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004354
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004355 return ICS;
4356}
4357
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004358static ImplicitConversionSequence
4359TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4360 bool SuppressUserConversions,
4361 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004362 bool AllowObjCWritebackConversion,
4363 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004364
4365/// TryListConversion - Try to copy-initialize a value of type ToType from the
4366/// initializer list From.
4367static ImplicitConversionSequence
4368TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4369 bool SuppressUserConversions,
4370 bool InOverloadResolution,
4371 bool AllowObjCWritebackConversion) {
4372 // C++11 [over.ics.list]p1:
4373 // When an argument is an initializer list, it is not an expression and
4374 // special rules apply for converting it to a parameter type.
4375
4376 ImplicitConversionSequence Result;
4377 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004378 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004379
Sebastian Redl09edce02012-01-23 22:09:39 +00004380 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004381 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004382 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004383 return Result;
4384
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004385 // C++11 [over.ics.list]p2:
4386 // If the parameter type is std::initializer_list<X> or "array of X" and
4387 // all the elements can be implicitly converted to X, the implicit
4388 // conversion sequence is the worst conversion necessary to convert an
4389 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004390 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004391 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004392 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004393 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004394 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004395 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004396 if (!X.isNull()) {
4397 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4398 Expr *Init = From->getInit(i);
4399 ImplicitConversionSequence ICS =
4400 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4401 InOverloadResolution,
4402 AllowObjCWritebackConversion);
4403 // If a single element isn't convertible, fail.
4404 if (ICS.isBad()) {
4405 Result = ICS;
4406 break;
4407 }
4408 // Otherwise, look for the worst conversion.
4409 if (Result.isBad() ||
4410 CompareImplicitConversionSequences(S, ICS, Result) ==
4411 ImplicitConversionSequence::Worse)
4412 Result = ICS;
4413 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004414
4415 // For an empty list, we won't have computed any conversion sequence.
4416 // Introduce the identity conversion sequence.
4417 if (From->getNumInits() == 0) {
4418 Result.setStandard();
4419 Result.Standard.setAsIdentityConversion();
4420 Result.Standard.setFromType(ToType);
4421 Result.Standard.setAllToTypes(ToType);
4422 }
4423
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004424 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004425 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004426 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004427 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004428
4429 // C++11 [over.ics.list]p3:
4430 // Otherwise, if the parameter is a non-aggregate class X and overload
4431 // resolution chooses a single best constructor [...] the implicit
4432 // conversion sequence is a user-defined conversion sequence. If multiple
4433 // constructors are viable but none is better than the others, the
4434 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004435 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4436 // This function can deal with initializer lists.
4437 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4438 /*AllowExplicit=*/false,
4439 InOverloadResolution, /*CStyle=*/false,
4440 AllowObjCWritebackConversion);
4441 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004442 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004443 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004444
4445 // C++11 [over.ics.list]p4:
4446 // Otherwise, if the parameter has an aggregate type which can be
4447 // initialized from the initializer list [...] the implicit conversion
4448 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004449 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004450 // Type is an aggregate, argument is an init list. At this point it comes
4451 // down to checking whether the initialization works.
4452 // FIXME: Find out whether this parameter is consumed or not.
4453 InitializedEntity Entity =
4454 InitializedEntity::InitializeParameter(S.Context, ToType,
4455 /*Consumed=*/false);
4456 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4457 Result.setUserDefined();
4458 Result.UserDefined.Before.setAsIdentityConversion();
4459 // Initializer lists don't have a type.
4460 Result.UserDefined.Before.setFromType(QualType());
4461 Result.UserDefined.Before.setAllToTypes(QualType());
4462
4463 Result.UserDefined.After.setAsIdentityConversion();
4464 Result.UserDefined.After.setFromType(ToType);
4465 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004466 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004467 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004468 return Result;
4469 }
4470
4471 // C++11 [over.ics.list]p5:
4472 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004473 if (ToType->isReferenceType()) {
4474 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4475 // mention initializer lists in any way. So we go by what list-
4476 // initialization would do and try to extrapolate from that.
4477
4478 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4479
4480 // If the initializer list has a single element that is reference-related
4481 // to the parameter type, we initialize the reference from that.
4482 if (From->getNumInits() == 1) {
4483 Expr *Init = From->getInit(0);
4484
4485 QualType T2 = Init->getType();
4486
4487 // If the initializer is the address of an overloaded function, try
4488 // to resolve the overloaded function. If all goes well, T2 is the
4489 // type of the resulting function.
4490 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4491 DeclAccessPair Found;
4492 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4493 Init, ToType, false, Found))
4494 T2 = Fn->getType();
4495 }
4496
4497 // Compute some basic properties of the types and the initializer.
4498 bool dummy1 = false;
4499 bool dummy2 = false;
4500 bool dummy3 = false;
4501 Sema::ReferenceCompareResult RefRelationship
4502 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4503 dummy2, dummy3);
4504
4505 if (RefRelationship >= Sema::Ref_Related)
4506 return TryReferenceInit(S, Init, ToType,
4507 /*FIXME:*/From->getLocStart(),
4508 SuppressUserConversions,
4509 /*AllowExplicit=*/false);
4510 }
4511
4512 // Otherwise, we bind the reference to a temporary created from the
4513 // initializer list.
4514 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4515 InOverloadResolution,
4516 AllowObjCWritebackConversion);
4517 if (Result.isFailure())
4518 return Result;
4519 assert(!Result.isEllipsis() &&
4520 "Sub-initialization cannot result in ellipsis conversion.");
4521
4522 // Can we even bind to a temporary?
4523 if (ToType->isRValueReferenceType() ||
4524 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4525 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4526 Result.UserDefined.After;
4527 SCS.ReferenceBinding = true;
4528 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4529 SCS.BindsToRvalue = true;
4530 SCS.BindsToFunctionLvalue = false;
4531 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4532 SCS.ObjCLifetimeConversionBinding = false;
4533 } else
4534 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4535 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004536 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004537 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004538
4539 // C++11 [over.ics.list]p6:
4540 // Otherwise, if the parameter type is not a class:
4541 if (!ToType->isRecordType()) {
4542 // - if the initializer list has one element, the implicit conversion
4543 // sequence is the one required to convert the element to the
4544 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004545 unsigned NumInits = From->getNumInits();
4546 if (NumInits == 1)
4547 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4548 SuppressUserConversions,
4549 InOverloadResolution,
4550 AllowObjCWritebackConversion);
4551 // - if the initializer list has no elements, the implicit conversion
4552 // sequence is the identity conversion.
4553 else if (NumInits == 0) {
4554 Result.setStandard();
4555 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004556 Result.Standard.setFromType(ToType);
4557 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004558 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004559 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004560 return Result;
4561 }
4562
4563 // C++11 [over.ics.list]p7:
4564 // In all cases other than those enumerated above, no conversion is possible
4565 return Result;
4566}
4567
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004568/// TryCopyInitialization - Try to copy-initialize a value of type
4569/// ToType from the expression From. Return the implicit conversion
4570/// sequence required to pass this argument, which may be a bad
4571/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004572/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004573/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004574static ImplicitConversionSequence
4575TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004577 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004578 bool AllowObjCWritebackConversion,
4579 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004580 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4581 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4582 InOverloadResolution,AllowObjCWritebackConversion);
4583
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004584 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004585 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004586 /*FIXME:*/From->getLocStart(),
4587 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004588 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004589
John McCall5c32be02010-08-24 20:38:10 +00004590 return TryImplicitConversion(S, From, ToType,
4591 SuppressUserConversions,
4592 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004593 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004594 /*CStyle=*/false,
4595 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004596}
4597
Anna Zaks1b068122011-07-28 19:46:48 +00004598static bool TryCopyInitialization(const CanQualType FromQTy,
4599 const CanQualType ToQTy,
4600 Sema &S,
4601 SourceLocation Loc,
4602 ExprValueKind FromVK) {
4603 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4604 ImplicitConversionSequence ICS =
4605 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4606
4607 return !ICS.isBad();
4608}
4609
Douglas Gregor436424c2008-11-18 23:14:02 +00004610/// TryObjectArgumentInitialization - Try to initialize the object
4611/// parameter of the given member function (@c Method) from the
4612/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004613static ImplicitConversionSequence
4614TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004615 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004616 CXXMethodDecl *Method,
4617 CXXRecordDecl *ActingContext) {
4618 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004619 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4620 // const volatile object.
4621 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4622 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004623 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004624
4625 // Set up the conversion sequence as a "bad" conversion, to allow us
4626 // to exit early.
4627 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004628
4629 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004630 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004631 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004632 FromType = PT->getPointeeType();
4633
Douglas Gregor02824322011-01-26 19:30:28 +00004634 // When we had a pointer, it's implicitly dereferenced, so we
4635 // better have an lvalue.
4636 assert(FromClassification.isLValue());
4637 }
4638
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004639 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004640
Douglas Gregor02824322011-01-26 19:30:28 +00004641 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004643 // parameter is
4644 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004645 // - "lvalue reference to cv X" for functions declared without a
4646 // ref-qualifier or with the & ref-qualifier
4647 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004648 // ref-qualifier
4649 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004651 // cv-qualification on the member function declaration.
4652 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004654 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004655 // (C++ [over.match.funcs]p5). We perform a simplified version of
4656 // reference binding here, that allows class rvalues to bind to
4657 // non-constant references.
4658
Douglas Gregor02824322011-01-26 19:30:28 +00004659 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004660 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004662 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004663 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004664 ICS.setBad(BadConversionSequence::bad_qualifiers,
4665 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004666 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004667 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004668
4669 // Check that we have either the same type or a derived type. It
4670 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004671 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004672 ImplicitConversionKind SecondKind;
4673 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4674 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004675 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004676 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004677 else {
John McCall65eb8792010-02-25 01:37:24 +00004678 ICS.setBad(BadConversionSequence::unrelated_class,
4679 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004680 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004681 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004682
Douglas Gregor02824322011-01-26 19:30:28 +00004683 // Check the ref-qualifier.
4684 switch (Method->getRefQualifier()) {
4685 case RQ_None:
4686 // Do nothing; we don't care about lvalueness or rvalueness.
4687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688
Douglas Gregor02824322011-01-26 19:30:28 +00004689 case RQ_LValue:
4690 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4691 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004692 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004693 ImplicitParamType);
4694 return ICS;
4695 }
4696 break;
4697
4698 case RQ_RValue:
4699 if (!FromClassification.isRValue()) {
4700 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004702 ImplicitParamType);
4703 return ICS;
4704 }
4705 break;
4706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregor436424c2008-11-18 23:14:02 +00004708 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004709 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004710 ICS.Standard.setAsIdentityConversion();
4711 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004712 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004713 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004714 ICS.Standard.ReferenceBinding = true;
4715 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004717 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004718 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4719 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4720 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004721 return ICS;
4722}
4723
4724/// PerformObjectArgumentInitialization - Perform initialization of
4725/// the implicit object parameter for the given Method with the given
4726/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004727ExprResult
4728Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004730 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004731 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004732 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004733 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004734 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004735
Douglas Gregor02824322011-01-26 19:30:28 +00004736 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004737 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004738 FromRecordType = PT->getPointeeType();
4739 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004740 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004741 } else {
4742 FromRecordType = From->getType();
4743 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004744 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004745 }
4746
John McCall6e9f8f62009-12-03 04:06:58 +00004747 // Note that we always use the true parent context when performing
4748 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004749 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004750 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4751 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004752 if (ICS.isBad()) {
4753 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4754 Qualifiers FromQs = FromRecordType.getQualifiers();
4755 Qualifiers ToQs = DestType.getQualifiers();
4756 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4757 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004758 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004759 diag::err_member_function_call_bad_cvr)
4760 << Method->getDeclName() << FromRecordType << (CVR - 1)
4761 << From->getSourceRange();
4762 Diag(Method->getLocation(), diag::note_previous_decl)
4763 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004764 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004765 }
4766 }
4767
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004768 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004769 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004770 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004771 }
Mike Stump11289f42009-09-09 15:08:12 +00004772
John Wiegley01296292011-04-08 18:41:53 +00004773 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4774 ExprResult FromRes =
4775 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4776 if (FromRes.isInvalid())
4777 return ExprError();
4778 From = FromRes.take();
4779 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004780
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004781 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004782 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004783 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004784 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004785}
4786
Douglas Gregor5fb53972009-01-14 15:45:31 +00004787/// TryContextuallyConvertToBool - Attempt to contextually convert the
4788/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004789static ImplicitConversionSequence
4790TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004791 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004792 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004793 // FIXME: Are these flags correct?
4794 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004795 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004796 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004797 /*CStyle=*/false,
4798 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004799}
4800
4801/// PerformContextuallyConvertToBool - Perform a contextual conversion
4802/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004803ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004804 if (checkPlaceholderForOverload(*this, From))
4805 return ExprError();
4806
John McCall5c32be02010-08-24 20:38:10 +00004807 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004808 if (!ICS.isBad())
4809 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
Fariborz Jahanian76197412009-11-18 18:26:29 +00004811 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004812 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004813 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004814 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004815 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004816}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Richard Smithf8379a02012-01-18 23:55:52 +00004818/// Check that the specified conversion is permitted in a converted constant
4819/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4820/// is acceptable.
4821static bool CheckConvertedConstantConversions(Sema &S,
4822 StandardConversionSequence &SCS) {
4823 // Since we know that the target type is an integral or unscoped enumeration
4824 // type, most conversion kinds are impossible. All possible First and Third
4825 // conversions are fine.
4826 switch (SCS.Second) {
4827 case ICK_Identity:
4828 case ICK_Integral_Promotion:
4829 case ICK_Integral_Conversion:
4830 return true;
4831
4832 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004833 // Conversion from an integral or unscoped enumeration type to bool is
4834 // classified as ICK_Boolean_Conversion, but it's also an integral
4835 // conversion, so it's permitted in a converted constant expression.
4836 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4837 SCS.getToType(2)->isBooleanType();
4838
Richard Smithf8379a02012-01-18 23:55:52 +00004839 case ICK_Floating_Integral:
4840 case ICK_Complex_Real:
4841 return false;
4842
4843 case ICK_Lvalue_To_Rvalue:
4844 case ICK_Array_To_Pointer:
4845 case ICK_Function_To_Pointer:
4846 case ICK_NoReturn_Adjustment:
4847 case ICK_Qualification:
4848 case ICK_Compatible_Conversion:
4849 case ICK_Vector_Conversion:
4850 case ICK_Vector_Splat:
4851 case ICK_Derived_To_Base:
4852 case ICK_Pointer_Conversion:
4853 case ICK_Pointer_Member:
4854 case ICK_Block_Pointer_Conversion:
4855 case ICK_Writeback_Conversion:
4856 case ICK_Floating_Promotion:
4857 case ICK_Complex_Promotion:
4858 case ICK_Complex_Conversion:
4859 case ICK_Floating_Conversion:
4860 case ICK_TransparentUnionConversion:
4861 llvm_unreachable("unexpected second conversion kind");
4862
4863 case ICK_Num_Conversion_Kinds:
4864 break;
4865 }
4866
4867 llvm_unreachable("unknown conversion kind");
4868}
4869
4870/// CheckConvertedConstantExpression - Check that the expression From is a
4871/// converted constant expression of type T, perform the conversion and produce
4872/// the converted expression, per C++11 [expr.const]p3.
4873ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4874 llvm::APSInt &Value,
4875 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004876 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004877 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4878
4879 if (checkPlaceholderForOverload(*this, From))
4880 return ExprError();
4881
4882 // C++11 [expr.const]p3 with proposed wording fixes:
4883 // A converted constant expression of type T is a core constant expression,
4884 // implicitly converted to a prvalue of type T, where the converted
4885 // expression is a literal constant expression and the implicit conversion
4886 // sequence contains only user-defined conversions, lvalue-to-rvalue
4887 // conversions, integral promotions, and integral conversions other than
4888 // narrowing conversions.
4889 ImplicitConversionSequence ICS =
4890 TryImplicitConversion(From, T,
4891 /*SuppressUserConversions=*/false,
4892 /*AllowExplicit=*/false,
4893 /*InOverloadResolution=*/false,
4894 /*CStyle=*/false,
4895 /*AllowObjcWritebackConversion=*/false);
4896 StandardConversionSequence *SCS = 0;
4897 switch (ICS.getKind()) {
4898 case ImplicitConversionSequence::StandardConversion:
4899 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004900 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004901 diag::err_typecheck_converted_constant_expression_disallowed)
4902 << From->getType() << From->getSourceRange() << T;
4903 SCS = &ICS.Standard;
4904 break;
4905 case ImplicitConversionSequence::UserDefinedConversion:
4906 // We are converting from class type to an integral or enumeration type, so
4907 // the Before sequence must be trivial.
4908 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004909 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004910 diag::err_typecheck_converted_constant_expression_disallowed)
4911 << From->getType() << From->getSourceRange() << T;
4912 SCS = &ICS.UserDefined.After;
4913 break;
4914 case ImplicitConversionSequence::AmbiguousConversion:
4915 case ImplicitConversionSequence::BadConversion:
4916 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004917 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004918 diag::err_typecheck_converted_constant_expression)
4919 << From->getType() << From->getSourceRange() << T;
4920 return ExprError();
4921
4922 case ImplicitConversionSequence::EllipsisConversion:
4923 llvm_unreachable("ellipsis conversion in converted constant expression");
4924 }
4925
4926 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4927 if (Result.isInvalid())
4928 return Result;
4929
4930 // Check for a narrowing implicit conversion.
4931 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004932 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004933 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4934 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004935 case NK_Variable_Narrowing:
4936 // Implicit conversion to a narrower type, and the value is not a constant
4937 // expression. We'll diagnose this in a moment.
4938 case NK_Not_Narrowing:
4939 break;
4940
4941 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004942 Diag(From->getLocStart(),
4943 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4944 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004945 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004946 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004947 break;
4948
4949 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004950 Diag(From->getLocStart(),
4951 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4952 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004953 << CCE << /*Constant*/0 << From->getType() << T;
4954 break;
4955 }
4956
4957 // Check the expression is a constant expression.
4958 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4959 Expr::EvalResult Eval;
4960 Eval.Diag = &Notes;
4961
4962 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4963 // The expression can't be folded, so we can't keep it at this position in
4964 // the AST.
4965 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004966 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004967 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004968
4969 if (Notes.empty()) {
4970 // It's a constant expression.
4971 return Result;
4972 }
Richard Smithf8379a02012-01-18 23:55:52 +00004973 }
4974
4975 // It's not a constant expression. Produce an appropriate diagnostic.
4976 if (Notes.size() == 1 &&
4977 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4978 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4979 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004980 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004981 << CCE << From->getSourceRange();
4982 for (unsigned I = 0; I < Notes.size(); ++I)
4983 Diag(Notes[I].first, Notes[I].second);
4984 }
Richard Smith911e1422012-01-30 22:27:01 +00004985 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004986}
4987
John McCallfec112d2011-09-09 06:11:02 +00004988/// dropPointerConversions - If the given standard conversion sequence
4989/// involves any pointer conversions, remove them. This may change
4990/// the result type of the conversion sequence.
4991static void dropPointerConversion(StandardConversionSequence &SCS) {
4992 if (SCS.Second == ICK_Pointer_Conversion) {
4993 SCS.Second = ICK_Identity;
4994 SCS.Third = ICK_Identity;
4995 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4996 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004997}
John McCall5c32be02010-08-24 20:38:10 +00004998
John McCallfec112d2011-09-09 06:11:02 +00004999/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5000/// convert the expression From to an Objective-C pointer type.
5001static ImplicitConversionSequence
5002TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5003 // Do an implicit conversion to 'id'.
5004 QualType Ty = S.Context.getObjCIdType();
5005 ImplicitConversionSequence ICS
5006 = TryImplicitConversion(S, From, Ty,
5007 // FIXME: Are these flags correct?
5008 /*SuppressUserConversions=*/false,
5009 /*AllowExplicit=*/true,
5010 /*InOverloadResolution=*/false,
5011 /*CStyle=*/false,
5012 /*AllowObjCWritebackConversion=*/false);
5013
5014 // Strip off any final conversions to 'id'.
5015 switch (ICS.getKind()) {
5016 case ImplicitConversionSequence::BadConversion:
5017 case ImplicitConversionSequence::AmbiguousConversion:
5018 case ImplicitConversionSequence::EllipsisConversion:
5019 break;
5020
5021 case ImplicitConversionSequence::UserDefinedConversion:
5022 dropPointerConversion(ICS.UserDefined.After);
5023 break;
5024
5025 case ImplicitConversionSequence::StandardConversion:
5026 dropPointerConversion(ICS.Standard);
5027 break;
5028 }
5029
5030 return ICS;
5031}
5032
5033/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5034/// conversion of the expression From to an Objective-C pointer type.
5035ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005036 if (checkPlaceholderForOverload(*this, From))
5037 return ExprError();
5038
John McCall8b07ec22010-05-15 11:32:37 +00005039 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005040 ImplicitConversionSequence ICS =
5041 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005042 if (!ICS.isBad())
5043 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005044 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005045}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005046
Richard Smith8dd34252012-02-04 07:07:42 +00005047/// Determine whether the provided type is an integral type, or an enumeration
5048/// type of a permitted flavor.
5049static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5050 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5051 : T->isIntegralOrUnscopedEnumerationType();
5052}
5053
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005055/// enumeration type.
5056///
5057/// This routine will attempt to convert an expression of class type to an
5058/// integral or enumeration type, if that class type only has a single
5059/// conversion to an integral or enumeration type.
5060///
Douglas Gregor4799d032010-06-30 00:20:43 +00005061/// \param Loc The source location of the construct that requires the
5062/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063///
James Dennett18348b62012-06-22 08:52:37 +00005064/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005065///
James Dennett18348b62012-06-22 08:52:37 +00005066/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005067///
Richard Smith8dd34252012-02-04 07:07:42 +00005068/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5069/// enumerations should be considered.
5070///
Douglas Gregor4799d032010-06-30 00:20:43 +00005071/// \returns The expression, converted to an integral or enumeration type if
5072/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073ExprResult
John McCallb268a282010-08-23 23:25:46 +00005074Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005075 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005076 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005077 // We can't perform any more checking for type-dependent expressions.
5078 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005079 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
Eli Friedman1da70392012-01-26 00:26:18 +00005081 // Process placeholders immediately.
5082 if (From->hasPlaceholderType()) {
5083 ExprResult result = CheckPlaceholderExpr(From);
5084 if (result.isInvalid()) return result;
5085 From = result.take();
5086 }
5087
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005088 // If the expression already has integral or enumeration type, we're golden.
5089 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005090 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005091 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005092
5093 // FIXME: Check for missing '()' if T is a function type?
5094
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095 // 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 +00005096 // expression of integral or enumeration type.
5097 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005098 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005099 if (!Diagnoser.Suppress)
5100 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005101 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005104 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005105 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005106 ICEConvertDiagnoser &Diagnoser;
5107 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005108
Douglas Gregore2b37442012-05-04 22:38:52 +00005109 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5110 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005111
5112 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005113 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005114 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005115 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005116
5117 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005118 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005120 // Look for a conversion to an integral or enumeration type.
5121 UnresolvedSet<4> ViableConversions;
5122 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005123 std::pair<CXXRecordDecl::conversion_iterator,
5124 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005125 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005127 bool HadMultipleCandidates
5128 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005129
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005130 for (CXXRecordDecl::conversion_iterator
5131 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005133 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5134 if (isIntegralOrEnumerationType(
5135 Conversion->getConversionType().getNonReferenceType(),
5136 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005137 if (Conversion->isExplicit())
5138 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5139 else
5140 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5141 }
Richard Smith8dd34252012-02-04 07:07:42 +00005142 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005145 switch (ViableConversions.size()) {
5146 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005147 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005148 DeclAccessPair Found = ExplicitConversions[0];
5149 CXXConversionDecl *Conversion
5150 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005152 // The user probably meant to invoke the given explicit
5153 // conversion; use it.
5154 QualType ConvTy
5155 = Conversion->getConversionType().getNonReferenceType();
5156 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005157 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Douglas Gregore2b37442012-05-04 22:38:52 +00005159 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005160 << FixItHint::CreateInsertion(From->getLocStart(),
5161 "static_cast<" + TypeStr + ">(")
5162 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5163 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005164 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165
5166 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005167 // explicit conversion function.
5168 if (isSFINAEContext())
5169 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005171 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005172 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5173 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005174 if (Result.isInvalid())
5175 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005176 // Record usage of conversion in an implicit cast.
5177 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5178 CK_UserDefinedConversion,
5179 Result.get(), 0,
5180 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005183 // We'll complain below about a non-integral condition type.
5184 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005186 case 1: {
5187 // Apply this conversion.
5188 DeclAccessPair Found = ViableConversions[0];
5189 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005190
Douglas Gregor4799d032010-06-30 00:20:43 +00005191 CXXConversionDecl *Conversion
5192 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5193 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005195 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005196 if (isSFINAEContext())
5197 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005198
Douglas Gregore2b37442012-05-04 22:38:52 +00005199 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5200 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005203 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5204 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005205 if (Result.isInvalid())
5206 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005207 // Record usage of conversion in an implicit cast.
5208 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5209 CK_UserDefinedConversion,
5210 Result.get(), 0,
5211 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005212 break;
5213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005215 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005216 if (Diagnoser.Suppress)
5217 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005218
Douglas Gregore2b37442012-05-04 22:38:52 +00005219 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005220 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5221 CXXConversionDecl *Conv
5222 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5223 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005224 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005225 }
John McCallb268a282010-08-23 23:25:46 +00005226 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228
Richard Smithf4c51d92012-02-04 09:53:13 +00005229 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005230 !Diagnoser.Suppress) {
5231 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5232 << From->getSourceRange();
5233 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005234
Eli Friedman1da70392012-01-26 00:26:18 +00005235 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005236}
5237
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005238/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005239/// candidate functions, using the given function call arguments. If
5240/// @p SuppressUserConversions, then don't allow user-defined
5241/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005242///
James Dennett2a4d13c2012-06-15 07:13:21 +00005243/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005244/// based on an incomplete set of function arguments. This feature is used by
5245/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005246void
5247Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005248 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005249 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005250 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005251 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005252 bool PartialOverloading,
5253 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005254 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005255 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005256 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005257 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005258 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005259
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005260 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005261 if (!isa<CXXConstructorDecl>(Method)) {
5262 // If we get here, it's because we're calling a member function
5263 // that is named without a member access expression (e.g.,
5264 // "this->f") that was either written explicitly or created
5265 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005266 // function, e.g., X::f(). We use an empty type for the implied
5267 // object argument (C++ [over.call.func]p3), and the acting context
5268 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005269 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005270 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005271 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005272 return;
5273 }
5274 // We treat a constructor like a non-member function, since its object
5275 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005276 }
5277
Douglas Gregorff7028a2009-11-13 23:59:09 +00005278 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005279 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005280
Douglas Gregor27381f32009-11-23 12:27:39 +00005281 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005282 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005283
Douglas Gregorffe14e32009-11-14 01:20:54 +00005284 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5285 // C++ [class.copy]p3:
5286 // A member function template is never instantiated to perform the copy
5287 // of a class object to an object of its class type.
5288 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005289 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005290 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005291 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5292 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005293 return;
5294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005296 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005297 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005298 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005299 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005300 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005301 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005302 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005303 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005305 unsigned NumArgsInProto = Proto->getNumArgs();
5306
5307 // (C++ 13.3.2p2): A candidate function having fewer than m
5308 // parameters is viable only if it has an ellipsis in its parameter
5309 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005310 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005311 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005312 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005313 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005314 return;
5315 }
5316
5317 // (C++ 13.3.2p2): A candidate function having more than m parameters
5318 // is viable only if the (m+1)st parameter has a default argument
5319 // (8.3.6). For the purposes of overload resolution, the
5320 // parameter list is truncated on the right, so that there are
5321 // exactly m parameters.
5322 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005323 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005324 // Not enough arguments.
5325 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005326 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005327 return;
5328 }
5329
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005330 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005331 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005332 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5333 if (CheckCUDATarget(Caller, Function)) {
5334 Candidate.Viable = false;
5335 Candidate.FailureKind = ovl_fail_bad_target;
5336 return;
5337 }
5338
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005339 // Determine the implicit conversion sequences for each of the
5340 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005341 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005342 if (ArgIdx < NumArgsInProto) {
5343 // (C++ 13.3.2p3): for F to be a viable function, there shall
5344 // exist for each argument an implicit conversion sequence
5345 // (13.3.3.1) that converts that argument to the corresponding
5346 // parameter of F.
5347 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005348 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005349 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005351 /*InOverloadResolution=*/true,
5352 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005353 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005354 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005355 if (Candidate.Conversions[ArgIdx].isBad()) {
5356 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005357 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005358 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005359 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005360 } else {
5361 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5362 // argument for which there is no corresponding parameter is
5363 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005364 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005365 }
5366 }
5367}
5368
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005369/// \brief Add all of the function declarations in the given function set to
5370/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005371void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005372 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005373 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005374 bool SuppressUserConversions,
5375 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005376 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005377 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005379 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005380 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005381 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005382 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005383 Args.slice(1), CandidateSet,
5384 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005385 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005386 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005387 SuppressUserConversions);
5388 } else {
John McCalla0296f72010-03-19 07:35:19 +00005389 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005390 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5391 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005392 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005393 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005394 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005395 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005396 Args[0]->Classify(Context), Args.slice(1),
5397 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005398 else
John McCalla0296f72010-03-19 07:35:19 +00005399 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005400 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005401 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005402 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005403 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005404}
5405
John McCallf0f1cf02009-11-17 07:50:12 +00005406/// AddMethodCandidate - Adds a named decl (which is some kind of
5407/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005408void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005409 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005410 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005411 Expr **Args, unsigned NumArgs,
5412 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005413 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005414 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005415 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005416
5417 if (isa<UsingShadowDecl>(Decl))
5418 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
John McCallf0f1cf02009-11-17 07:50:12 +00005420 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5421 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5422 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005423 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5424 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005425 ObjectType, ObjectClassification,
5426 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005427 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005428 } else {
John McCalla0296f72010-03-19 07:35:19 +00005429 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005430 ObjectType, ObjectClassification,
5431 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005432 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005433 }
5434}
5435
Douglas Gregor436424c2008-11-18 23:14:02 +00005436/// AddMethodCandidate - Adds the given C++ member function to the set
5437/// of candidate functions, using the given function call arguments
5438/// and the object argument (@c Object). For example, in a call
5439/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5440/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5441/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005442/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005443void
John McCalla0296f72010-03-19 07:35:19 +00005444Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005445 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005446 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005447 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005448 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005449 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005450 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005451 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005452 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005453 assert(!isa<CXXConstructorDecl>(Method) &&
5454 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005455
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005456 if (!CandidateSet.isNewCandidate(Method))
5457 return;
5458
Douglas Gregor27381f32009-11-23 12:27:39 +00005459 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005460 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005461
Douglas Gregor436424c2008-11-18 23:14:02 +00005462 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005463 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005464 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005465 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005466 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005467 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005468 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005469
5470 unsigned NumArgsInProto = Proto->getNumArgs();
5471
5472 // (C++ 13.3.2p2): A candidate function having fewer than m
5473 // parameters is viable only if it has an ellipsis in its parameter
5474 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005475 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005476 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005477 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005478 return;
5479 }
5480
5481 // (C++ 13.3.2p2): A candidate function having more than m parameters
5482 // is viable only if the (m+1)st parameter has a default argument
5483 // (8.3.6). For the purposes of overload resolution, the
5484 // parameter list is truncated on the right, so that there are
5485 // exactly m parameters.
5486 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005487 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005488 // Not enough arguments.
5489 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005490 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005491 return;
5492 }
5493
5494 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005495
John McCall6e9f8f62009-12-03 04:06:58 +00005496 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005497 // The implicit object argument is ignored.
5498 Candidate.IgnoreObjectArgument = true;
5499 else {
5500 // Determine the implicit conversion sequence for the object
5501 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005502 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005503 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5504 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005505 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005506 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005507 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005508 return;
5509 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005510 }
5511
5512 // Determine the implicit conversion sequences for each of the
5513 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005514 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005515 if (ArgIdx < NumArgsInProto) {
5516 // (C++ 13.3.2p3): for F to be a viable function, there shall
5517 // exist for each argument an implicit conversion sequence
5518 // (13.3.3.1) that converts that argument to the corresponding
5519 // parameter of F.
5520 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005521 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005522 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005524 /*InOverloadResolution=*/true,
5525 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005526 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005527 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005528 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005529 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005530 break;
5531 }
5532 } else {
5533 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5534 // argument for which there is no corresponding parameter is
5535 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005536 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005537 }
5538 }
5539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540
Douglas Gregor97628d62009-08-21 00:16:32 +00005541/// \brief Add a C++ member function template as a candidate to the candidate
5542/// set, using template argument deduction to produce an appropriate member
5543/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005544void
Douglas Gregor97628d62009-08-21 00:16:32 +00005545Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005546 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005547 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005548 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005549 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005550 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005551 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005552 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005553 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005554 if (!CandidateSet.isNewCandidate(MethodTmpl))
5555 return;
5556
Douglas Gregor97628d62009-08-21 00:16:32 +00005557 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005558 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005559 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005560 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005561 // candidate functions in the usual way.113) A given name can refer to one
5562 // or more function templates and also to a set of overloaded non-template
5563 // functions. In such a case, the candidate functions generated from each
5564 // function template are combined with the set of non-template candidate
5565 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005566 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005567 FunctionDecl *Specialization = 0;
5568 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005569 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5570 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005571 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005572 Candidate.FoundDecl = FoundDecl;
5573 Candidate.Function = MethodTmpl->getTemplatedDecl();
5574 Candidate.Viable = false;
5575 Candidate.FailureKind = ovl_fail_bad_deduction;
5576 Candidate.IsSurrogate = false;
5577 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005578 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005580 Info);
5581 return;
5582 }
Mike Stump11289f42009-09-09 15:08:12 +00005583
Douglas Gregor97628d62009-08-21 00:16:32 +00005584 // Add the function template specialization produced by template argument
5585 // deduction as a candidate.
5586 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005587 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005588 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005589 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005590 ActingContext, ObjectType, ObjectClassification, Args,
5591 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005592}
5593
Douglas Gregor05155d82009-08-21 23:19:43 +00005594/// \brief Add a C++ function template specialization as a candidate
5595/// in the candidate set, using template argument deduction to produce
5596/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005597void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005598Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005599 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005600 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005601 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005602 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005603 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005604 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5605 return;
5606
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005607 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005608 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005609 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005610 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005611 // candidate functions in the usual way.113) A given name can refer to one
5612 // or more function templates and also to a set of overloaded non-template
5613 // functions. In such a case, the candidate functions generated from each
5614 // function template are combined with the set of non-template candidate
5615 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005616 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005617 FunctionDecl *Specialization = 0;
5618 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005619 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5620 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005621 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005622 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005623 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5624 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005625 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005626 Candidate.IsSurrogate = false;
5627 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005628 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005630 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005631 return;
5632 }
Mike Stump11289f42009-09-09 15:08:12 +00005633
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005634 // Add the function template specialization produced by template argument
5635 // deduction as a candidate.
5636 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005637 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005638 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005639}
Mike Stump11289f42009-09-09 15:08:12 +00005640
Douglas Gregora1f013e2008-11-07 22:36:19 +00005641/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005642/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005643/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005644/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005645/// (which may or may not be the same type as the type that the
5646/// conversion function produces).
5647void
5648Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005649 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005650 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005651 Expr *From, QualType ToType,
5652 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005653 assert(!Conversion->getDescribedFunctionTemplate() &&
5654 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005655 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005656 if (!CandidateSet.isNewCandidate(Conversion))
5657 return;
5658
Douglas Gregor27381f32009-11-23 12:27:39 +00005659 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005660 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005661
Douglas Gregora1f013e2008-11-07 22:36:19 +00005662 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005663 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005664 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005665 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005666 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005667 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005668 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005669 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005670 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005671 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005672 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005673
Douglas Gregor6affc782010-08-19 15:37:02 +00005674 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675 // For conversion functions, the function is considered to be a member of
5676 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005677 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005678 //
5679 // Determine the implicit conversion sequence for the implicit
5680 // object parameter.
5681 QualType ImplicitParamType = From->getType();
5682 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5683 ImplicitParamType = FromPtrType->getPointeeType();
5684 CXXRecordDecl *ConversionContext
5685 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005687 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688 = TryObjectArgumentInitialization(*this, From->getType(),
5689 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005690 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
John McCall0d1da222010-01-12 00:44:57 +00005692 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005693 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005694 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005695 return;
5696 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005697
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005698 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005699 // derived to base as such conversions are given Conversion Rank. They only
5700 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5701 QualType FromCanon
5702 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5703 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5704 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5705 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005706 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005707 return;
5708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
Douglas Gregora1f013e2008-11-07 22:36:19 +00005710 // To determine what the conversion from the result of calling the
5711 // conversion function to the type we're eventually trying to
5712 // convert to (ToType), we need to synthesize a call to the
5713 // conversion function and attempt copy initialization from it. This
5714 // makes sure that we get the right semantics with respect to
5715 // lvalues/rvalues and the type. Fortunately, we can allocate this
5716 // call on the stack and we don't need its arguments to be
5717 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005718 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005719 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005720 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5721 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005722 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005723 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005724
Richard Smith48d24642011-07-13 22:53:21 +00005725 QualType ConversionType = Conversion->getConversionType();
5726 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005727 Candidate.Viable = false;
5728 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5729 return;
5730 }
5731
Richard Smith48d24642011-07-13 22:53:21 +00005732 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005733
Mike Stump11289f42009-09-09 15:08:12 +00005734 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005735 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5736 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005737 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramerc215e762012-08-24 11:54:20 +00005738 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005739 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005740 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005741 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005742 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005743 /*InOverloadResolution=*/false,
5744 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005745
John McCall0d1da222010-01-12 00:44:57 +00005746 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005747 case ImplicitConversionSequence::StandardConversion:
5748 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005750 // C++ [over.ics.user]p3:
5751 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005752 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005753 // shall have exact match rank.
5754 if (Conversion->getPrimaryTemplate() &&
5755 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5756 Candidate.Viable = false;
5757 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Douglas Gregorcba72b12011-01-21 05:18:22 +00005760 // C++0x [dcl.init.ref]p5:
5761 // In the second case, if the reference is an rvalue reference and
5762 // the second standard conversion sequence of the user-defined
5763 // conversion sequence includes an lvalue-to-rvalue conversion, the
5764 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005766 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5767 Candidate.Viable = false;
5768 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5769 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005770 break;
5771
5772 case ImplicitConversionSequence::BadConversion:
5773 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005774 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005775 break;
5776
5777 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005778 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005779 "Can only end up with a standard conversion sequence or failure");
5780 }
5781}
5782
Douglas Gregor05155d82009-08-21 23:19:43 +00005783/// \brief Adds a conversion function template specialization
5784/// candidate to the overload set, using template argument deduction
5785/// to deduce the template arguments of the conversion function
5786/// template from the type that we are converting to (C++
5787/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005788void
Douglas Gregor05155d82009-08-21 23:19:43 +00005789Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005790 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005791 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005792 Expr *From, QualType ToType,
5793 OverloadCandidateSet &CandidateSet) {
5794 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5795 "Only conversion function templates permitted here");
5796
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005797 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5798 return;
5799
Craig Toppere6706e42012-09-19 02:26:47 +00005800 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005801 CXXConversionDecl *Specialization = 0;
5802 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005803 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005804 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005805 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005806 Candidate.FoundDecl = FoundDecl;
5807 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5808 Candidate.Viable = false;
5809 Candidate.FailureKind = ovl_fail_bad_deduction;
5810 Candidate.IsSurrogate = false;
5811 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005812 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005813 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005814 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005815 return;
5816 }
Mike Stump11289f42009-09-09 15:08:12 +00005817
Douglas Gregor05155d82009-08-21 23:19:43 +00005818 // Add the conversion function template specialization produced by
5819 // template argument deduction as a candidate.
5820 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005821 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005822 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005823}
5824
Douglas Gregorab7897a2008-11-19 22:57:39 +00005825/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5826/// converts the given @c Object to a function pointer via the
5827/// conversion function @c Conversion, and then attempts to call it
5828/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5829/// the type of function that we'll eventually be calling.
5830void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005831 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005832 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005833 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005834 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005835 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005836 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005837 if (!CandidateSet.isNewCandidate(Conversion))
5838 return;
5839
Douglas Gregor27381f32009-11-23 12:27:39 +00005840 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005841 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005842
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005843 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005844 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005845 Candidate.Function = 0;
5846 Candidate.Surrogate = Conversion;
5847 Candidate.Viable = true;
5848 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005849 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005850 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005851
5852 // Determine the implicit conversion sequence for the implicit
5853 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005854 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005855 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005856 Object->Classify(Context),
5857 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005858 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005859 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005860 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005861 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005862 return;
5863 }
5864
5865 // The first conversion is actually a user-defined conversion whose
5866 // first conversion is ObjectInit's standard conversion (which is
5867 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005868 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005869 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005870 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005871 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005872 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005873 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005874 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005875 = Candidate.Conversions[0].UserDefined.Before;
5876 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5877
Mike Stump11289f42009-09-09 15:08:12 +00005878 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005879 unsigned NumArgsInProto = Proto->getNumArgs();
5880
5881 // (C++ 13.3.2p2): A candidate function having fewer than m
5882 // parameters is viable only if it has an ellipsis in its parameter
5883 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005884 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005885 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005886 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005887 return;
5888 }
5889
5890 // Function types don't have any default arguments, so just check if
5891 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005892 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005893 // Not enough arguments.
5894 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005895 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005896 return;
5897 }
5898
5899 // Determine the implicit conversion sequences for each of the
5900 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005901 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005902 if (ArgIdx < NumArgsInProto) {
5903 // (C++ 13.3.2p3): for F to be a viable function, there shall
5904 // exist for each argument an implicit conversion sequence
5905 // (13.3.3.1) that converts that argument to the corresponding
5906 // parameter of F.
5907 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005908 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005909 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005910 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005911 /*InOverloadResolution=*/false,
5912 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005913 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005914 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005915 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005916 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005917 break;
5918 }
5919 } else {
5920 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5921 // argument for which there is no corresponding parameter is
5922 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005923 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005924 }
5925 }
5926}
5927
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005928/// \brief Add overload candidates for overloaded operators that are
5929/// member functions.
5930///
5931/// Add the overloaded operator candidates that are member functions
5932/// for the operator Op that was used in an operator expression such
5933/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5934/// CandidateSet will store the added overload candidates. (C++
5935/// [over.match.oper]).
5936void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5937 SourceLocation OpLoc,
5938 Expr **Args, unsigned NumArgs,
5939 OverloadCandidateSet& CandidateSet,
5940 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005941 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5942
5943 // C++ [over.match.oper]p3:
5944 // For a unary operator @ with an operand of a type whose
5945 // cv-unqualified version is T1, and for a binary operator @ with
5946 // a left operand of a type whose cv-unqualified version is T1 and
5947 // a right operand of a type whose cv-unqualified version is T2,
5948 // three sets of candidate functions, designated member
5949 // candidates, non-member candidates and built-in candidates, are
5950 // constructed as follows:
5951 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005952
5953 // -- If T1 is a class type, the set of member candidates is the
5954 // result of the qualified lookup of T1::operator@
5955 // (13.3.1.1.1); otherwise, the set of member candidates is
5956 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005957 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005958 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005959 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005960 return;
Mike Stump11289f42009-09-09 15:08:12 +00005961
John McCall27b18f82009-11-17 02:14:36 +00005962 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5963 LookupQualifiedName(Operators, T1Rec->getDecl());
5964 Operators.suppressDiagnostics();
5965
Mike Stump11289f42009-09-09 15:08:12 +00005966 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005967 OperEnd = Operators.end();
5968 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005969 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005970 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005971 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005972 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005973 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005974 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005975}
5976
Douglas Gregora11693b2008-11-12 17:17:38 +00005977/// AddBuiltinCandidate - Add a candidate for a built-in
5978/// operator. ResultTy and ParamTys are the result and parameter types
5979/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005980/// arguments being passed to the candidate. IsAssignmentOperator
5981/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005982/// operator. NumContextualBoolArguments is the number of arguments
5983/// (at the beginning of the argument list) that will be contextually
5984/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005985void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005986 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005987 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005988 bool IsAssignmentOperator,
5989 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005990 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005991 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005992
Douglas Gregora11693b2008-11-12 17:17:38 +00005993 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005994 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005995 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005996 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005997 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005998 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005999 Candidate.BuiltinTypes.ResultTy = ResultTy;
6000 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6001 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6002
6003 // Determine the implicit conversion sequences for each of the
6004 // arguments.
6005 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006006 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00006007 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006008 // C++ [over.match.oper]p4:
6009 // For the built-in assignment operators, conversions of the
6010 // left operand are restricted as follows:
6011 // -- no temporaries are introduced to hold the left operand, and
6012 // -- no user-defined conversions are applied to the left
6013 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006014 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006015 //
6016 // We block these conversions by turning off user-defined
6017 // conversions, since that is the only way that initialization of
6018 // a reference to a non-class type can occur from something that
6019 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006020 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006021 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006022 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006023 Candidate.Conversions[ArgIdx]
6024 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006025 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006026 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006027 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006028 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006029 /*InOverloadResolution=*/false,
6030 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006031 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006032 }
John McCall0d1da222010-01-12 00:44:57 +00006033 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006034 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006035 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006036 break;
6037 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006038 }
6039}
6040
6041/// BuiltinCandidateTypeSet - A set of types that will be used for the
6042/// candidate operator functions for built-in operators (C++
6043/// [over.built]). The types are separated into pointer types and
6044/// enumeration types.
6045class BuiltinCandidateTypeSet {
6046 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006047 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006048
6049 /// PointerTypes - The set of pointer types that will be used in the
6050 /// built-in candidates.
6051 TypeSet PointerTypes;
6052
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006053 /// MemberPointerTypes - The set of member pointer types that will be
6054 /// used in the built-in candidates.
6055 TypeSet MemberPointerTypes;
6056
Douglas Gregora11693b2008-11-12 17:17:38 +00006057 /// EnumerationTypes - The set of enumeration types that will be
6058 /// used in the built-in candidates.
6059 TypeSet EnumerationTypes;
6060
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006061 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006062 /// candidates.
6063 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006064
6065 /// \brief A flag indicating non-record types are viable candidates
6066 bool HasNonRecordTypes;
6067
6068 /// \brief A flag indicating whether either arithmetic or enumeration types
6069 /// were present in the candidate set.
6070 bool HasArithmeticOrEnumeralTypes;
6071
Douglas Gregor80af3132011-05-21 23:15:46 +00006072 /// \brief A flag indicating whether the nullptr type was present in the
6073 /// candidate set.
6074 bool HasNullPtrType;
6075
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006076 /// Sema - The semantic analysis instance where we are building the
6077 /// candidate type set.
6078 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006079
Douglas Gregora11693b2008-11-12 17:17:38 +00006080 /// Context - The AST context in which we will build the type sets.
6081 ASTContext &Context;
6082
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006083 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6084 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006085 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006086
6087public:
6088 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006089 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006090
Mike Stump11289f42009-09-09 15:08:12 +00006091 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006092 : HasNonRecordTypes(false),
6093 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006094 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006095 SemaRef(SemaRef),
6096 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006097
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006098 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006099 SourceLocation Loc,
6100 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006101 bool AllowExplicitConversions,
6102 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006103
6104 /// pointer_begin - First pointer type found;
6105 iterator pointer_begin() { return PointerTypes.begin(); }
6106
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006107 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006108 iterator pointer_end() { return PointerTypes.end(); }
6109
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006110 /// member_pointer_begin - First member pointer type found;
6111 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6112
6113 /// member_pointer_end - Past the last member pointer type found;
6114 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6115
Douglas Gregora11693b2008-11-12 17:17:38 +00006116 /// enumeration_begin - First enumeration type found;
6117 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6118
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006119 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006120 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006121
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006122 iterator vector_begin() { return VectorTypes.begin(); }
6123 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006124
6125 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6126 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006127 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006128};
6129
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006130/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006131/// the set of pointer types along with any more-qualified variants of
6132/// that type. For example, if @p Ty is "int const *", this routine
6133/// will add "int const *", "int const volatile *", "int const
6134/// restrict *", and "int const volatile restrict *" to the set of
6135/// pointer types. Returns true if the add of @p Ty itself succeeded,
6136/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006137///
6138/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006139bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006140BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6141 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006142
Douglas Gregora11693b2008-11-12 17:17:38 +00006143 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006144 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006145 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006146
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006147 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006148 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006149 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006150 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006151 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6152 PointeeTy = PTy->getPointeeType();
6153 buildObjCPtr = true;
6154 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006155 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006156 }
6157
Sebastian Redl4990a632009-11-18 20:39:26 +00006158 // Don't add qualified variants of arrays. For one, they're not allowed
6159 // (the qualifier would sink to the element type), and for another, the
6160 // only overload situation where it matters is subscript or pointer +- int,
6161 // and those shouldn't have qualifier variants anyway.
6162 if (PointeeTy->isArrayType())
6163 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006164
John McCall8ccfcb52009-09-24 19:53:00 +00006165 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006166 bool hasVolatile = VisibleQuals.hasVolatile();
6167 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168
John McCall8ccfcb52009-09-24 19:53:00 +00006169 // Iterate through all strict supersets of BaseCVR.
6170 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6171 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006172 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006173 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006174
6175 // Skip over restrict if no restrict found anywhere in the types, or if
6176 // the type cannot be restrict-qualified.
6177 if ((CVR & Qualifiers::Restrict) &&
6178 (!hasRestrict ||
6179 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6180 continue;
6181
6182 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006183 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006184
6185 // Build qualified pointer type.
6186 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006187 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006188 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006189 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006190 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6191
6192 // Insert qualified pointer type.
6193 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006194 }
6195
6196 return true;
6197}
6198
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006199/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6200/// to the set of pointer types along with any more-qualified variants of
6201/// that type. For example, if @p Ty is "int const *", this routine
6202/// will add "int const *", "int const volatile *", "int const
6203/// restrict *", and "int const volatile restrict *" to the set of
6204/// pointer types. Returns true if the add of @p Ty itself succeeded,
6205/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006206///
6207/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006208bool
6209BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6210 QualType Ty) {
6211 // Insert this type.
6212 if (!MemberPointerTypes.insert(Ty))
6213 return false;
6214
John McCall8ccfcb52009-09-24 19:53:00 +00006215 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6216 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006217
John McCall8ccfcb52009-09-24 19:53:00 +00006218 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006219 // Don't add qualified variants of arrays. For one, they're not allowed
6220 // (the qualifier would sink to the element type), and for another, the
6221 // only overload situation where it matters is subscript or pointer +- int,
6222 // and those shouldn't have qualifier variants anyway.
6223 if (PointeeTy->isArrayType())
6224 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006225 const Type *ClassTy = PointerTy->getClass();
6226
6227 // Iterate through all strict supersets of the pointee type's CVR
6228 // qualifiers.
6229 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6230 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6231 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006232
John McCall8ccfcb52009-09-24 19:53:00 +00006233 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006234 MemberPointerTypes.insert(
6235 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006236 }
6237
6238 return true;
6239}
6240
Douglas Gregora11693b2008-11-12 17:17:38 +00006241/// AddTypesConvertedFrom - Add each of the types to which the type @p
6242/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006243/// primarily interested in pointer types and enumeration types. We also
6244/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006245/// AllowUserConversions is true if we should look at the conversion
6246/// functions of a class type, and AllowExplicitConversions if we
6247/// should also include the explicit conversion functions of a class
6248/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006249void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006250BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006251 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006252 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006253 bool AllowExplicitConversions,
6254 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006255 // Only deal with canonical types.
6256 Ty = Context.getCanonicalType(Ty);
6257
6258 // Look through reference types; they aren't part of the type of an
6259 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006260 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006261 Ty = RefTy->getPointeeType();
6262
John McCall33ddac02011-01-19 10:06:00 +00006263 // If we're dealing with an array type, decay to the pointer.
6264 if (Ty->isArrayType())
6265 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6266
6267 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006268 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006269
Chandler Carruth00a38332010-12-13 01:44:01 +00006270 // Flag if we ever add a non-record type.
6271 const RecordType *TyRec = Ty->getAs<RecordType>();
6272 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6273
Chandler Carruth00a38332010-12-13 01:44:01 +00006274 // Flag if we encounter an arithmetic type.
6275 HasArithmeticOrEnumeralTypes =
6276 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6277
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006278 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6279 PointerTypes.insert(Ty);
6280 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006281 // Insert our type, and its more-qualified variants, into the set
6282 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006283 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006284 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006285 } else if (Ty->isMemberPointerType()) {
6286 // Member pointers are far easier, since the pointee can't be converted.
6287 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6288 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006289 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006290 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006291 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006292 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006293 // We treat vector types as arithmetic types in many contexts as an
6294 // extension.
6295 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006296 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006297 } else if (Ty->isNullPtrType()) {
6298 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006299 } else if (AllowUserConversions && TyRec) {
6300 // No conversion functions in incomplete types.
6301 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6302 return;
Mike Stump11289f42009-09-09 15:08:12 +00006303
Chandler Carruth00a38332010-12-13 01:44:01 +00006304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006305 std::pair<CXXRecordDecl::conversion_iterator,
6306 CXXRecordDecl::conversion_iterator>
6307 Conversions = ClassDecl->getVisibleConversionFunctions();
6308 for (CXXRecordDecl::conversion_iterator
6309 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006310 NamedDecl *D = I.getDecl();
6311 if (isa<UsingShadowDecl>(D))
6312 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006313
Chandler Carruth00a38332010-12-13 01:44:01 +00006314 // Skip conversion function templates; they don't tell us anything
6315 // about which builtin types we can convert to.
6316 if (isa<FunctionTemplateDecl>(D))
6317 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006318
Chandler Carruth00a38332010-12-13 01:44:01 +00006319 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6320 if (AllowExplicitConversions || !Conv->isExplicit()) {
6321 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6322 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006323 }
6324 }
6325 }
6326}
6327
Douglas Gregor84605ae2009-08-24 13:43:27 +00006328/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6329/// the volatile- and non-volatile-qualified assignment operators for the
6330/// given type to the candidate set.
6331static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6332 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006333 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006334 unsigned NumArgs,
6335 OverloadCandidateSet &CandidateSet) {
6336 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006337
Douglas Gregor84605ae2009-08-24 13:43:27 +00006338 // T& operator=(T&, T)
6339 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6340 ParamTypes[1] = T;
6341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6342 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006343
Douglas Gregor84605ae2009-08-24 13:43:27 +00006344 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6345 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006346 ParamTypes[0]
6347 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006348 ParamTypes[1] = T;
6349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006350 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006351 }
6352}
Mike Stump11289f42009-09-09 15:08:12 +00006353
Sebastian Redl1054fae2009-10-25 17:03:50 +00006354/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6355/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006356static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6357 Qualifiers VRQuals;
6358 const RecordType *TyRec;
6359 if (const MemberPointerType *RHSMPType =
6360 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006361 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006362 else
6363 TyRec = ArgExpr->getType()->getAs<RecordType>();
6364 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006365 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006366 VRQuals.addVolatile();
6367 VRQuals.addRestrict();
6368 return VRQuals;
6369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006370
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006371 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006372 if (!ClassDecl->hasDefinition())
6373 return VRQuals;
6374
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006375 std::pair<CXXRecordDecl::conversion_iterator,
6376 CXXRecordDecl::conversion_iterator>
6377 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006379 for (CXXRecordDecl::conversion_iterator
6380 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006381 NamedDecl *D = I.getDecl();
6382 if (isa<UsingShadowDecl>(D))
6383 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6384 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006385 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6386 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6387 CanTy = ResTypeRef->getPointeeType();
6388 // Need to go down the pointer/mempointer chain and add qualifiers
6389 // as see them.
6390 bool done = false;
6391 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006392 if (CanTy.isRestrictQualified())
6393 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006394 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6395 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006396 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006397 CanTy->getAs<MemberPointerType>())
6398 CanTy = ResTypeMPtr->getPointeeType();
6399 else
6400 done = true;
6401 if (CanTy.isVolatileQualified())
6402 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006403 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6404 return VRQuals;
6405 }
6406 }
6407 }
6408 return VRQuals;
6409}
John McCall52872982010-11-13 05:51:15 +00006410
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006411namespace {
John McCall52872982010-11-13 05:51:15 +00006412
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006413/// \brief Helper class to manage the addition of builtin operator overload
6414/// candidates. It provides shared state and utility methods used throughout
6415/// the process, as well as a helper method to add each group of builtin
6416/// operator overloads from the standard to a candidate set.
6417class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006418 // Common instance state available to all overload candidate addition methods.
6419 Sema &S;
6420 Expr **Args;
6421 unsigned NumArgs;
6422 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006423 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006424 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006425 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006426
Chandler Carruthc6586e52010-12-12 10:35:00 +00006427 // Define some constants used to index and iterate over the arithemetic types
6428 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006429 // The "promoted arithmetic types" are the arithmetic
6430 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006431 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006432 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006433 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006434 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006435 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006436 LastPromotedArithmeticType = 11;
6437 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006438
Chandler Carruthc6586e52010-12-12 10:35:00 +00006439 /// \brief Get the canonical type for a given arithmetic type index.
6440 CanQualType getArithmeticType(unsigned index) {
6441 assert(index < NumArithmeticTypes);
6442 static CanQualType ASTContext::* const
6443 ArithmeticTypes[NumArithmeticTypes] = {
6444 // Start of promoted types.
6445 &ASTContext::FloatTy,
6446 &ASTContext::DoubleTy,
6447 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006448
Chandler Carruthc6586e52010-12-12 10:35:00 +00006449 // Start of integral types.
6450 &ASTContext::IntTy,
6451 &ASTContext::LongTy,
6452 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006453 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006454 &ASTContext::UnsignedIntTy,
6455 &ASTContext::UnsignedLongTy,
6456 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006457 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006458 // End of promoted types.
6459
6460 &ASTContext::BoolTy,
6461 &ASTContext::CharTy,
6462 &ASTContext::WCharTy,
6463 &ASTContext::Char16Ty,
6464 &ASTContext::Char32Ty,
6465 &ASTContext::SignedCharTy,
6466 &ASTContext::ShortTy,
6467 &ASTContext::UnsignedCharTy,
6468 &ASTContext::UnsignedShortTy,
6469 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006470 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006471 };
6472 return S.Context.*ArithmeticTypes[index];
6473 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006474
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006475 /// \brief Gets the canonical type resulting from the usual arithemetic
6476 /// converions for the given arithmetic types.
6477 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6478 // Accelerator table for performing the usual arithmetic conversions.
6479 // The rules are basically:
6480 // - if either is floating-point, use the wider floating-point
6481 // - if same signedness, use the higher rank
6482 // - if same size, use unsigned of the higher rank
6483 // - use the larger type
6484 // These rules, together with the axiom that higher ranks are
6485 // never smaller, are sufficient to precompute all of these results
6486 // *except* when dealing with signed types of higher rank.
6487 // (we could precompute SLL x UI for all known platforms, but it's
6488 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006489 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006490 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006491 Dep=-1,
6492 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006493 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006494 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006495 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006496/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6497/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6498/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6499/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6500/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6501/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6502/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6503/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6504/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6505/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6506/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006507 };
6508
6509 assert(L < LastPromotedArithmeticType);
6510 assert(R < LastPromotedArithmeticType);
6511 int Idx = ConversionsTable[L][R];
6512
6513 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006514 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006515
6516 // Slow path: we need to compare widths.
6517 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006518 CanQualType LT = getArithmeticType(L),
6519 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006520 unsigned LW = S.Context.getIntWidth(LT),
6521 RW = S.Context.getIntWidth(RT);
6522
6523 // If they're different widths, use the signed type.
6524 if (LW > RW) return LT;
6525 else if (LW < RW) return RT;
6526
6527 // Otherwise, use the unsigned type of the signed type's rank.
6528 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6529 assert(L == SLL || R == SLL);
6530 return S.Context.UnsignedLongLongTy;
6531 }
6532
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006533 /// \brief Helper method to factor out the common pattern of adding overloads
6534 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006535 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006536 bool HasVolatile,
6537 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006538 QualType ParamTypes[2] = {
6539 S.Context.getLValueReferenceType(CandidateTy),
6540 S.Context.IntTy
6541 };
6542
6543 // Non-volatile version.
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 // Use a heuristic to reduce number of builtin candidates in the set:
6550 // add volatile version only if there are conversions to a volatile type.
6551 if (HasVolatile) {
6552 ParamTypes[0] =
6553 S.Context.getLValueReferenceType(
6554 S.Context.getVolatileType(CandidateTy));
6555 if (NumArgs == 1)
6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6557 else
6558 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6559 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006560
6561 // Add restrict version only if there are conversions to a restrict type
6562 // and our candidate type is a non-restrict-qualified pointer.
6563 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6564 !CandidateTy.isRestrictQualified()) {
6565 ParamTypes[0]
6566 = S.Context.getLValueReferenceType(
6567 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6568 if (NumArgs == 1)
6569 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6570 else
6571 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6572
6573 if (HasVolatile) {
6574 ParamTypes[0]
6575 = S.Context.getLValueReferenceType(
6576 S.Context.getCVRQualifiedType(CandidateTy,
6577 (Qualifiers::Volatile |
6578 Qualifiers::Restrict)));
6579 if (NumArgs == 1)
6580 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6581 CandidateSet);
6582 else
6583 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6584 }
6585 }
6586
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006587 }
6588
6589public:
6590 BuiltinOperatorOverloadBuilder(
6591 Sema &S, Expr **Args, unsigned NumArgs,
6592 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006593 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006594 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006595 OverloadCandidateSet &CandidateSet)
6596 : S(S), Args(Args), NumArgs(NumArgs),
6597 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006598 HasArithmeticOrEnumeralCandidateType(
6599 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006600 CandidateTypes(CandidateTypes),
6601 CandidateSet(CandidateSet) {
6602 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006603 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006604 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006605 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006606 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006607 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006608 assert(getArithmeticType(FirstPromotedArithmeticType)
6609 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006610 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006611 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006612 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006613 "Invalid last promoted arithmetic type");
6614 }
6615
6616 // C++ [over.built]p3:
6617 //
6618 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6619 // is either volatile or empty, there exist candidate operator
6620 // functions of the form
6621 //
6622 // VQ T& operator++(VQ T&);
6623 // T operator++(VQ T&, int);
6624 //
6625 // C++ [over.built]p4:
6626 //
6627 // For every pair (T, VQ), where T is an arithmetic type other
6628 // than bool, and VQ is either volatile or empty, there exist
6629 // candidate operator functions of the form
6630 //
6631 // VQ T& operator--(VQ T&);
6632 // T operator--(VQ T&, int);
6633 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006634 if (!HasArithmeticOrEnumeralCandidateType)
6635 return;
6636
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006637 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6638 Arith < NumArithmeticTypes; ++Arith) {
6639 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006640 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006641 VisibleTypeConversionsQuals.hasVolatile(),
6642 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006643 }
6644 }
6645
6646 // C++ [over.built]p5:
6647 //
6648 // For every pair (T, VQ), where T is a cv-qualified or
6649 // cv-unqualified object type, and VQ is either volatile or
6650 // empty, there exist candidate operator functions of the form
6651 //
6652 // T*VQ& operator++(T*VQ&);
6653 // T*VQ& operator--(T*VQ&);
6654 // T* operator++(T*VQ&, int);
6655 // T* operator--(T*VQ&, int);
6656 void addPlusPlusMinusMinusPointerOverloads() {
6657 for (BuiltinCandidateTypeSet::iterator
6658 Ptr = CandidateTypes[0].pointer_begin(),
6659 PtrEnd = CandidateTypes[0].pointer_end();
6660 Ptr != PtrEnd; ++Ptr) {
6661 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006662 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006663 continue;
6664
6665 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006666 (!(*Ptr).isVolatileQualified() &&
6667 VisibleTypeConversionsQuals.hasVolatile()),
6668 (!(*Ptr).isRestrictQualified() &&
6669 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006670 }
6671 }
6672
6673 // C++ [over.built]p6:
6674 // For every cv-qualified or cv-unqualified object type T, there
6675 // exist candidate operator functions of the form
6676 //
6677 // T& operator*(T*);
6678 //
6679 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006681 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006682 // T& operator*(T*);
6683 void addUnaryStarPointerOverloads() {
6684 for (BuiltinCandidateTypeSet::iterator
6685 Ptr = CandidateTypes[0].pointer_begin(),
6686 PtrEnd = CandidateTypes[0].pointer_end();
6687 Ptr != PtrEnd; ++Ptr) {
6688 QualType ParamTy = *Ptr;
6689 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006690 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6691 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692
Douglas Gregor02824322011-01-26 19:30:28 +00006693 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6694 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6695 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006697 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6698 &ParamTy, Args, 1, CandidateSet);
6699 }
6700 }
6701
6702 // C++ [over.built]p9:
6703 // For every promoted arithmetic type T, there exist candidate
6704 // operator functions of the form
6705 //
6706 // T operator+(T);
6707 // T operator-(T);
6708 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006709 if (!HasArithmeticOrEnumeralCandidateType)
6710 return;
6711
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006712 for (unsigned Arith = FirstPromotedArithmeticType;
6713 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006714 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006715 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6716 }
6717
6718 // Extension: We also add these operators for vector types.
6719 for (BuiltinCandidateTypeSet::iterator
6720 Vec = CandidateTypes[0].vector_begin(),
6721 VecEnd = CandidateTypes[0].vector_end();
6722 Vec != VecEnd; ++Vec) {
6723 QualType VecTy = *Vec;
6724 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6725 }
6726 }
6727
6728 // C++ [over.built]p8:
6729 // For every type T, there exist candidate operator functions of
6730 // the form
6731 //
6732 // T* operator+(T*);
6733 void addUnaryPlusPointerOverloads() {
6734 for (BuiltinCandidateTypeSet::iterator
6735 Ptr = CandidateTypes[0].pointer_begin(),
6736 PtrEnd = CandidateTypes[0].pointer_end();
6737 Ptr != PtrEnd; ++Ptr) {
6738 QualType ParamTy = *Ptr;
6739 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6740 }
6741 }
6742
6743 // C++ [over.built]p10:
6744 // For every promoted integral type T, there exist candidate
6745 // operator functions of the form
6746 //
6747 // T operator~(T);
6748 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006749 if (!HasArithmeticOrEnumeralCandidateType)
6750 return;
6751
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006752 for (unsigned Int = FirstPromotedIntegralType;
6753 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006754 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006755 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6756 }
6757
6758 // Extension: We also add this operator for vector types.
6759 for (BuiltinCandidateTypeSet::iterator
6760 Vec = CandidateTypes[0].vector_begin(),
6761 VecEnd = CandidateTypes[0].vector_end();
6762 Vec != VecEnd; ++Vec) {
6763 QualType VecTy = *Vec;
6764 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6765 }
6766 }
6767
6768 // C++ [over.match.oper]p16:
6769 // For every pointer to member type T, there exist candidate operator
6770 // functions of the form
6771 //
6772 // bool operator==(T,T);
6773 // bool operator!=(T,T);
6774 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6775 /// Set of (canonical) types that we've already handled.
6776 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6777
6778 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6779 for (BuiltinCandidateTypeSet::iterator
6780 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6781 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6782 MemPtr != MemPtrEnd;
6783 ++MemPtr) {
6784 // Don't add the same builtin candidate twice.
6785 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6786 continue;
6787
6788 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6789 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6790 CandidateSet);
6791 }
6792 }
6793 }
6794
6795 // C++ [over.built]p15:
6796 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006797 // For every T, where T is an enumeration type, a pointer type, or
6798 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006799 //
6800 // bool operator<(T, T);
6801 // bool operator>(T, T);
6802 // bool operator<=(T, T);
6803 // bool operator>=(T, T);
6804 // bool operator==(T, T);
6805 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006806 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00006807 // C++ [over.match.oper]p3:
6808 // [...]the built-in candidates include all of the candidate operator
6809 // functions defined in 13.6 that, compared to the given operator, [...]
6810 // do not have the same parameter-type-list as any non-template non-member
6811 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006812 //
Eli Friedman14f082b2012-09-18 21:52:24 +00006813 // Note that in practice, this only affects enumeration types because there
6814 // aren't any built-in candidates of record type, and a user-defined operator
6815 // must have an operand of record or enumeration type. Also, the only other
6816 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006817 // cannot be overloaded for enumeration types, so this is the only place
6818 // where we must suppress candidates like this.
6819 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6820 UserDefinedBinaryOperators;
6821
6822 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6823 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6824 CandidateTypes[ArgIdx].enumeration_end()) {
6825 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6826 CEnd = CandidateSet.end();
6827 C != CEnd; ++C) {
6828 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6829 continue;
6830
Eli Friedman14f082b2012-09-18 21:52:24 +00006831 if (C->Function->isFunctionTemplateSpecialization())
6832 continue;
6833
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006834 QualType FirstParamType =
6835 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6836 QualType SecondParamType =
6837 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6838
6839 // Skip if either parameter isn't of enumeral type.
6840 if (!FirstParamType->isEnumeralType() ||
6841 !SecondParamType->isEnumeralType())
6842 continue;
6843
6844 // Add this operator to the set of known user-defined operators.
6845 UserDefinedBinaryOperators.insert(
6846 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6847 S.Context.getCanonicalType(SecondParamType)));
6848 }
6849 }
6850 }
6851
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006852 /// Set of (canonical) types that we've already handled.
6853 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6854
6855 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6856 for (BuiltinCandidateTypeSet::iterator
6857 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6858 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6859 Ptr != PtrEnd; ++Ptr) {
6860 // Don't add the same builtin candidate twice.
6861 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6862 continue;
6863
6864 QualType ParamTypes[2] = { *Ptr, *Ptr };
6865 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6866 CandidateSet);
6867 }
6868 for (BuiltinCandidateTypeSet::iterator
6869 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6870 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6871 Enum != EnumEnd; ++Enum) {
6872 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6873
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006874 // Don't add the same builtin candidate twice, or if a user defined
6875 // candidate exists.
6876 if (!AddedTypes.insert(CanonType) ||
6877 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6878 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006879 continue;
6880
6881 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006882 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6883 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006884 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006885
6886 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6887 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6888 if (AddedTypes.insert(NullPtrTy) &&
6889 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6890 NullPtrTy))) {
6891 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6892 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6893 CandidateSet);
6894 }
6895 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 }
6897 }
6898
6899 // C++ [over.built]p13:
6900 //
6901 // For every cv-qualified or cv-unqualified object type T
6902 // there exist candidate operator functions of the form
6903 //
6904 // T* operator+(T*, ptrdiff_t);
6905 // T& operator[](T*, ptrdiff_t); [BELOW]
6906 // T* operator-(T*, ptrdiff_t);
6907 // T* operator+(ptrdiff_t, T*);
6908 // T& operator[](ptrdiff_t, T*); [BELOW]
6909 //
6910 // C++ [over.built]p14:
6911 //
6912 // For every T, where T is a pointer to object type, there
6913 // exist candidate operator functions of the form
6914 //
6915 // ptrdiff_t operator-(T, T);
6916 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6917 /// Set of (canonical) types that we've already handled.
6918 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6919
6920 for (int Arg = 0; Arg < 2; ++Arg) {
6921 QualType AsymetricParamTypes[2] = {
6922 S.Context.getPointerDiffType(),
6923 S.Context.getPointerDiffType(),
6924 };
6925 for (BuiltinCandidateTypeSet::iterator
6926 Ptr = CandidateTypes[Arg].pointer_begin(),
6927 PtrEnd = CandidateTypes[Arg].pointer_end();
6928 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006929 QualType PointeeTy = (*Ptr)->getPointeeType();
6930 if (!PointeeTy->isObjectType())
6931 continue;
6932
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006933 AsymetricParamTypes[Arg] = *Ptr;
6934 if (Arg == 0 || Op == OO_Plus) {
6935 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6936 // T* operator+(ptrdiff_t, T*);
6937 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6938 CandidateSet);
6939 }
6940 if (Op == OO_Minus) {
6941 // ptrdiff_t operator-(T, T);
6942 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6943 continue;
6944
6945 QualType ParamTypes[2] = { *Ptr, *Ptr };
6946 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6947 Args, 2, CandidateSet);
6948 }
6949 }
6950 }
6951 }
6952
6953 // C++ [over.built]p12:
6954 //
6955 // For every pair of promoted arithmetic types L and R, there
6956 // exist candidate operator functions of the form
6957 //
6958 // LR operator*(L, R);
6959 // LR operator/(L, R);
6960 // LR operator+(L, R);
6961 // LR operator-(L, R);
6962 // bool operator<(L, R);
6963 // bool operator>(L, R);
6964 // bool operator<=(L, R);
6965 // bool operator>=(L, R);
6966 // bool operator==(L, R);
6967 // bool operator!=(L, R);
6968 //
6969 // where LR is the result of the usual arithmetic conversions
6970 // between types L and R.
6971 //
6972 // C++ [over.built]p24:
6973 //
6974 // For every pair of promoted arithmetic types L and R, there exist
6975 // candidate operator functions of the form
6976 //
6977 // LR operator?(bool, L, R);
6978 //
6979 // where LR is the result of the usual arithmetic conversions
6980 // between types L and R.
6981 // Our candidates ignore the first parameter.
6982 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006983 if (!HasArithmeticOrEnumeralCandidateType)
6984 return;
6985
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006986 for (unsigned Left = FirstPromotedArithmeticType;
6987 Left < LastPromotedArithmeticType; ++Left) {
6988 for (unsigned Right = FirstPromotedArithmeticType;
6989 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006990 QualType LandR[2] = { getArithmeticType(Left),
6991 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006992 QualType Result =
6993 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006994 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006995 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6996 }
6997 }
6998
6999 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7000 // conditional operator for vector types.
7001 for (BuiltinCandidateTypeSet::iterator
7002 Vec1 = CandidateTypes[0].vector_begin(),
7003 Vec1End = CandidateTypes[0].vector_end();
7004 Vec1 != Vec1End; ++Vec1) {
7005 for (BuiltinCandidateTypeSet::iterator
7006 Vec2 = CandidateTypes[1].vector_begin(),
7007 Vec2End = CandidateTypes[1].vector_end();
7008 Vec2 != Vec2End; ++Vec2) {
7009 QualType LandR[2] = { *Vec1, *Vec2 };
7010 QualType Result = S.Context.BoolTy;
7011 if (!isComparison) {
7012 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7013 Result = *Vec1;
7014 else
7015 Result = *Vec2;
7016 }
7017
7018 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7019 }
7020 }
7021 }
7022
7023 // C++ [over.built]p17:
7024 //
7025 // For every pair of promoted integral types L and R, there
7026 // exist candidate operator functions of the form
7027 //
7028 // LR operator%(L, R);
7029 // LR operator&(L, R);
7030 // LR operator^(L, R);
7031 // LR operator|(L, R);
7032 // L operator<<(L, R);
7033 // L operator>>(L, R);
7034 //
7035 // where LR is the result of the usual arithmetic conversions
7036 // between types L and R.
7037 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007038 if (!HasArithmeticOrEnumeralCandidateType)
7039 return;
7040
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007041 for (unsigned Left = FirstPromotedIntegralType;
7042 Left < LastPromotedIntegralType; ++Left) {
7043 for (unsigned Right = FirstPromotedIntegralType;
7044 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007045 QualType LandR[2] = { getArithmeticType(Left),
7046 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007047 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7048 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007049 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007050 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7051 }
7052 }
7053 }
7054
7055 // C++ [over.built]p20:
7056 //
7057 // For every pair (T, VQ), where T is an enumeration or
7058 // pointer to member type and VQ is either volatile or
7059 // empty, there exist candidate operator functions of the form
7060 //
7061 // VQ T& operator=(VQ T&, T);
7062 void addAssignmentMemberPointerOrEnumeralOverloads() {
7063 /// Set of (canonical) types that we've already handled.
7064 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7065
7066 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7067 for (BuiltinCandidateTypeSet::iterator
7068 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7069 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7070 Enum != EnumEnd; ++Enum) {
7071 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7072 continue;
7073
7074 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7075 CandidateSet);
7076 }
7077
7078 for (BuiltinCandidateTypeSet::iterator
7079 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7080 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7081 MemPtr != MemPtrEnd; ++MemPtr) {
7082 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7083 continue;
7084
7085 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7086 CandidateSet);
7087 }
7088 }
7089 }
7090
7091 // C++ [over.built]p19:
7092 //
7093 // For every pair (T, VQ), where T is any type and VQ is either
7094 // volatile or empty, there exist candidate operator functions
7095 // of the form
7096 //
7097 // T*VQ& operator=(T*VQ&, T*);
7098 //
7099 // C++ [over.built]p21:
7100 //
7101 // For every pair (T, VQ), where T is a cv-qualified or
7102 // cv-unqualified object type and VQ is either volatile or
7103 // empty, there exist candidate operator functions of the form
7104 //
7105 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7106 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7107 void addAssignmentPointerOverloads(bool isEqualOp) {
7108 /// Set of (canonical) types that we've already handled.
7109 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7110
7111 for (BuiltinCandidateTypeSet::iterator
7112 Ptr = CandidateTypes[0].pointer_begin(),
7113 PtrEnd = CandidateTypes[0].pointer_end();
7114 Ptr != PtrEnd; ++Ptr) {
7115 // If this is operator=, keep track of the builtin candidates we added.
7116 if (isEqualOp)
7117 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007118 else if (!(*Ptr)->getPointeeType()->isObjectType())
7119 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007120
7121 // non-volatile version
7122 QualType ParamTypes[2] = {
7123 S.Context.getLValueReferenceType(*Ptr),
7124 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7125 };
7126 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7127 /*IsAssigmentOperator=*/ isEqualOp);
7128
Douglas Gregor5bee2582012-06-04 00:15:09 +00007129 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7130 VisibleTypeConversionsQuals.hasVolatile();
7131 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007132 // volatile version
7133 ParamTypes[0] =
7134 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7135 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7136 /*IsAssigmentOperator=*/isEqualOp);
7137 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007138
7139 if (!(*Ptr).isRestrictQualified() &&
7140 VisibleTypeConversionsQuals.hasRestrict()) {
7141 // restrict version
7142 ParamTypes[0]
7143 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7145 /*IsAssigmentOperator=*/isEqualOp);
7146
7147 if (NeedVolatile) {
7148 // volatile restrict version
7149 ParamTypes[0]
7150 = S.Context.getLValueReferenceType(
7151 S.Context.getCVRQualifiedType(*Ptr,
7152 (Qualifiers::Volatile |
7153 Qualifiers::Restrict)));
7154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7155 CandidateSet,
7156 /*IsAssigmentOperator=*/isEqualOp);
7157 }
7158 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007159 }
7160
7161 if (isEqualOp) {
7162 for (BuiltinCandidateTypeSet::iterator
7163 Ptr = CandidateTypes[1].pointer_begin(),
7164 PtrEnd = CandidateTypes[1].pointer_end();
7165 Ptr != PtrEnd; ++Ptr) {
7166 // Make sure we don't add the same candidate twice.
7167 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7168 continue;
7169
Chandler Carruth8e543b32010-12-12 08:17:55 +00007170 QualType ParamTypes[2] = {
7171 S.Context.getLValueReferenceType(*Ptr),
7172 *Ptr,
7173 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174
7175 // non-volatile version
7176 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7177 /*IsAssigmentOperator=*/true);
7178
Douglas Gregor5bee2582012-06-04 00:15:09 +00007179 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7180 VisibleTypeConversionsQuals.hasVolatile();
7181 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007182 // volatile version
7183 ParamTypes[0] =
7184 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7186 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007187 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007188
7189 if (!(*Ptr).isRestrictQualified() &&
7190 VisibleTypeConversionsQuals.hasRestrict()) {
7191 // restrict version
7192 ParamTypes[0]
7193 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7194 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7195 CandidateSet, /*IsAssigmentOperator=*/true);
7196
7197 if (NeedVolatile) {
7198 // volatile restrict version
7199 ParamTypes[0]
7200 = S.Context.getLValueReferenceType(
7201 S.Context.getCVRQualifiedType(*Ptr,
7202 (Qualifiers::Volatile |
7203 Qualifiers::Restrict)));
7204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7205 CandidateSet, /*IsAssigmentOperator=*/true);
7206
7207 }
7208 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007209 }
7210 }
7211 }
7212
7213 // C++ [over.built]p18:
7214 //
7215 // For every triple (L, VQ, R), where L is an arithmetic type,
7216 // VQ is either volatile or empty, and R is a promoted
7217 // arithmetic type, there exist candidate operator functions of
7218 // the form
7219 //
7220 // VQ L& operator=(VQ L&, R);
7221 // VQ L& operator*=(VQ L&, R);
7222 // VQ L& operator/=(VQ L&, R);
7223 // VQ L& operator+=(VQ L&, R);
7224 // VQ L& operator-=(VQ L&, R);
7225 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007226 if (!HasArithmeticOrEnumeralCandidateType)
7227 return;
7228
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007229 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7230 for (unsigned Right = FirstPromotedArithmeticType;
7231 Right < LastPromotedArithmeticType; ++Right) {
7232 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007233 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007234
7235 // Add this built-in operator as a candidate (VQ is empty).
7236 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007237 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007238 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7239 /*IsAssigmentOperator=*/isEqualOp);
7240
7241 // Add this built-in operator as a candidate (VQ is 'volatile').
7242 if (VisibleTypeConversionsQuals.hasVolatile()) {
7243 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007244 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007245 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007246 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7247 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007248 /*IsAssigmentOperator=*/isEqualOp);
7249 }
7250 }
7251 }
7252
7253 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7254 for (BuiltinCandidateTypeSet::iterator
7255 Vec1 = CandidateTypes[0].vector_begin(),
7256 Vec1End = CandidateTypes[0].vector_end();
7257 Vec1 != Vec1End; ++Vec1) {
7258 for (BuiltinCandidateTypeSet::iterator
7259 Vec2 = CandidateTypes[1].vector_begin(),
7260 Vec2End = CandidateTypes[1].vector_end();
7261 Vec2 != Vec2End; ++Vec2) {
7262 QualType ParamTypes[2];
7263 ParamTypes[1] = *Vec2;
7264 // Add this built-in operator as a candidate (VQ is empty).
7265 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7267 /*IsAssigmentOperator=*/isEqualOp);
7268
7269 // Add this built-in operator as a candidate (VQ is 'volatile').
7270 if (VisibleTypeConversionsQuals.hasVolatile()) {
7271 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7272 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007273 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7274 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 /*IsAssigmentOperator=*/isEqualOp);
7276 }
7277 }
7278 }
7279 }
7280
7281 // C++ [over.built]p22:
7282 //
7283 // For every triple (L, VQ, R), where L is an integral type, VQ
7284 // is either volatile or empty, and R is a promoted integral
7285 // type, there exist candidate operator functions of the form
7286 //
7287 // VQ L& operator%=(VQ L&, R);
7288 // VQ L& operator<<=(VQ L&, R);
7289 // VQ L& operator>>=(VQ L&, R);
7290 // VQ L& operator&=(VQ L&, R);
7291 // VQ L& operator^=(VQ L&, R);
7292 // VQ L& operator|=(VQ L&, R);
7293 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007294 if (!HasArithmeticOrEnumeralCandidateType)
7295 return;
7296
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7298 for (unsigned Right = FirstPromotedIntegralType;
7299 Right < LastPromotedIntegralType; ++Right) {
7300 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007301 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007302
7303 // Add this built-in operator as a candidate (VQ is empty).
7304 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007305 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7307 if (VisibleTypeConversionsQuals.hasVolatile()) {
7308 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007309 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007310 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7311 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7313 CandidateSet);
7314 }
7315 }
7316 }
7317 }
7318
7319 // C++ [over.operator]p23:
7320 //
7321 // There also exist candidate operator functions of the form
7322 //
7323 // bool operator!(bool);
7324 // bool operator&&(bool, bool);
7325 // bool operator||(bool, bool);
7326 void addExclaimOverload() {
7327 QualType ParamTy = S.Context.BoolTy;
7328 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7329 /*IsAssignmentOperator=*/false,
7330 /*NumContextualBoolArguments=*/1);
7331 }
7332 void addAmpAmpOrPipePipeOverload() {
7333 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7334 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7335 /*IsAssignmentOperator=*/false,
7336 /*NumContextualBoolArguments=*/2);
7337 }
7338
7339 // C++ [over.built]p13:
7340 //
7341 // For every cv-qualified or cv-unqualified object type T there
7342 // exist candidate operator functions of the form
7343 //
7344 // T* operator+(T*, ptrdiff_t); [ABOVE]
7345 // T& operator[](T*, ptrdiff_t);
7346 // T* operator-(T*, ptrdiff_t); [ABOVE]
7347 // T* operator+(ptrdiff_t, T*); [ABOVE]
7348 // T& operator[](ptrdiff_t, T*);
7349 void addSubscriptOverloads() {
7350 for (BuiltinCandidateTypeSet::iterator
7351 Ptr = CandidateTypes[0].pointer_begin(),
7352 PtrEnd = CandidateTypes[0].pointer_end();
7353 Ptr != PtrEnd; ++Ptr) {
7354 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7355 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007356 if (!PointeeType->isObjectType())
7357 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007358
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007359 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7360
7361 // T& operator[](T*, ptrdiff_t)
7362 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7363 }
7364
7365 for (BuiltinCandidateTypeSet::iterator
7366 Ptr = CandidateTypes[1].pointer_begin(),
7367 PtrEnd = CandidateTypes[1].pointer_end();
7368 Ptr != PtrEnd; ++Ptr) {
7369 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7370 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007371 if (!PointeeType->isObjectType())
7372 continue;
7373
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007374 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7375
7376 // T& operator[](ptrdiff_t, T*)
7377 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7378 }
7379 }
7380
7381 // C++ [over.built]p11:
7382 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7383 // C1 is the same type as C2 or is a derived class of C2, T is an object
7384 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7385 // there exist candidate operator functions of the form
7386 //
7387 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7388 //
7389 // where CV12 is the union of CV1 and CV2.
7390 void addArrowStarOverloads() {
7391 for (BuiltinCandidateTypeSet::iterator
7392 Ptr = CandidateTypes[0].pointer_begin(),
7393 PtrEnd = CandidateTypes[0].pointer_end();
7394 Ptr != PtrEnd; ++Ptr) {
7395 QualType C1Ty = (*Ptr);
7396 QualType C1;
7397 QualifierCollector Q1;
7398 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7399 if (!isa<RecordType>(C1))
7400 continue;
7401 // heuristic to reduce number of builtin candidates in the set.
7402 // Add volatile/restrict version only if there are conversions to a
7403 // volatile/restrict type.
7404 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7405 continue;
7406 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7407 continue;
7408 for (BuiltinCandidateTypeSet::iterator
7409 MemPtr = CandidateTypes[1].member_pointer_begin(),
7410 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7411 MemPtr != MemPtrEnd; ++MemPtr) {
7412 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7413 QualType C2 = QualType(mptr->getClass(), 0);
7414 C2 = C2.getUnqualifiedType();
7415 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7416 break;
7417 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7418 // build CV12 T&
7419 QualType T = mptr->getPointeeType();
7420 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7421 T.isVolatileQualified())
7422 continue;
7423 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7424 T.isRestrictQualified())
7425 continue;
7426 T = Q1.apply(S.Context, T);
7427 QualType ResultTy = S.Context.getLValueReferenceType(T);
7428 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7429 }
7430 }
7431 }
7432
7433 // Note that we don't consider the first argument, since it has been
7434 // contextually converted to bool long ago. The candidates below are
7435 // therefore added as binary.
7436 //
7437 // C++ [over.built]p25:
7438 // For every type T, where T is a pointer, pointer-to-member, or scoped
7439 // enumeration type, there exist candidate operator functions of the form
7440 //
7441 // T operator?(bool, T, T);
7442 //
7443 void addConditionalOperatorOverloads() {
7444 /// Set of (canonical) types that we've already handled.
7445 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7446
7447 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7448 for (BuiltinCandidateTypeSet::iterator
7449 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7450 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7451 Ptr != PtrEnd; ++Ptr) {
7452 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7453 continue;
7454
7455 QualType ParamTypes[2] = { *Ptr, *Ptr };
7456 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7457 }
7458
7459 for (BuiltinCandidateTypeSet::iterator
7460 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7461 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7462 MemPtr != MemPtrEnd; ++MemPtr) {
7463 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7464 continue;
7465
7466 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7467 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7468 }
7469
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007470 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007471 for (BuiltinCandidateTypeSet::iterator
7472 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7473 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7474 Enum != EnumEnd; ++Enum) {
7475 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7476 continue;
7477
7478 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7479 continue;
7480
7481 QualType ParamTypes[2] = { *Enum, *Enum };
7482 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7483 }
7484 }
7485 }
7486 }
7487};
7488
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007489} // end anonymous namespace
7490
7491/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7492/// operator overloads to the candidate set (C++ [over.built]), based
7493/// on the operator @p Op and the arguments given. For example, if the
7494/// operator is a binary '+', this routine might add "int
7495/// operator+(int, int)" to cover integer addition.
7496void
7497Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7498 SourceLocation OpLoc,
7499 Expr **Args, unsigned NumArgs,
7500 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007501 // Find all of the types that the arguments can convert to, but only
7502 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007503 // that make use of these types. Also record whether we encounter non-record
7504 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007505 Qualifiers VisibleTypeConversionsQuals;
7506 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007507 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7508 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007509
7510 bool HasNonRecordCandidateType = false;
7511 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007512 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007513 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7514 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7515 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7516 OpLoc,
7517 true,
7518 (Op == OO_Exclaim ||
7519 Op == OO_AmpAmp ||
7520 Op == OO_PipePipe),
7521 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007522 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7523 CandidateTypes[ArgIdx].hasNonRecordTypes();
7524 HasArithmeticOrEnumeralCandidateType =
7525 HasArithmeticOrEnumeralCandidateType ||
7526 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007527 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007528
Chandler Carruth00a38332010-12-13 01:44:01 +00007529 // Exit early when no non-record types have been added to the candidate set
7530 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007531 //
7532 // We can't exit early for !, ||, or &&, since there we have always have
7533 // 'bool' overloads.
7534 if (!HasNonRecordCandidateType &&
7535 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007536 return;
7537
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007538 // Setup an object to manage the common state for building overloads.
7539 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7540 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007541 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542 CandidateTypes, CandidateSet);
7543
7544 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007545 switch (Op) {
7546 case OO_None:
7547 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007548 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007549
Chandler Carruth5184de02010-12-12 08:51:33 +00007550 case OO_New:
7551 case OO_Delete:
7552 case OO_Array_New:
7553 case OO_Array_Delete:
7554 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007555 llvm_unreachable(
7556 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007557
7558 case OO_Comma:
7559 case OO_Arrow:
7560 // C++ [over.match.oper]p3:
7561 // -- For the operator ',', the unary operator '&', or the
7562 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007563 break;
7564
7565 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007566 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007567 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007568 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007569
7570 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007571 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007573 } else {
7574 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7575 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7576 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007577 break;
7578
Chandler Carruth5184de02010-12-12 08:51:33 +00007579 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007580 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007581 OpBuilder.addUnaryStarPointerOverloads();
7582 else
7583 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7584 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007585
Chandler Carruth5184de02010-12-12 08:51:33 +00007586 case OO_Slash:
7587 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007588 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007589
7590 case OO_PlusPlus:
7591 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7593 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007594 break;
7595
Douglas Gregor84605ae2009-08-24 13:43:27 +00007596 case OO_EqualEqual:
7597 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007598 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007599 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007600
Douglas Gregora11693b2008-11-12 17:17:38 +00007601 case OO_Less:
7602 case OO_Greater:
7603 case OO_LessEqual:
7604 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007605 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007606 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7607 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007608
Douglas Gregora11693b2008-11-12 17:17:38 +00007609 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007610 case OO_Caret:
7611 case OO_Pipe:
7612 case OO_LessLess:
7613 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007614 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007615 break;
7616
Chandler Carruth5184de02010-12-12 08:51:33 +00007617 case OO_Amp: // '&' is either unary or binary
7618 if (NumArgs == 1)
7619 // C++ [over.match.oper]p3:
7620 // -- For the operator ',', the unary operator '&', or the
7621 // operator '->', the built-in candidates set is empty.
7622 break;
7623
7624 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7625 break;
7626
7627 case OO_Tilde:
7628 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7629 break;
7630
Douglas Gregora11693b2008-11-12 17:17:38 +00007631 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007633 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007634
7635 case OO_PlusEqual:
7636 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007637 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007638 // Fall through.
7639
7640 case OO_StarEqual:
7641 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007643 break;
7644
7645 case OO_PercentEqual:
7646 case OO_LessLessEqual:
7647 case OO_GreaterGreaterEqual:
7648 case OO_AmpEqual:
7649 case OO_CaretEqual:
7650 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007652 break;
7653
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654 case OO_Exclaim:
7655 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007656 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007657
Douglas Gregora11693b2008-11-12 17:17:38 +00007658 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 case OO_PipePipe:
7660 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007661 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007662
7663 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007664 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007665 break;
7666
7667 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007668 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007669 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007670
7671 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007672 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007673 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7674 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007675 }
7676}
7677
Douglas Gregore254f902009-02-04 00:32:51 +00007678/// \brief Add function candidates found via argument-dependent lookup
7679/// to the set of overloading candidates.
7680///
7681/// This routine performs argument-dependent name lookup based on the
7682/// given function name (which may also be an operator name) and adds
7683/// all of the overload candidates found by ADL to the overload
7684/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007685void
Douglas Gregore254f902009-02-04 00:32:51 +00007686Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007687 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007688 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007689 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007690 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00007691 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00007692 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007693
John McCall91f61fc2010-01-26 06:04:06 +00007694 // FIXME: This approach for uniquing ADL results (and removing
7695 // redundant candidates from the set) relies on pointer-equality,
7696 // which means we need to key off the canonical decl. However,
7697 // always going back to the canonical decl might not get us the
7698 // right set of default arguments. What default arguments are
7699 // we supposed to consider on ADL candidates, anyway?
7700
Douglas Gregorcabea402009-09-22 15:41:20 +00007701 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00007702 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00007703
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007704 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007705 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7706 CandEnd = CandidateSet.end();
7707 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007708 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007709 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007710 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007711 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007712 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007713
7714 // For each of the ADL candidates we found, add it to the overload
7715 // set.
John McCall8fe68082010-01-26 07:16:45 +00007716 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007717 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007718 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007719 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007720 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007721
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007722 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7723 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007724 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007725 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007726 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007727 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007728 }
Douglas Gregore254f902009-02-04 00:32:51 +00007729}
7730
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007731/// isBetterOverloadCandidate - Determines whether the first overload
7732/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007733bool
John McCall5c32be02010-08-24 20:38:10 +00007734isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007735 const OverloadCandidate &Cand1,
7736 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007737 SourceLocation Loc,
7738 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007739 // Define viable functions to be better candidates than non-viable
7740 // functions.
7741 if (!Cand2.Viable)
7742 return Cand1.Viable;
7743 else if (!Cand1.Viable)
7744 return false;
7745
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007746 // C++ [over.match.best]p1:
7747 //
7748 // -- if F is a static member function, ICS1(F) is defined such
7749 // that ICS1(F) is neither better nor worse than ICS1(G) for
7750 // any function G, and, symmetrically, ICS1(G) is neither
7751 // better nor worse than ICS1(F).
7752 unsigned StartArg = 0;
7753 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7754 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007755
Douglas Gregord3cb3562009-07-07 23:38:56 +00007756 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007757 // A viable function F1 is defined to be a better function than another
7758 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007759 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007760 unsigned NumArgs = Cand1.NumConversions;
7761 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007762 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007763 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007764 switch (CompareImplicitConversionSequences(S,
7765 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007766 Cand2.Conversions[ArgIdx])) {
7767 case ImplicitConversionSequence::Better:
7768 // Cand1 has a better conversion sequence.
7769 HasBetterConversion = true;
7770 break;
7771
7772 case ImplicitConversionSequence::Worse:
7773 // Cand1 can't be better than Cand2.
7774 return false;
7775
7776 case ImplicitConversionSequence::Indistinguishable:
7777 // Do nothing.
7778 break;
7779 }
7780 }
7781
Mike Stump11289f42009-09-09 15:08:12 +00007782 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007783 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007784 if (HasBetterConversion)
7785 return true;
7786
Mike Stump11289f42009-09-09 15:08:12 +00007787 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007788 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007789 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007790 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7791 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007792
7793 // -- F1 and F2 are function template specializations, and the function
7794 // template for F1 is more specialized than the template for F2
7795 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007796 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007797 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007798 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007799 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007800 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7801 Cand2.Function->getPrimaryTemplate(),
7802 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007804 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007805 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007806 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007808
Douglas Gregora1f013e2008-11-07 22:36:19 +00007809 // -- the context is an initialization by user-defined conversion
7810 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7811 // from the return type of F1 to the destination type (i.e.,
7812 // the type of the entity being initialized) is a better
7813 // conversion sequence than the standard conversion sequence
7814 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007815 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007816 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007817 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007818 // First check whether we prefer one of the conversion functions over the
7819 // other. This only distinguishes the results in non-standard, extension
7820 // cases such as the conversion from a lambda closure type to a function
7821 // pointer or block.
7822 ImplicitConversionSequence::CompareKind FuncResult
7823 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7824 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7825 return FuncResult;
7826
John McCall5c32be02010-08-24 20:38:10 +00007827 switch (CompareStandardConversionSequences(S,
7828 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007829 Cand2.FinalConversion)) {
7830 case ImplicitConversionSequence::Better:
7831 // Cand1 has a better conversion sequence.
7832 return true;
7833
7834 case ImplicitConversionSequence::Worse:
7835 // Cand1 can't be better than Cand2.
7836 return false;
7837
7838 case ImplicitConversionSequence::Indistinguishable:
7839 // Do nothing
7840 break;
7841 }
7842 }
7843
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007844 return false;
7845}
7846
Mike Stump11289f42009-09-09 15:08:12 +00007847/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007848/// within an overload candidate set.
7849///
James Dennettffad8b72012-06-22 08:10:18 +00007850/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007851/// which overload resolution occurs.
7852///
James Dennettffad8b72012-06-22 08:10:18 +00007853/// \param Best If overload resolution was successful or found a deleted
7854/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007855///
7856/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007857OverloadingResult
7858OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007859 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007860 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007861 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007862 Best = end();
7863 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7864 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007866 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007867 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007868 }
7869
7870 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007871 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007872 return OR_No_Viable_Function;
7873
7874 // Make sure that this function is better than every other viable
7875 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007876 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007877 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007878 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007879 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007880 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007881 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007882 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007883 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007884 }
Mike Stump11289f42009-09-09 15:08:12 +00007885
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007886 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007887 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007888 (Best->Function->isDeleted() ||
7889 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007890 return OR_Deleted;
7891
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007892 return OR_Success;
7893}
7894
John McCall53262c92010-01-12 02:15:36 +00007895namespace {
7896
7897enum OverloadCandidateKind {
7898 oc_function,
7899 oc_method,
7900 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007901 oc_function_template,
7902 oc_method_template,
7903 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007904 oc_implicit_default_constructor,
7905 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007906 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007907 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007908 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007909 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007910};
7911
John McCalle1ac8d12010-01-13 00:25:19 +00007912OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7913 FunctionDecl *Fn,
7914 std::string &Description) {
7915 bool isTemplate = false;
7916
7917 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7918 isTemplate = true;
7919 Description = S.getTemplateArgumentBindingsText(
7920 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7921 }
John McCallfd0b2f82010-01-06 09:43:14 +00007922
7923 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007924 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007925 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007926
Sebastian Redl08905022011-02-05 19:23:19 +00007927 if (Ctor->getInheritedConstructor())
7928 return oc_implicit_inherited_constructor;
7929
Alexis Hunt119c10e2011-05-25 23:16:36 +00007930 if (Ctor->isDefaultConstructor())
7931 return oc_implicit_default_constructor;
7932
7933 if (Ctor->isMoveConstructor())
7934 return oc_implicit_move_constructor;
7935
7936 assert(Ctor->isCopyConstructor() &&
7937 "unexpected sort of implicit constructor");
7938 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007939 }
7940
7941 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7942 // This actually gets spelled 'candidate function' for now, but
7943 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007944 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007945 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007946
Alexis Hunt119c10e2011-05-25 23:16:36 +00007947 if (Meth->isMoveAssignmentOperator())
7948 return oc_implicit_move_assignment;
7949
Douglas Gregor12695102012-02-10 08:36:38 +00007950 if (Meth->isCopyAssignmentOperator())
7951 return oc_implicit_copy_assignment;
7952
7953 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7954 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007955 }
7956
John McCalle1ac8d12010-01-13 00:25:19 +00007957 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007958}
7959
Sebastian Redl08905022011-02-05 19:23:19 +00007960void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7961 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7962 if (!Ctor) return;
7963
7964 Ctor = Ctor->getInheritedConstructor();
7965 if (!Ctor) return;
7966
7967 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7968}
7969
John McCall53262c92010-01-12 02:15:36 +00007970} // end anonymous namespace
7971
7972// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007973void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007974 std::string FnDesc;
7975 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007976 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7977 << (unsigned) K << FnDesc;
7978 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7979 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007980 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007981}
7982
Douglas Gregorb491ed32011-02-19 21:32:49 +00007983//Notes the location of all overload candidates designated through
7984// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007985void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007986 assert(OverloadedExpr->getType() == Context.OverloadTy);
7987
7988 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7989 OverloadExpr *OvlExpr = Ovl.Expression;
7990
7991 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7992 IEnd = OvlExpr->decls_end();
7993 I != IEnd; ++I) {
7994 if (FunctionTemplateDecl *FunTmpl =
7995 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007996 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007997 } else if (FunctionDecl *Fun
7998 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007999 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008000 }
8001 }
8002}
8003
John McCall0d1da222010-01-12 00:44:57 +00008004/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8005/// "lead" diagnostic; it will be given two arguments, the source and
8006/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008007void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8008 Sema &S,
8009 SourceLocation CaretLoc,
8010 const PartialDiagnostic &PDiag) const {
8011 S.Diag(CaretLoc, PDiag)
8012 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008013 // FIXME: The note limiting machinery is borrowed from
8014 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8015 // refactoring here.
8016 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8017 unsigned CandsShown = 0;
8018 AmbiguousConversionSequence::const_iterator I, E;
8019 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8020 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8021 break;
8022 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008023 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008024 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008025 if (I != E)
8026 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008027}
8028
John McCall0d1da222010-01-12 00:44:57 +00008029namespace {
8030
John McCall6a61b522010-01-13 09:16:55 +00008031void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8032 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8033 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008034 assert(Cand->Function && "for now, candidate must be a function");
8035 FunctionDecl *Fn = Cand->Function;
8036
8037 // There's a conversion slot for the object argument if this is a
8038 // non-constructor method. Note that 'I' corresponds the
8039 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008040 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008041 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008042 if (I == 0)
8043 isObjectArgument = true;
8044 else
8045 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008046 }
8047
John McCalle1ac8d12010-01-13 00:25:19 +00008048 std::string FnDesc;
8049 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8050
John McCall6a61b522010-01-13 09:16:55 +00008051 Expr *FromExpr = Conv.Bad.FromExpr;
8052 QualType FromTy = Conv.Bad.getFromType();
8053 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008054
John McCallfb7ad0f2010-02-02 02:42:52 +00008055 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008056 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008057 Expr *E = FromExpr->IgnoreParens();
8058 if (isa<UnaryOperator>(E))
8059 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008060 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008061
8062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8063 << (unsigned) FnKind << FnDesc
8064 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8065 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008066 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008067 return;
8068 }
8069
John McCall6d174642010-01-23 08:10:49 +00008070 // Do some hand-waving analysis to see if the non-viability is due
8071 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008072 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8073 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8074 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8075 CToTy = RT->getPointeeType();
8076 else {
8077 // TODO: detect and diagnose the full richness of const mismatches.
8078 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8079 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8080 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8081 }
8082
8083 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8084 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008085 Qualifiers FromQs = CFromTy.getQualifiers();
8086 Qualifiers ToQs = CToTy.getQualifiers();
8087
8088 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8090 << (unsigned) FnKind << FnDesc
8091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8092 << FromTy
8093 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8094 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008095 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008096 return;
8097 }
8098
John McCall31168b02011-06-15 23:02:42 +00008099 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008101 << (unsigned) FnKind << FnDesc
8102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8103 << FromTy
8104 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8105 << (unsigned) isObjectArgument << I+1;
8106 MaybeEmitInheritedConstructorNote(S, Fn);
8107 return;
8108 }
8109
Douglas Gregoraec25842011-04-26 23:16:46 +00008110 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8112 << (unsigned) FnKind << FnDesc
8113 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8114 << FromTy
8115 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8116 << (unsigned) isObjectArgument << I+1;
8117 MaybeEmitInheritedConstructorNote(S, Fn);
8118 return;
8119 }
8120
John McCall47000992010-01-14 03:28:57 +00008121 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8122 assert(CVR && "unexpected qualifiers mismatch");
8123
8124 if (isObjectArgument) {
8125 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8126 << (unsigned) FnKind << FnDesc
8127 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8128 << FromTy << (CVR - 1);
8129 } else {
8130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8131 << (unsigned) FnKind << FnDesc
8132 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8133 << FromTy << (CVR - 1) << I+1;
8134 }
Sebastian Redl08905022011-02-05 19:23:19 +00008135 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008136 return;
8137 }
8138
Sebastian Redla72462c2011-09-24 17:48:32 +00008139 // Special diagnostic for failure to convert an initializer list, since
8140 // telling the user that it has type void is not useful.
8141 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8143 << (unsigned) FnKind << FnDesc
8144 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8145 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8146 MaybeEmitInheritedConstructorNote(S, Fn);
8147 return;
8148 }
8149
John McCall6d174642010-01-23 08:10:49 +00008150 // Diagnose references or pointers to incomplete types differently,
8151 // since it's far from impossible that the incompleteness triggered
8152 // the failure.
8153 QualType TempFromTy = FromTy.getNonReferenceType();
8154 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8155 TempFromTy = PTy->getPointeeType();
8156 if (TempFromTy->isIncompleteType()) {
8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8158 << (unsigned) FnKind << FnDesc
8159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8160 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008161 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008162 return;
8163 }
8164
Douglas Gregor56f2e342010-06-30 23:01:39 +00008165 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008166 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008167 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8168 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8169 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8170 FromPtrTy->getPointeeType()) &&
8171 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8172 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008173 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008174 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008175 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008176 }
8177 } else if (const ObjCObjectPointerType *FromPtrTy
8178 = FromTy->getAs<ObjCObjectPointerType>()) {
8179 if (const ObjCObjectPointerType *ToPtrTy
8180 = ToTy->getAs<ObjCObjectPointerType>())
8181 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8182 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8183 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8184 FromPtrTy->getPointeeType()) &&
8185 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008186 BaseToDerivedConversion = 2;
8187 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008188 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8189 !FromTy->isIncompleteType() &&
8190 !ToRefTy->getPointeeType()->isIncompleteType() &&
8191 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8192 BaseToDerivedConversion = 3;
8193 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8194 ToTy.getNonReferenceType().getCanonicalType() ==
8195 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8197 << (unsigned) FnKind << FnDesc
8198 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8199 << (unsigned) isObjectArgument << I + 1;
8200 MaybeEmitInheritedConstructorNote(S, Fn);
8201 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008202 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008204
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008205 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008206 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008207 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008208 << (unsigned) FnKind << FnDesc
8209 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008210 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008211 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008212 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008213 return;
8214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008215
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008216 if (isa<ObjCObjectPointerType>(CFromTy) &&
8217 isa<PointerType>(CToTy)) {
8218 Qualifiers FromQs = CFromTy.getQualifiers();
8219 Qualifiers ToQs = CToTy.getQualifiers();
8220 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8222 << (unsigned) FnKind << FnDesc
8223 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8224 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8225 MaybeEmitInheritedConstructorNote(S, Fn);
8226 return;
8227 }
8228 }
8229
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008230 // Emit the generic diagnostic and, optionally, add the hints to it.
8231 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8232 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008233 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008234 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8235 << (unsigned) (Cand->Fix.Kind);
8236
8237 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008238 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8239 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008240 FDiag << *HI;
8241 S.Diag(Fn->getLocation(), FDiag);
8242
Sebastian Redl08905022011-02-05 19:23:19 +00008243 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008244}
8245
8246void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8247 unsigned NumFormalArgs) {
8248 // TODO: treat calls to a missing default constructor as a special case
8249
8250 FunctionDecl *Fn = Cand->Function;
8251 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8252
8253 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008254
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008255 // With invalid overloaded operators, it's possible that we think we
8256 // have an arity mismatch when it fact it looks like we have the
8257 // right number of arguments, because only overloaded operators have
8258 // the weird behavior of overloading member and non-member functions.
8259 // Just don't report anything.
8260 if (Fn->isInvalidDecl() &&
8261 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8262 return;
8263
John McCall6a61b522010-01-13 09:16:55 +00008264 // at least / at most / exactly
8265 unsigned mode, modeCount;
8266 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008267 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8268 (Cand->FailureKind == ovl_fail_bad_deduction &&
8269 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008270 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008271 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008272 mode = 0; // "at least"
8273 else
8274 mode = 2; // "exactly"
8275 modeCount = MinParams;
8276 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008277 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8278 (Cand->FailureKind == ovl_fail_bad_deduction &&
8279 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008280 if (MinParams != FnTy->getNumArgs())
8281 mode = 1; // "at most"
8282 else
8283 mode = 2; // "exactly"
8284 modeCount = FnTy->getNumArgs();
8285 }
8286
8287 std::string Description;
8288 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8289
Richard Smith10ff50d2012-05-11 05:16:41 +00008290 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8292 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8293 << Fn->getParamDecl(0) << NumFormalArgs;
8294 else
8295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8296 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8297 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008298 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008299}
8300
John McCall8b9ed552010-02-01 18:53:26 +00008301/// Diagnose a failed template-argument deduction.
8302void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008303 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008304 FunctionDecl *Fn = Cand->Function; // pattern
8305
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008306 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008307 NamedDecl *ParamD;
8308 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8309 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8310 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008311 switch (Cand->DeductionFailure.Result) {
8312 case Sema::TDK_Success:
8313 llvm_unreachable("TDK_success while diagnosing bad deduction");
8314
8315 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008316 assert(ParamD && "no parameter found for incomplete deduction result");
8317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8318 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008319 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008320 return;
8321 }
8322
John McCall42d7d192010-08-05 09:05:08 +00008323 case Sema::TDK_Underqualified: {
8324 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8325 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8326
8327 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8328
8329 // Param will have been canonicalized, but it should just be a
8330 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008331 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008332 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008333 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008334 assert(S.Context.hasSameType(Param, NonCanonParam));
8335
8336 // Arg has also been canonicalized, but there's nothing we can do
8337 // about that. It also doesn't matter as much, because it won't
8338 // have any template parameters in it (because deduction isn't
8339 // done on dependent types).
8340 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8341
8342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8343 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008344 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008345 return;
8346 }
8347
8348 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008349 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008350 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008351 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008352 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008353 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008354 which = 1;
8355 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008356 which = 2;
8357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008358
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008360 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008361 << *Cand->DeductionFailure.getFirstArg()
8362 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008363 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008364 return;
8365 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008366
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008367 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008369 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008370 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008371 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8372 << ParamD->getDeclName();
8373 else {
8374 int index = 0;
8375 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8376 index = TTP->getIndex();
8377 else if (NonTypeTemplateParmDecl *NTTP
8378 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8379 index = NTTP->getIndex();
8380 else
8381 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008382 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008383 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8384 << (index + 1);
8385 }
Sebastian Redl08905022011-02-05 19:23:19 +00008386 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008387 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008388
Douglas Gregor02eb4832010-05-08 18:13:28 +00008389 case Sema::TDK_TooManyArguments:
8390 case Sema::TDK_TooFewArguments:
8391 DiagnoseArityMismatch(S, Cand, NumArgs);
8392 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008393
8394 case Sema::TDK_InstantiationDepth:
8395 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008396 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008397 return;
8398
8399 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008400 // Format the template argument list into the argument string.
8401 llvm::SmallString<128> TemplateArgString;
8402 if (TemplateArgumentList *Args =
8403 Cand->DeductionFailure.getTemplateArgumentList()) {
8404 TemplateArgString = " ";
8405 TemplateArgString += S.getTemplateArgumentBindingsText(
8406 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8407 }
8408
Richard Smith6f8d2c62012-05-09 05:17:00 +00008409 // If this candidate was disabled by enable_if, say so.
8410 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8411 if (PDiag && PDiag->second.getDiagID() ==
8412 diag::err_typename_nested_not_found_enable_if) {
8413 // FIXME: Use the source range of the condition, and the fully-qualified
8414 // name of the enable_if template. These are both present in PDiag.
8415 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8416 << "'enable_if'" << TemplateArgString;
8417 return;
8418 }
8419
Richard Smith9ca64612012-05-07 09:03:25 +00008420 // Format the SFINAE diagnostic into the argument string.
8421 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8422 // formatted message in another diagnostic.
8423 llvm::SmallString<128> SFINAEArgString;
8424 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008425 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008426 SFINAEArgString = ": ";
8427 R = SourceRange(PDiag->first, PDiag->first);
8428 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8429 }
8430
Douglas Gregord09efd42010-05-08 20:07:26 +00008431 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008432 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008433 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008434 return;
8435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008436
John McCall8b9ed552010-02-01 18:53:26 +00008437 // TODO: diagnose these individually, then kill off
8438 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008439 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008440 case Sema::TDK_FailedOverloadResolution:
8441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008442 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008443 return;
8444 }
8445}
8446
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008447/// CUDA: diagnose an invalid call across targets.
8448void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8449 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8450 FunctionDecl *Callee = Cand->Function;
8451
8452 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8453 CalleeTarget = S.IdentifyCUDATarget(Callee);
8454
8455 std::string FnDesc;
8456 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8457
8458 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8459 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8460}
8461
John McCall8b9ed552010-02-01 18:53:26 +00008462/// Generates a 'note' diagnostic for an overload candidate. We've
8463/// already generated a primary error at the call site.
8464///
8465/// It really does need to be a single diagnostic with its caret
8466/// pointed at the candidate declaration. Yes, this creates some
8467/// major challenges of technical writing. Yes, this makes pointing
8468/// out problems with specific arguments quite awkward. It's still
8469/// better than generating twenty screens of text for every failed
8470/// overload.
8471///
8472/// It would be great to be able to express per-candidate problems
8473/// more richly for those diagnostic clients that cared, but we'd
8474/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008475void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008476 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008477 FunctionDecl *Fn = Cand->Function;
8478
John McCall12f97bc2010-01-08 04:41:39 +00008479 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008480 if (Cand->Viable && (Fn->isDeleted() ||
8481 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008482 std::string FnDesc;
8483 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008484
8485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008486 << FnKind << FnDesc
8487 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008488 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008489 return;
John McCall12f97bc2010-01-08 04:41:39 +00008490 }
8491
John McCalle1ac8d12010-01-13 00:25:19 +00008492 // We don't really have anything else to say about viable candidates.
8493 if (Cand->Viable) {
8494 S.NoteOverloadCandidate(Fn);
8495 return;
8496 }
John McCall0d1da222010-01-12 00:44:57 +00008497
John McCall6a61b522010-01-13 09:16:55 +00008498 switch (Cand->FailureKind) {
8499 case ovl_fail_too_many_arguments:
8500 case ovl_fail_too_few_arguments:
8501 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008502
John McCall6a61b522010-01-13 09:16:55 +00008503 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008504 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008505
John McCallfe796dd2010-01-23 05:17:32 +00008506 case ovl_fail_trivial_conversion:
8507 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008508 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008509 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008510
John McCall65eb8792010-02-25 01:37:24 +00008511 case ovl_fail_bad_conversion: {
8512 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008513 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008514 if (Cand->Conversions[I].isBad())
8515 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516
John McCall6a61b522010-01-13 09:16:55 +00008517 // FIXME: this currently happens when we're called from SemaInit
8518 // when user-conversion overload fails. Figure out how to handle
8519 // those conditions and diagnose them well.
8520 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008521 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008522
8523 case ovl_fail_bad_target:
8524 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008525 }
John McCalld3224162010-01-08 00:58:21 +00008526}
8527
8528void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8529 // Desugar the type of the surrogate down to a function type,
8530 // retaining as many typedefs as possible while still showing
8531 // the function type (and, therefore, its parameter types).
8532 QualType FnType = Cand->Surrogate->getConversionType();
8533 bool isLValueReference = false;
8534 bool isRValueReference = false;
8535 bool isPointer = false;
8536 if (const LValueReferenceType *FnTypeRef =
8537 FnType->getAs<LValueReferenceType>()) {
8538 FnType = FnTypeRef->getPointeeType();
8539 isLValueReference = true;
8540 } else if (const RValueReferenceType *FnTypeRef =
8541 FnType->getAs<RValueReferenceType>()) {
8542 FnType = FnTypeRef->getPointeeType();
8543 isRValueReference = true;
8544 }
8545 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8546 FnType = FnTypePtr->getPointeeType();
8547 isPointer = true;
8548 }
8549 // Desugar down to a function type.
8550 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8551 // Reconstruct the pointer/reference as appropriate.
8552 if (isPointer) FnType = S.Context.getPointerType(FnType);
8553 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8554 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8555
8556 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8557 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008558 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008559}
8560
8561void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00008562 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00008563 SourceLocation OpLoc,
8564 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008565 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008566 std::string TypeStr("operator");
8567 TypeStr += Opc;
8568 TypeStr += "(";
8569 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008570 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008571 TypeStr += ")";
8572 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8573 } else {
8574 TypeStr += ", ";
8575 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8576 TypeStr += ")";
8577 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8578 }
8579}
8580
8581void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8582 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008583 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008584 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8585 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008586 if (ICS.isBad()) break; // all meaningless after first invalid
8587 if (!ICS.isAmbiguous()) continue;
8588
John McCall5c32be02010-08-24 20:38:10 +00008589 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008590 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008591 }
8592}
8593
John McCall3712d9e2010-01-15 23:32:50 +00008594SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8595 if (Cand->Function)
8596 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008597 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008598 return Cand->Surrogate->getLocation();
8599 return SourceLocation();
8600}
8601
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008602static unsigned
8603RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008604 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008605 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008606 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008607
Douglas Gregorc5c01a62012-09-13 21:01:57 +00008608 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008609 case Sema::TDK_Incomplete:
8610 return 1;
8611
8612 case Sema::TDK_Underqualified:
8613 case Sema::TDK_Inconsistent:
8614 return 2;
8615
8616 case Sema::TDK_SubstitutionFailure:
8617 case Sema::TDK_NonDeducedMismatch:
8618 return 3;
8619
8620 case Sema::TDK_InstantiationDepth:
8621 case Sema::TDK_FailedOverloadResolution:
8622 return 4;
8623
8624 case Sema::TDK_InvalidExplicitArguments:
8625 return 5;
8626
8627 case Sema::TDK_TooManyArguments:
8628 case Sema::TDK_TooFewArguments:
8629 return 6;
8630 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008631 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008632}
8633
John McCallad2587a2010-01-12 00:48:53 +00008634struct CompareOverloadCandidatesForDisplay {
8635 Sema &S;
8636 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008637
8638 bool operator()(const OverloadCandidate *L,
8639 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008640 // Fast-path this check.
8641 if (L == R) return false;
8642
John McCall12f97bc2010-01-08 04:41:39 +00008643 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008644 if (L->Viable) {
8645 if (!R->Viable) return true;
8646
8647 // TODO: introduce a tri-valued comparison for overload
8648 // candidates. Would be more worthwhile if we had a sort
8649 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008650 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8651 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008652 } else if (R->Viable)
8653 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008654
John McCall3712d9e2010-01-15 23:32:50 +00008655 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008656
John McCall3712d9e2010-01-15 23:32:50 +00008657 // Criteria by which we can sort non-viable candidates:
8658 if (!L->Viable) {
8659 // 1. Arity mismatches come after other candidates.
8660 if (L->FailureKind == ovl_fail_too_many_arguments ||
8661 L->FailureKind == ovl_fail_too_few_arguments)
8662 return false;
8663 if (R->FailureKind == ovl_fail_too_many_arguments ||
8664 R->FailureKind == ovl_fail_too_few_arguments)
8665 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008666
John McCallfe796dd2010-01-23 05:17:32 +00008667 // 2. Bad conversions come first and are ordered by the number
8668 // of bad conversions and quality of good conversions.
8669 if (L->FailureKind == ovl_fail_bad_conversion) {
8670 if (R->FailureKind != ovl_fail_bad_conversion)
8671 return true;
8672
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008673 // The conversion that can be fixed with a smaller number of changes,
8674 // comes first.
8675 unsigned numLFixes = L->Fix.NumConversionsFixed;
8676 unsigned numRFixes = R->Fix.NumConversionsFixed;
8677 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8678 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008679 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008680 if (numLFixes < numRFixes)
8681 return true;
8682 else
8683 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008684 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008685
John McCallfe796dd2010-01-23 05:17:32 +00008686 // If there's any ordering between the defined conversions...
8687 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008688 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008689
8690 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008691 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008692 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008693 switch (CompareImplicitConversionSequences(S,
8694 L->Conversions[I],
8695 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008696 case ImplicitConversionSequence::Better:
8697 leftBetter++;
8698 break;
8699
8700 case ImplicitConversionSequence::Worse:
8701 leftBetter--;
8702 break;
8703
8704 case ImplicitConversionSequence::Indistinguishable:
8705 break;
8706 }
8707 }
8708 if (leftBetter > 0) return true;
8709 if (leftBetter < 0) return false;
8710
8711 } else if (R->FailureKind == ovl_fail_bad_conversion)
8712 return false;
8713
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008714 if (L->FailureKind == ovl_fail_bad_deduction) {
8715 if (R->FailureKind != ovl_fail_bad_deduction)
8716 return true;
8717
8718 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8719 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008720 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008721 } else if (R->FailureKind == ovl_fail_bad_deduction)
8722 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008723
John McCall3712d9e2010-01-15 23:32:50 +00008724 // TODO: others?
8725 }
8726
8727 // Sort everything else by location.
8728 SourceLocation LLoc = GetLocationForCandidate(L);
8729 SourceLocation RLoc = GetLocationForCandidate(R);
8730
8731 // Put candidates without locations (e.g. builtins) at the end.
8732 if (LLoc.isInvalid()) return false;
8733 if (RLoc.isInvalid()) return true;
8734
8735 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008736 }
8737};
8738
John McCallfe796dd2010-01-23 05:17:32 +00008739/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008740/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008741void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008742 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008743 assert(!Cand->Viable);
8744
8745 // Don't do anything on failures other than bad conversion.
8746 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8747
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008748 // We only want the FixIts if all the arguments can be corrected.
8749 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008750 // Use a implicit copy initialization to check conversion fixes.
8751 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008752
John McCallfe796dd2010-01-23 05:17:32 +00008753 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008754 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008755 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008756 while (true) {
8757 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8758 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008759 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008760 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008761 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008762 }
John McCallfe796dd2010-01-23 05:17:32 +00008763 }
8764
8765 if (ConvIdx == ConvCount)
8766 return;
8767
John McCall65eb8792010-02-25 01:37:24 +00008768 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8769 "remaining conversion is initialized?");
8770
Douglas Gregoradc7a702010-04-16 17:45:54 +00008771 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008772 // operation somehow.
8773 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008774
8775 const FunctionProtoType* Proto;
8776 unsigned ArgIdx = ConvIdx;
8777
8778 if (Cand->IsSurrogate) {
8779 QualType ConvType
8780 = Cand->Surrogate->getConversionType().getNonReferenceType();
8781 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8782 ConvType = ConvPtrType->getPointeeType();
8783 Proto = ConvType->getAs<FunctionProtoType>();
8784 ArgIdx--;
8785 } else if (Cand->Function) {
8786 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8787 if (isa<CXXMethodDecl>(Cand->Function) &&
8788 !isa<CXXConstructorDecl>(Cand->Function))
8789 ArgIdx--;
8790 } else {
8791 // Builtin binary operator with a bad first conversion.
8792 assert(ConvCount <= 3);
8793 for (; ConvIdx != ConvCount; ++ConvIdx)
8794 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008795 = TryCopyInitialization(S, Args[ConvIdx],
8796 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008797 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008798 /*InOverloadResolution*/ true,
8799 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008800 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008801 return;
8802 }
8803
8804 // Fill in the rest of the conversions.
8805 unsigned NumArgsInProto = Proto->getNumArgs();
8806 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008807 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008808 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008809 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008810 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008811 /*InOverloadResolution=*/true,
8812 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008813 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008814 // Store the FixIt in the candidate if it exists.
8815 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008816 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008817 }
John McCallfe796dd2010-01-23 05:17:32 +00008818 else
8819 Cand->Conversions[ConvIdx].setEllipsis();
8820 }
8821}
8822
John McCalld3224162010-01-08 00:58:21 +00008823} // end anonymous namespace
8824
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008825/// PrintOverloadCandidates - When overload resolution fails, prints
8826/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008827/// set.
John McCall5c32be02010-08-24 20:38:10 +00008828void OverloadCandidateSet::NoteCandidates(Sema &S,
8829 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008830 llvm::ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00008831 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00008832 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008833 // Sort the candidates by viability and position. Sorting directly would
8834 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008835 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008836 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8837 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008838 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008839 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008840 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008841 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008842 if (Cand->Function || Cand->IsSurrogate)
8843 Cands.push_back(Cand);
8844 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8845 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008846 }
8847 }
8848
John McCallad2587a2010-01-12 00:48:53 +00008849 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008850 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851
John McCall0d1da222010-01-12 00:44:57 +00008852 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008853
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008854 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00008855 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008856 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008857 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8858 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008859
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008860 // Set an arbitrary limit on the number of candidate functions we'll spam
8861 // the user with. FIXME: This limit should depend on details of the
8862 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00008863 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008864 break;
8865 }
8866 ++CandsShown;
8867
John McCalld3224162010-01-08 00:58:21 +00008868 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008869 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008870 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008871 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008872 else {
8873 assert(Cand->Viable &&
8874 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008875 // Generally we only see ambiguities including viable builtin
8876 // operators if overload resolution got screwed up by an
8877 // ambiguous user-defined conversion.
8878 //
8879 // FIXME: It's quite possible for different conversions to see
8880 // different ambiguities, though.
8881 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008882 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008883 ReportedAmbiguousConversions = true;
8884 }
John McCalld3224162010-01-08 00:58:21 +00008885
John McCall0d1da222010-01-12 00:44:57 +00008886 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008887 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008888 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008889 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008890
8891 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008892 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008893}
8894
Douglas Gregorb491ed32011-02-19 21:32:49 +00008895// [PossiblyAFunctionType] --> [Return]
8896// NonFunctionType --> NonFunctionType
8897// R (A) --> R(A)
8898// R (*)(A) --> R (A)
8899// R (&)(A) --> R (A)
8900// R (S::*)(A) --> R (A)
8901QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8902 QualType Ret = PossiblyAFunctionType;
8903 if (const PointerType *ToTypePtr =
8904 PossiblyAFunctionType->getAs<PointerType>())
8905 Ret = ToTypePtr->getPointeeType();
8906 else if (const ReferenceType *ToTypeRef =
8907 PossiblyAFunctionType->getAs<ReferenceType>())
8908 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008909 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008910 PossiblyAFunctionType->getAs<MemberPointerType>())
8911 Ret = MemTypePtr->getPointeeType();
8912 Ret =
8913 Context.getCanonicalType(Ret).getUnqualifiedType();
8914 return Ret;
8915}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008916
Douglas Gregorb491ed32011-02-19 21:32:49 +00008917// A helper class to help with address of function resolution
8918// - allows us to avoid passing around all those ugly parameters
8919class AddressOfFunctionResolver
8920{
8921 Sema& S;
8922 Expr* SourceExpr;
8923 const QualType& TargetType;
8924 QualType TargetFunctionType; // Extracted function type from target type
8925
8926 bool Complain;
8927 //DeclAccessPair& ResultFunctionAccessPair;
8928 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008929
Douglas Gregorb491ed32011-02-19 21:32:49 +00008930 bool TargetTypeIsNonStaticMemberFunction;
8931 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008932
Douglas Gregorb491ed32011-02-19 21:32:49 +00008933 OverloadExpr::FindResult OvlExprInfo;
8934 OverloadExpr *OvlExpr;
8935 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008936 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008937
Douglas Gregorb491ed32011-02-19 21:32:49 +00008938public:
8939 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8940 const QualType& TargetType, bool Complain)
8941 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8942 Complain(Complain), Context(S.getASTContext()),
8943 TargetTypeIsNonStaticMemberFunction(
8944 !!TargetType->getAs<MemberPointerType>()),
8945 FoundNonTemplateFunction(false),
8946 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8947 OvlExpr(OvlExprInfo.Expression)
8948 {
8949 ExtractUnqualifiedFunctionTypeFromTargetType();
8950
8951 if (!TargetFunctionType->isFunctionType()) {
8952 if (OvlExpr->hasExplicitTemplateArgs()) {
8953 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008954 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008955 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008956
8957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8958 if (!Method->isStatic()) {
8959 // If the target type is a non-function type and the function
8960 // found is a non-static member function, pretend as if that was
8961 // the target, it's the only possible type to end up with.
8962 TargetTypeIsNonStaticMemberFunction = true;
8963
8964 // And skip adding the function if its not in the proper form.
8965 // We'll diagnose this due to an empty set of functions.
8966 if (!OvlExprInfo.HasFormOfMemberPointer)
8967 return;
8968 }
8969 }
8970
Douglas Gregorb491ed32011-02-19 21:32:49 +00008971 Matches.push_back(std::make_pair(dap,Fn));
8972 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008973 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008974 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008975 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008976
8977 if (OvlExpr->hasExplicitTemplateArgs())
8978 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008979
Douglas Gregorb491ed32011-02-19 21:32:49 +00008980 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8981 // C++ [over.over]p4:
8982 // If more than one function is selected, [...]
8983 if (Matches.size() > 1) {
8984 if (FoundNonTemplateFunction)
8985 EliminateAllTemplateMatches();
8986 else
8987 EliminateAllExceptMostSpecializedTemplate();
8988 }
8989 }
8990 }
8991
8992private:
8993 bool isTargetTypeAFunction() const {
8994 return TargetFunctionType->isFunctionType();
8995 }
8996
8997 // [ToType] [Return]
8998
8999 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9000 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9001 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9002 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9003 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9004 }
9005
9006 // return true if any matching specializations were found
9007 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9008 const DeclAccessPair& CurAccessFunPair) {
9009 if (CXXMethodDecl *Method
9010 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9011 // Skip non-static function templates when converting to pointer, and
9012 // static when converting to member pointer.
9013 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9014 return false;
9015 }
9016 else if (TargetTypeIsNonStaticMemberFunction)
9017 return false;
9018
9019 // C++ [over.over]p2:
9020 // If the name is a function template, template argument deduction is
9021 // done (14.8.2.2), and if the argument deduction succeeds, the
9022 // resulting template argument list is used to generate a single
9023 // function template specialization, which is added to the set of
9024 // overloaded functions considered.
9025 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009026 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009027 if (Sema::TemplateDeductionResult Result
9028 = S.DeduceTemplateArguments(FunctionTemplate,
9029 &OvlExplicitTemplateArgs,
9030 TargetFunctionType, Specialization,
9031 Info)) {
9032 // FIXME: make a note of the failed deduction for diagnostics.
9033 (void)Result;
9034 return false;
9035 }
9036
9037 // Template argument deduction ensures that we have an exact match.
9038 // This function template specicalization works.
9039 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9040 assert(TargetFunctionType
9041 == Context.getCanonicalType(Specialization->getType()));
9042 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9043 return true;
9044 }
9045
9046 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9047 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009049 // Skip non-static functions when converting to pointer, and static
9050 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009051 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9052 return false;
9053 }
9054 else if (TargetTypeIsNonStaticMemberFunction)
9055 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009056
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009057 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009058 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009059 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9060 if (S.CheckCUDATarget(Caller, FunDecl))
9061 return false;
9062
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009063 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009064 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9065 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009066 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9067 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009068 Matches.push_back(std::make_pair(CurAccessFunPair,
9069 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009070 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009071 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009072 }
Mike Stump11289f42009-09-09 15:08:12 +00009073 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009074
9075 return false;
9076 }
9077
9078 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9079 bool Ret = false;
9080
9081 // If the overload expression doesn't have the form of a pointer to
9082 // member, don't try to convert it to a pointer-to-member type.
9083 if (IsInvalidFormOfPointerToMemberFunction())
9084 return false;
9085
9086 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9087 E = OvlExpr->decls_end();
9088 I != E; ++I) {
9089 // Look through any using declarations to find the underlying function.
9090 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9091
9092 // C++ [over.over]p3:
9093 // Non-member functions and static member functions match
9094 // targets of type "pointer-to-function" or "reference-to-function."
9095 // Nonstatic member functions match targets of
9096 // type "pointer-to-member-function."
9097 // Note that according to DR 247, the containing class does not matter.
9098 if (FunctionTemplateDecl *FunctionTemplate
9099 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9100 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9101 Ret = true;
9102 }
9103 // If we have explicit template arguments supplied, skip non-templates.
9104 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9105 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9106 Ret = true;
9107 }
9108 assert(Ret || Matches.empty());
9109 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009110 }
9111
Douglas Gregorb491ed32011-02-19 21:32:49 +00009112 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009113 // [...] and any given function template specialization F1 is
9114 // eliminated if the set contains a second function template
9115 // specialization whose function template is more specialized
9116 // than the function template of F1 according to the partial
9117 // ordering rules of 14.5.5.2.
9118
9119 // The algorithm specified above is quadratic. We instead use a
9120 // two-pass algorithm (similar to the one used to identify the
9121 // best viable function in an overload set) that identifies the
9122 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009123
9124 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9125 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9126 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009127
John McCall58cc69d2010-01-27 01:50:18 +00009128 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009129 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9130 TPOC_Other, 0, SourceExpr->getLocStart(),
9131 S.PDiag(),
9132 S.PDiag(diag::err_addr_ovl_ambiguous)
9133 << Matches[0].second->getDeclName(),
9134 S.PDiag(diag::note_ovl_candidate)
9135 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009136 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009137
Douglas Gregorb491ed32011-02-19 21:32:49 +00009138 if (Result != MatchesCopy.end()) {
9139 // Make it the first and only element
9140 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9141 Matches[0].second = cast<FunctionDecl>(*Result);
9142 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009143 }
9144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009145
Douglas Gregorb491ed32011-02-19 21:32:49 +00009146 void EliminateAllTemplateMatches() {
9147 // [...] any function template specializations in the set are
9148 // eliminated if the set also contains a non-template function, [...]
9149 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9150 if (Matches[I].second->getPrimaryTemplate() == 0)
9151 ++I;
9152 else {
9153 Matches[I] = Matches[--N];
9154 Matches.set_size(N);
9155 }
9156 }
9157 }
9158
9159public:
9160 void ComplainNoMatchesFound() const {
9161 assert(Matches.empty());
9162 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9163 << OvlExpr->getName() << TargetFunctionType
9164 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009165 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009166 }
9167
9168 bool IsInvalidFormOfPointerToMemberFunction() const {
9169 return TargetTypeIsNonStaticMemberFunction &&
9170 !OvlExprInfo.HasFormOfMemberPointer;
9171 }
9172
9173 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9174 // TODO: Should we condition this on whether any functions might
9175 // have matched, or is it more appropriate to do that in callers?
9176 // TODO: a fixit wouldn't hurt.
9177 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9178 << TargetType << OvlExpr->getSourceRange();
9179 }
9180
9181 void ComplainOfInvalidConversion() const {
9182 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9183 << OvlExpr->getName() << TargetType;
9184 }
9185
9186 void ComplainMultipleMatchesFound() const {
9187 assert(Matches.size() > 1);
9188 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9189 << OvlExpr->getName()
9190 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009191 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009192 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009193
9194 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9195
Douglas Gregorb491ed32011-02-19 21:32:49 +00009196 int getNumMatches() const { return Matches.size(); }
9197
9198 FunctionDecl* getMatchingFunctionDecl() const {
9199 if (Matches.size() != 1) return 0;
9200 return Matches[0].second;
9201 }
9202
9203 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9204 if (Matches.size() != 1) return 0;
9205 return &Matches[0].first;
9206 }
9207};
9208
9209/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9210/// an overloaded function (C++ [over.over]), where @p From is an
9211/// expression with overloaded function type and @p ToType is the type
9212/// we're trying to resolve to. For example:
9213///
9214/// @code
9215/// int f(double);
9216/// int f(int);
9217///
9218/// int (*pfd)(double) = f; // selects f(double)
9219/// @endcode
9220///
9221/// This routine returns the resulting FunctionDecl if it could be
9222/// resolved, and NULL otherwise. When @p Complain is true, this
9223/// routine will emit diagnostics if there is an error.
9224FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009225Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9226 QualType TargetType,
9227 bool Complain,
9228 DeclAccessPair &FoundResult,
9229 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009230 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009231
9232 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9233 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009234 int NumMatches = Resolver.getNumMatches();
9235 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009236 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009237 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9238 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9239 else
9240 Resolver.ComplainNoMatchesFound();
9241 }
9242 else if (NumMatches > 1 && Complain)
9243 Resolver.ComplainMultipleMatchesFound();
9244 else if (NumMatches == 1) {
9245 Fn = Resolver.getMatchingFunctionDecl();
9246 assert(Fn);
9247 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009248 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009249 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009250 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009251
9252 if (pHadMultipleCandidates)
9253 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009254 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009255}
9256
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009257/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009258/// resolve that overloaded function expression down to a single function.
9259///
9260/// This routine can only resolve template-ids that refer to a single function
9261/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009262/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009263/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009264FunctionDecl *
9265Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9266 bool Complain,
9267 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009268 // C++ [over.over]p1:
9269 // [...] [Note: any redundant set of parentheses surrounding the
9270 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009271 // C++ [over.over]p1:
9272 // [...] The overloaded function name can be preceded by the &
9273 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009274
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009275 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009276 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009277 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009278
9279 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009280 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009281
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009282 // Look through all of the overloaded functions, searching for one
9283 // whose type matches exactly.
9284 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009285 for (UnresolvedSetIterator I = ovl->decls_begin(),
9286 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009287 // C++0x [temp.arg.explicit]p3:
9288 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009289 // where deduction is not done, if a template argument list is
9290 // specified and it, along with any default template arguments,
9291 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009292 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009293 FunctionTemplateDecl *FunctionTemplate
9294 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009295
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009296 // C++ [over.over]p2:
9297 // If the name is a function template, template argument deduction is
9298 // done (14.8.2.2), and if the argument deduction succeeds, the
9299 // resulting template argument list is used to generate a single
9300 // function template specialization, which is added to the set of
9301 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009302 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009303 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009304 if (TemplateDeductionResult Result
9305 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9306 Specialization, Info)) {
9307 // FIXME: make a note of the failed deduction for diagnostics.
9308 (void)Result;
9309 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009310 }
9311
John McCall0009fcc2011-04-26 20:42:42 +00009312 assert(Specialization && "no specialization and no error?");
9313
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009314 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009315 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009316 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009317 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9318 << ovl->getName();
9319 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009320 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009321 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009322 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009323
John McCall0009fcc2011-04-26 20:42:42 +00009324 Matched = Specialization;
9325 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009327
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009328 return Matched;
9329}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009330
Douglas Gregor1beec452011-03-12 01:48:56 +00009331
9332
9333
John McCall50a2c2c2011-10-11 23:14:30 +00009334// Resolve and fix an overloaded expression that can be resolved
9335// because it identifies a single function template specialization.
9336//
Douglas Gregor1beec452011-03-12 01:48:56 +00009337// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009338//
9339// Return true if it was logically possible to so resolve the
9340// expression, regardless of whether or not it succeeded. Always
9341// returns true if 'complain' is set.
9342bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9343 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9344 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009345 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009346 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009347 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009348
John McCall50a2c2c2011-10-11 23:14:30 +00009349 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009350
John McCall0009fcc2011-04-26 20:42:42 +00009351 DeclAccessPair found;
9352 ExprResult SingleFunctionExpression;
9353 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9354 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009355 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009356 SrcExpr = ExprError();
9357 return true;
9358 }
John McCall0009fcc2011-04-26 20:42:42 +00009359
9360 // It is only correct to resolve to an instance method if we're
9361 // resolving a form that's permitted to be a pointer to member.
9362 // Otherwise we'll end up making a bound member expression, which
9363 // is illegal in all the contexts we resolve like this.
9364 if (!ovl.HasFormOfMemberPointer &&
9365 isa<CXXMethodDecl>(fn) &&
9366 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009367 if (!complain) return false;
9368
9369 Diag(ovl.Expression->getExprLoc(),
9370 diag::err_bound_member_function)
9371 << 0 << ovl.Expression->getSourceRange();
9372
9373 // TODO: I believe we only end up here if there's a mix of
9374 // static and non-static candidates (otherwise the expression
9375 // would have 'bound member' type, not 'overload' type).
9376 // Ideally we would note which candidate was chosen and why
9377 // the static candidates were rejected.
9378 SrcExpr = ExprError();
9379 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009380 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009381
Sylvestre Ledrua5202662012-07-31 06:56:50 +00009382 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +00009383 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009384 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009385
9386 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009387 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009388 SingleFunctionExpression =
9389 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009390 if (SingleFunctionExpression.isInvalid()) {
9391 SrcExpr = ExprError();
9392 return true;
9393 }
9394 }
John McCall0009fcc2011-04-26 20:42:42 +00009395 }
9396
9397 if (!SingleFunctionExpression.isUsable()) {
9398 if (complain) {
9399 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9400 << ovl.Expression->getName()
9401 << DestTypeForComplaining
9402 << OpRangeForComplaining
9403 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009404 NoteAllOverloadCandidates(SrcExpr.get());
9405
9406 SrcExpr = ExprError();
9407 return true;
9408 }
9409
9410 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009411 }
9412
John McCall50a2c2c2011-10-11 23:14:30 +00009413 SrcExpr = SingleFunctionExpression;
9414 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009415}
9416
Douglas Gregorcabea402009-09-22 15:41:20 +00009417/// \brief Add a single candidate to the overload set.
9418static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009419 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009420 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009421 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009422 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009423 bool PartialOverloading,
9424 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009425 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009426 if (isa<UsingShadowDecl>(Callee))
9427 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9428
Douglas Gregorcabea402009-09-22 15:41:20 +00009429 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009430 if (ExplicitTemplateArgs) {
9431 assert(!KnownValid && "Explicit template arguments?");
9432 return;
9433 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009434 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9435 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009436 return;
John McCalld14a8642009-11-21 08:51:07 +00009437 }
9438
9439 if (FunctionTemplateDecl *FuncTemplate
9440 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009441 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009442 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009443 return;
9444 }
9445
Richard Smith95ce4f62011-06-26 22:19:54 +00009446 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009447}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009448
Douglas Gregorcabea402009-09-22 15:41:20 +00009449/// \brief Add the overload candidates named by callee and/or found by argument
9450/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009451void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009452 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009453 OverloadCandidateSet &CandidateSet,
9454 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009455
9456#ifndef NDEBUG
9457 // Verify that ArgumentDependentLookup is consistent with the rules
9458 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009459 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009460 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9461 // and let Y be the lookup set produced by argument dependent
9462 // lookup (defined as follows). If X contains
9463 //
9464 // -- a declaration of a class member, or
9465 //
9466 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009467 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009468 //
9469 // -- a declaration that is neither a function or a function
9470 // template
9471 //
9472 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009473
John McCall57500772009-12-16 12:17:52 +00009474 if (ULE->requiresADL()) {
9475 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9476 E = ULE->decls_end(); I != E; ++I) {
9477 assert(!(*I)->getDeclContext()->isRecord());
9478 assert(isa<UsingShadowDecl>(*I) ||
9479 !(*I)->getDeclContext()->isFunctionOrMethod());
9480 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009481 }
9482 }
9483#endif
9484
John McCall57500772009-12-16 12:17:52 +00009485 // It would be nice to avoid this copy.
9486 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009487 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009488 if (ULE->hasExplicitTemplateArgs()) {
9489 ULE->copyTemplateArgumentsInto(TABuffer);
9490 ExplicitTemplateArgs = &TABuffer;
9491 }
9492
9493 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9494 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009495 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9496 CandidateSet, PartialOverloading,
9497 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009498
John McCall57500772009-12-16 12:17:52 +00009499 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009500 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009501 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009502 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +00009503 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009504}
John McCalld681c392009-12-16 08:11:27 +00009505
Richard Smith998a5912011-06-05 22:42:48 +00009506/// Attempt to recover from an ill-formed use of a non-dependent name in a
9507/// template, where the non-dependent name was declared after the template
9508/// was defined. This is common in code written for a compilers which do not
9509/// correctly implement two-stage name lookup.
9510///
9511/// Returns true if a viable candidate was found and a diagnostic was issued.
9512static bool
9513DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9514 const CXXScopeSpec &SS, LookupResult &R,
9515 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009516 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009517 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9518 return false;
9519
9520 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009521 if (DC->isTransparentContext())
9522 continue;
9523
Richard Smith998a5912011-06-05 22:42:48 +00009524 SemaRef.LookupQualifiedName(R, DC);
9525
9526 if (!R.empty()) {
9527 R.suppressDiagnostics();
9528
9529 if (isa<CXXRecordDecl>(DC)) {
9530 // Don't diagnose names we find in classes; we get much better
9531 // diagnostics for these from DiagnoseEmptyLookup.
9532 R.clear();
9533 return false;
9534 }
9535
9536 OverloadCandidateSet Candidates(FnLoc);
9537 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9538 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009539 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009540 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009541
9542 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009543 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009544 // No viable functions. Don't bother the user with notes for functions
9545 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009546 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009547 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009548 }
Richard Smith998a5912011-06-05 22:42:48 +00009549
9550 // Find the namespaces where ADL would have looked, and suggest
9551 // declaring the function there instead.
9552 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9553 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00009554 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +00009555 AssociatedNamespaces,
9556 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +00009557 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckya21719d2012-11-13 00:08:34 +00009558 DeclContext *Std = SemaRef.getStdNamespace();
9559 for (Sema::AssociatedNamespaceSet::iterator
9560 it = AssociatedNamespaces.begin(),
9561 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith21bae432012-12-22 02:46:14 +00009562 // Never suggest declaring a function within namespace 'std'.
9563 if (Std && Std->Encloses(*it))
9564 continue;
9565
9566 // Never suggest declaring a function within a namespace with a reserved
9567 // name, like __gnu_cxx.
9568 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9569 if (NS &&
9570 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9571 continue;
9572
9573 SuggestedNamespaces.insert(*it);
Richard Smith998a5912011-06-05 22:42:48 +00009574 }
9575
9576 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9577 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009578 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009579 SemaRef.Diag(Best->Function->getLocation(),
9580 diag::note_not_found_by_two_phase_lookup)
9581 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009582 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009583 SemaRef.Diag(Best->Function->getLocation(),
9584 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009585 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009586 } else {
9587 // FIXME: It would be useful to list the associated namespaces here,
9588 // but the diagnostics infrastructure doesn't provide a way to produce
9589 // a localized representation of a list of items.
9590 SemaRef.Diag(Best->Function->getLocation(),
9591 diag::note_not_found_by_two_phase_lookup)
9592 << R.getLookupName() << 2;
9593 }
9594
9595 // Try to recover by calling this function.
9596 return true;
9597 }
9598
9599 R.clear();
9600 }
9601
9602 return false;
9603}
9604
9605/// Attempt to recover from ill-formed use of a non-dependent operator in a
9606/// template, where the non-dependent operator was declared after the template
9607/// was defined.
9608///
9609/// Returns true if a viable candidate was found and a diagnostic was issued.
9610static bool
9611DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9612 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009613 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009614 DeclarationName OpName =
9615 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9616 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9617 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009618 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009619}
9620
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009621namespace {
9622// Callback to limit the allowed keywords and to only accept typo corrections
9623// that are keywords or whose decls refer to functions (or template functions)
9624// that accept the given number of arguments.
9625class RecoveryCallCCC : public CorrectionCandidateCallback {
9626 public:
9627 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9628 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009629 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009630 WantRemainingKeywords = false;
9631 }
9632
9633 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9634 if (!candidate.getCorrectionDecl())
9635 return candidate.isKeyword();
9636
9637 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9638 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9639 FunctionDecl *FD = 0;
9640 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9641 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9642 FD = FTD->getTemplatedDecl();
9643 if (!HasExplicitTemplateArgs && !FD) {
9644 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9645 // If the Decl is neither a function nor a template function,
9646 // determine if it is a pointer or reference to a function. If so,
9647 // check against the number of arguments expected for the pointee.
9648 QualType ValType = cast<ValueDecl>(ND)->getType();
9649 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9650 ValType = ValType->getPointeeType();
9651 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9652 if (FPT->getNumArgs() == NumArgs)
9653 return true;
9654 }
9655 }
9656 if (FD && FD->getNumParams() >= NumArgs &&
9657 FD->getMinRequiredArguments() <= NumArgs)
9658 return true;
9659 }
9660 return false;
9661 }
9662
9663 private:
9664 unsigned NumArgs;
9665 bool HasExplicitTemplateArgs;
9666};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009667
9668// Callback that effectively disabled typo correction
9669class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9670 public:
9671 NoTypoCorrectionCCC() {
9672 WantTypeSpecifiers = false;
9673 WantExpressionKeywords = false;
9674 WantCXXNamedCasts = false;
9675 WantRemainingKeywords = false;
9676 }
9677
9678 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9679 return false;
9680 }
9681};
Richard Smith88d67f32012-09-25 04:46:05 +00009682
9683class BuildRecoveryCallExprRAII {
9684 Sema &SemaRef;
9685public:
9686 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9687 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9688 SemaRef.IsBuildingRecoveryCallExpr = true;
9689 }
9690
9691 ~BuildRecoveryCallExprRAII() {
9692 SemaRef.IsBuildingRecoveryCallExpr = false;
9693 }
9694};
9695
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009696}
9697
John McCalld681c392009-12-16 08:11:27 +00009698/// Attempts to recover from a call where no functions were found.
9699///
9700/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009701static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009702BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009703 UnresolvedLookupExpr *ULE,
9704 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009705 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009706 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009707 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +00009708 // Do not try to recover if it is already building a recovery call.
9709 // This stops infinite loops for template instantiations like
9710 //
9711 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9712 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9713 //
9714 if (SemaRef.IsBuildingRecoveryCallExpr)
9715 return ExprError();
9716 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +00009717
9718 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009719 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009720 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009721
John McCall57500772009-12-16 12:17:52 +00009722 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009723 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009724 if (ULE->hasExplicitTemplateArgs()) {
9725 ULE->copyTemplateArgumentsInto(TABuffer);
9726 ExplicitTemplateArgs = &TABuffer;
9727 }
9728
John McCalld681c392009-12-16 08:11:27 +00009729 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9730 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009731 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009732 NoTypoCorrectionCCC RejectAll;
9733 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9734 (CorrectionCandidateCallback*)&Validator :
9735 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009736 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009737 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009738 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009739 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009740 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009741 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009742
John McCall57500772009-12-16 12:17:52 +00009743 assert(!R.empty() && "lookup results empty despite recovery");
9744
9745 // Build an implicit member call if appropriate. Just drop the
9746 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009747 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009748 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009749 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9750 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009751 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009752 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009753 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009754 else
9755 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9756
9757 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009758 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009759
9760 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009761 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009762 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009763 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009764 MultiExprArg(Args.data(), Args.size()),
9765 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009766}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009767
Sam Panzer0f384432012-08-21 00:52:01 +00009768/// \brief Constructs and populates an OverloadedCandidateSet from
9769/// the given function.
9770/// \returns true when an the ExprResult output parameter has been set.
9771bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9772 UnresolvedLookupExpr *ULE,
9773 Expr **Args, unsigned NumArgs,
9774 SourceLocation RParenLoc,
9775 OverloadCandidateSet *CandidateSet,
9776 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +00009777#ifndef NDEBUG
9778 if (ULE->requiresADL()) {
9779 // To do ADL, we must have found an unqualified name.
9780 assert(!ULE->getQualifier() && "qualified name with ADL");
9781
9782 // We don't perform ADL for implicit declarations of builtins.
9783 // Verify that this was correctly set up.
9784 FunctionDecl *F;
9785 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9786 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9787 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009788 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009789
John McCall57500772009-12-16 12:17:52 +00009790 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009791 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +00009792 }
John McCall57500772009-12-16 12:17:52 +00009793#endif
9794
John McCall4124c492011-10-17 18:40:02 +00009795 UnbridgedCastsSet UnbridgedCasts;
Sam Panzer0f384432012-08-21 00:52:01 +00009796 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9797 *Result = ExprError();
9798 return true;
9799 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009800
John McCall57500772009-12-16 12:17:52 +00009801 // Add the functions denoted by the callee to the set of candidate
9802 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009803 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzer0f384432012-08-21 00:52:01 +00009804 *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009805
9806 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009807 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9808 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +00009809 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009810 // In Microsoft mode, if we are inside a template class member function then
9811 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009812 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009813 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009814 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009815 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00009816 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9817 llvm::makeArrayRef(Args, NumArgs),
9818 Context.DependentTy, VK_RValue,
9819 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009820 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +00009821 *Result = Owned(CE);
9822 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009823 }
Sam Panzer0f384432012-08-21 00:52:01 +00009824 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +00009825 }
John McCalld681c392009-12-16 08:11:27 +00009826
John McCall4124c492011-10-17 18:40:02 +00009827 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +00009828 return false;
9829}
John McCall4124c492011-10-17 18:40:02 +00009830
Sam Panzer0f384432012-08-21 00:52:01 +00009831/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9832/// the completed call expression. If overload resolution fails, emits
9833/// diagnostics and returns ExprError()
9834static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9835 UnresolvedLookupExpr *ULE,
9836 SourceLocation LParenLoc,
9837 Expr **Args, unsigned NumArgs,
9838 SourceLocation RParenLoc,
9839 Expr *ExecConfig,
9840 OverloadCandidateSet *CandidateSet,
9841 OverloadCandidateSet::iterator *Best,
9842 OverloadingResult OverloadResult,
9843 bool AllowTypoCorrection) {
9844 if (CandidateSet->empty())
9845 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9846 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9847 RParenLoc, /*EmptyLookup=*/true,
9848 AllowTypoCorrection);
9849
9850 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +00009851 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +00009852 FunctionDecl *FDecl = (*Best)->Function;
9853 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9854 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9855 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9856 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9857 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9858 RParenLoc, ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009859 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009860
Richard Smith998a5912011-06-05 22:42:48 +00009861 case OR_No_Viable_Function: {
9862 // Try to recover by looking for viable functions which the user might
9863 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +00009864 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009865 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9866 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009867 /*EmptyLookup=*/false,
9868 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009869 if (!Recovery.isInvalid())
9870 return Recovery;
9871
Sam Panzer0f384432012-08-21 00:52:01 +00009872 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009873 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009874 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009875 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9876 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009877 break;
Richard Smith998a5912011-06-05 22:42:48 +00009878 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009879
9880 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +00009881 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009882 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009883 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9884 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009885 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009886
Sam Panzer0f384432012-08-21 00:52:01 +00009887 case OR_Deleted: {
9888 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9889 << (*Best)->Function->isDeleted()
9890 << ULE->getName()
9891 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9892 << Fn->getSourceRange();
9893 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9894 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009895
Sam Panzer0f384432012-08-21 00:52:01 +00009896 // We emitted an error for the unvailable/deleted function call but keep
9897 // the call in the AST.
9898 FunctionDecl *FDecl = (*Best)->Function;
9899 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9900 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9901 RParenLoc, ExecConfig);
9902 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009903 }
9904
Douglas Gregorb412e172010-07-25 18:17:45 +00009905 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009906 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009907}
9908
Sam Panzer0f384432012-08-21 00:52:01 +00009909/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9910/// (which eventually refers to the declaration Func) and the call
9911/// arguments Args/NumArgs, attempt to resolve the function call down
9912/// to a specific function. If overload resolution succeeds, returns
9913/// the call expression produced by overload resolution.
9914/// Otherwise, emits diagnostics and returns ExprError.
9915ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9916 UnresolvedLookupExpr *ULE,
9917 SourceLocation LParenLoc,
9918 Expr **Args, unsigned NumArgs,
9919 SourceLocation RParenLoc,
9920 Expr *ExecConfig,
9921 bool AllowTypoCorrection) {
9922 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9923 ExprResult result;
9924
9925 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9926 &CandidateSet, &result))
9927 return result;
9928
9929 OverloadCandidateSet::iterator Best;
9930 OverloadingResult OverloadResult =
9931 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9932
9933 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9934 RParenLoc, ExecConfig, &CandidateSet,
9935 &Best, OverloadResult,
9936 AllowTypoCorrection);
9937}
9938
John McCall4c4c1df2010-01-26 03:27:55 +00009939static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009940 return Functions.size() > 1 ||
9941 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9942}
9943
Douglas Gregor084d8552009-03-13 23:49:33 +00009944/// \brief Create a unary operation that may resolve to an overloaded
9945/// operator.
9946///
9947/// \param OpLoc The location of the operator itself (e.g., '*').
9948///
9949/// \param OpcIn The UnaryOperator::Opcode that describes this
9950/// operator.
9951///
James Dennett18348b62012-06-22 08:52:37 +00009952/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009953/// considered by overload resolution. The caller needs to build this
9954/// set based on the context using, e.g.,
9955/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9956/// set should not contain any member functions; those will be added
9957/// by CreateOverloadedUnaryOp().
9958///
James Dennett91738ff2012-06-22 10:32:46 +00009959/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009960ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009961Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9962 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009963 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009964 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009965
9966 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9967 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9968 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009969 // TODO: provide better source location info.
9970 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009971
John McCall4124c492011-10-17 18:40:02 +00009972 if (checkPlaceholderForOverload(*this, Input))
9973 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009974
Douglas Gregor084d8552009-03-13 23:49:33 +00009975 Expr *Args[2] = { Input, 0 };
9976 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009977
Douglas Gregor084d8552009-03-13 23:49:33 +00009978 // For post-increment and post-decrement, add the implicit '0' as
9979 // the second argument, so that we know this is a post-increment or
9980 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009981 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009982 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009983 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9984 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009985 NumArgs = 2;
9986 }
9987
9988 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009989 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009990 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009991 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009992 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009993 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009994 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009995
John McCall58cc69d2010-01-27 01:50:18 +00009996 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009997 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009998 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009999 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010000 /*ADL*/ true, IsOverloaded(Fns),
10001 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +000010002 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010003 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor084d8552009-03-13 23:49:33 +000010004 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010005 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010006 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010007 }
10008
10009 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010010 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010011
10012 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010013 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10014 false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010015
10016 // Add operator candidates that are member functions.
10017 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10018
John McCall4c4c1df2010-01-26 03:27:55 +000010019 // Add candidates from ADL.
10020 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010021 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +000010022 /*ExplicitTemplateArgs*/ 0,
10023 CandidateSet);
10024
Douglas Gregor084d8552009-03-13 23:49:33 +000010025 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010026 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010027
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010028 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10029
Douglas Gregor084d8552009-03-13 23:49:33 +000010030 // Perform overload resolution.
10031 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010032 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010033 case OR_Success: {
10034 // We found a built-in operator or an overloaded operator.
10035 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010036
Douglas Gregor084d8552009-03-13 23:49:33 +000010037 if (FnDecl) {
10038 // We matched an overloaded operator. Build a call to that
10039 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010040
Eli Friedmanfa0df832012-02-02 03:46:19 +000010041 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010042
Douglas Gregor084d8552009-03-13 23:49:33 +000010043 // Convert the arguments.
10044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010045 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010046
John Wiegley01296292011-04-08 18:41:53 +000010047 ExprResult InputRes =
10048 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10049 Best->FoundDecl, Method);
10050 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010051 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010052 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010053 } else {
10054 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010055 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010056 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010057 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010058 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010059 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010060 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010061 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010062 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010063 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010064 }
10065
John McCall4fa0d5f2010-05-06 18:15:07 +000010066 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10067
John McCall7decc9e2010-11-18 06:31:45 +000010068 // Determine the result type.
10069 QualType ResultTy = FnDecl->getResultType();
10070 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10071 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +000010072
Douglas Gregor084d8552009-03-13 23:49:33 +000010073 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010074 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010075 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010076 if (FnExpr.isInvalid())
10077 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010078
Eli Friedman030eee42009-11-18 03:58:17 +000010079 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010080 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010081 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010082 llvm::makeArrayRef(Args, NumArgs),
Lang Hames5de91cc2012-10-02 04:45:10 +000010083 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010084
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010085 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010086 FnDecl))
10087 return ExprError();
10088
John McCallb268a282010-08-23 23:25:46 +000010089 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010090 } else {
10091 // We matched a built-in operator. Convert the arguments, then
10092 // break out so that we will build the appropriate built-in
10093 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010094 ExprResult InputRes =
10095 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10096 Best->Conversions[0], AA_Passing);
10097 if (InputRes.isInvalid())
10098 return ExprError();
10099 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010100 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010101 }
John Wiegley01296292011-04-08 18:41:53 +000010102 }
10103
10104 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010105 // This is an erroneous use of an operator which can be overloaded by
10106 // a non-member function. Check for non-member operators which were
10107 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010108 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10109 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010110 // FIXME: Recover by calling the found function.
10111 return ExprError();
10112
John Wiegley01296292011-04-08 18:41:53 +000010113 // No viable function; fall through to handling this as a
10114 // built-in operator, which will produce an error message for us.
10115 break;
10116
10117 case OR_Ambiguous:
10118 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10119 << UnaryOperator::getOpcodeStr(Opc)
10120 << Input->getType()
10121 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010122 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10123 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010124 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10125 return ExprError();
10126
10127 case OR_Deleted:
10128 Diag(OpLoc, diag::err_ovl_deleted_oper)
10129 << Best->Function->isDeleted()
10130 << UnaryOperator::getOpcodeStr(Opc)
10131 << getDeletedOrUnavailableSuffix(Best->Function)
10132 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010133 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10134 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010135 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010136 return ExprError();
10137 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010138
10139 // Either we found no viable overloaded operator or we matched a
10140 // built-in operator. In either case, fall through to trying to
10141 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010142 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010143}
10144
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010145/// \brief Create a binary operation that may resolve to an overloaded
10146/// operator.
10147///
10148/// \param OpLoc The location of the operator itself (e.g., '+').
10149///
10150/// \param OpcIn The BinaryOperator::Opcode that describes this
10151/// operator.
10152///
James Dennett18348b62012-06-22 08:52:37 +000010153/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010154/// considered by overload resolution. The caller needs to build this
10155/// set based on the context using, e.g.,
10156/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10157/// set should not contain any member functions; those will be added
10158/// by CreateOverloadedBinOp().
10159///
10160/// \param LHS Left-hand argument.
10161/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010162ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010163Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010164 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010165 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010166 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010167 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010168 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010169
10170 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10171 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10172 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10173
10174 // If either side is type-dependent, create an appropriate dependent
10175 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010176 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010177 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010178 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010179 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010180 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010181 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010182 Context.DependentTy,
10183 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010184 OpLoc,
10185 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010186
Douglas Gregor5287f092009-11-05 00:51:44 +000010187 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10188 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010189 VK_LValue,
10190 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010191 Context.DependentTy,
10192 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010193 OpLoc,
10194 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010195 }
John McCall4c4c1df2010-01-26 03:27:55 +000010196
10197 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010198 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010199 // TODO: provide better source location info in DNLoc component.
10200 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010201 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010202 = UnresolvedLookupExpr::Create(Context, NamingClass,
10203 NestedNameSpecifierLoc(), OpNameInfo,
10204 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010205 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010206 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10207 Context.DependentTy, VK_RValue,
10208 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010209 }
10210
John McCall4124c492011-10-17 18:40:02 +000010211 // Always do placeholder-like conversions on the RHS.
10212 if (checkPlaceholderForOverload(*this, Args[1]))
10213 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010214
John McCall526ab472011-10-25 17:37:35 +000010215 // Do placeholder-like conversion on the LHS; note that we should
10216 // not get here with a PseudoObject LHS.
10217 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010218 if (checkPlaceholderForOverload(*this, Args[0]))
10219 return ExprError();
10220
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010221 // If this is the assignment operator, we only perform overload resolution
10222 // if the left-hand side is a class or enumeration type. This is actually
10223 // a hack. The standard requires that we do overload resolution between the
10224 // various built-in candidates, but as DR507 points out, this can lead to
10225 // problems. So we do it this way, which pretty much follows what GCC does.
10226 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010227 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010228 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010229
John McCalle26a8722010-12-04 08:14:53 +000010230 // If this is the .* operator, which is not overloadable, just
10231 // create a built-in binary operator.
10232 if (Opc == BO_PtrMemD)
10233 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10234
Douglas Gregor084d8552009-03-13 23:49:33 +000010235 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010236 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010237
10238 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010239 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010240
10241 // Add operator candidates that are member functions.
10242 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10243
John McCall4c4c1df2010-01-26 03:27:55 +000010244 // Add candidates from ADL.
10245 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010246 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010247 /*ExplicitTemplateArgs*/ 0,
10248 CandidateSet);
10249
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010250 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010251 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010252
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010253 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10254
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010255 // Perform overload resolution.
10256 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010257 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010258 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010259 // We found a built-in operator or an overloaded operator.
10260 FunctionDecl *FnDecl = Best->Function;
10261
10262 if (FnDecl) {
10263 // We matched an overloaded operator. Build a call to that
10264 // operator.
10265
Eli Friedmanfa0df832012-02-02 03:46:19 +000010266 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010267
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010268 // Convert the arguments.
10269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010270 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010271 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010272
Chandler Carruth8e543b32010-12-12 08:17:55 +000010273 ExprResult Arg1 =
10274 PerformCopyInitialization(
10275 InitializedEntity::InitializeParameter(Context,
10276 FnDecl->getParamDecl(0)),
10277 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010278 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010279 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010280
John Wiegley01296292011-04-08 18:41:53 +000010281 ExprResult Arg0 =
10282 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10283 Best->FoundDecl, Method);
10284 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010285 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010286 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010287 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010288 } else {
10289 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010290 ExprResult Arg0 = PerformCopyInitialization(
10291 InitializedEntity::InitializeParameter(Context,
10292 FnDecl->getParamDecl(0)),
10293 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010294 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010295 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010296
Chandler Carruth8e543b32010-12-12 08:17:55 +000010297 ExprResult Arg1 =
10298 PerformCopyInitialization(
10299 InitializedEntity::InitializeParameter(Context,
10300 FnDecl->getParamDecl(1)),
10301 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010302 if (Arg1.isInvalid())
10303 return ExprError();
10304 Args[0] = LHS = Arg0.takeAs<Expr>();
10305 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010306 }
10307
John McCall4fa0d5f2010-05-06 18:15:07 +000010308 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10309
John McCall7decc9e2010-11-18 06:31:45 +000010310 // Determine the result type.
10311 QualType ResultTy = FnDecl->getResultType();
10312 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10313 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010314
10315 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010316 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10317 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010318 if (FnExpr.isInvalid())
10319 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010320
John McCallb268a282010-08-23 23:25:46 +000010321 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010322 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010323 Args, ResultTy, VK, OpLoc,
10324 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010325
10326 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010327 FnDecl))
10328 return ExprError();
10329
John McCallb268a282010-08-23 23:25:46 +000010330 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010331 } else {
10332 // We matched a built-in operator. Convert the arguments, then
10333 // break out so that we will build the appropriate built-in
10334 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010335 ExprResult ArgsRes0 =
10336 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10337 Best->Conversions[0], AA_Passing);
10338 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010339 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010340 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010341
John Wiegley01296292011-04-08 18:41:53 +000010342 ExprResult ArgsRes1 =
10343 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10344 Best->Conversions[1], AA_Passing);
10345 if (ArgsRes1.isInvalid())
10346 return ExprError();
10347 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010348 break;
10349 }
10350 }
10351
Douglas Gregor66950a32009-09-30 21:46:01 +000010352 case OR_No_Viable_Function: {
10353 // C++ [over.match.oper]p9:
10354 // If the operator is the operator , [...] and there are no
10355 // viable functions, then the operator is assumed to be the
10356 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010357 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010358 break;
10359
Chandler Carruth8e543b32010-12-12 08:17:55 +000010360 // For class as left operand for assignment or compound assigment
10361 // operator do not fall through to handling in built-in, but report that
10362 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010363 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010364 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010365 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010366 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10367 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010368 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010369 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010370 // This is an erroneous use of an operator which can be overloaded by
10371 // a non-member function. Check for non-member operators which were
10372 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010373 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010374 // FIXME: Recover by calling the found function.
10375 return ExprError();
10376
Douglas Gregor66950a32009-09-30 21:46:01 +000010377 // No viable function; try to create a built-in operation, which will
10378 // produce an error. Then, show the non-viable candidates.
10379 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010381 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010382 "C++ binary operator overloading is missing candidates!");
10383 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010384 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010385 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010386 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000010387 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010388
10389 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010390 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010391 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010392 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010393 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010394 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010395 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010396 return ExprError();
10397
10398 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010399 if (isImplicitlyDeleted(Best->Function)) {
10400 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10401 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000010402 << Context.getRecordType(Method->getParent())
10403 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010404
Richard Smithde1a4872012-12-28 12:23:24 +000010405 // The user probably meant to call this special member. Just
10406 // explain why it's deleted.
10407 NoteDeletedFunction(Method);
10408 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000010409 } else {
10410 Diag(OpLoc, diag::err_ovl_deleted_oper)
10411 << Best->Function->isDeleted()
10412 << BinaryOperator::getOpcodeStr(Opc)
10413 << getDeletedOrUnavailableSuffix(Best->Function)
10414 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10415 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010416 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010417 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010418 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010419 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010420
Douglas Gregor66950a32009-09-30 21:46:01 +000010421 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010422 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010423}
10424
John McCalldadc5752010-08-24 06:29:42 +000010425ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010426Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10427 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010428 Expr *Base, Expr *Idx) {
10429 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010430 DeclarationName OpName =
10431 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10432
10433 // If either side is type-dependent, create an appropriate dependent
10434 // expression.
10435 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10436
John McCall58cc69d2010-01-27 01:50:18 +000010437 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010438 // CHECKME: no 'operator' keyword?
10439 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10440 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010441 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010442 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010443 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010444 /*ADL*/ true, /*Overloaded*/ false,
10445 UnresolvedSetIterator(),
10446 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010447 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010448
Sebastian Redladba46e2009-10-29 20:17:01 +000010449 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010450 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000010451 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010452 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010453 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000010454 }
10455
John McCall4124c492011-10-17 18:40:02 +000010456 // Handle placeholders on both operands.
10457 if (checkPlaceholderForOverload(*this, Args[0]))
10458 return ExprError();
10459 if (checkPlaceholderForOverload(*this, Args[1]))
10460 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010461
Sebastian Redladba46e2009-10-29 20:17:01 +000010462 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010463 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010464
10465 // Subscript can only be overloaded as a member function.
10466
10467 // Add operator candidates that are member functions.
10468 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10469
10470 // Add builtin operator candidates.
10471 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10472
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010473 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10474
Sebastian Redladba46e2009-10-29 20:17:01 +000010475 // Perform overload resolution.
10476 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010477 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010478 case OR_Success: {
10479 // We found a built-in operator or an overloaded operator.
10480 FunctionDecl *FnDecl = Best->Function;
10481
10482 if (FnDecl) {
10483 // We matched an overloaded operator. Build a call to that
10484 // operator.
10485
Eli Friedmanfa0df832012-02-02 03:46:19 +000010486 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010487
John McCalla0296f72010-03-19 07:35:19 +000010488 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010489 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010490
Sebastian Redladba46e2009-10-29 20:17:01 +000010491 // Convert the arguments.
10492 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010493 ExprResult Arg0 =
10494 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10495 Best->FoundDecl, Method);
10496 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010497 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010498 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010499
Anders Carlssona68e51e2010-01-29 18:37:50 +000010500 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010501 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010502 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010503 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010504 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010505 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010506 Owned(Args[1]));
10507 if (InputInit.isInvalid())
10508 return ExprError();
10509
10510 Args[1] = InputInit.takeAs<Expr>();
10511
Sebastian Redladba46e2009-10-29 20:17:01 +000010512 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010513 QualType ResultTy = FnDecl->getResultType();
10514 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10515 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010516
10517 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010518 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10519 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010520 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10521 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010522 OpLocInfo.getLoc(),
10523 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010524 if (FnExpr.isInvalid())
10525 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010526
John McCallb268a282010-08-23 23:25:46 +000010527 CXXOperatorCallExpr *TheCall =
10528 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010529 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000010530 ResultTy, VK, RLoc,
10531 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000010532
John McCallb268a282010-08-23 23:25:46 +000010533 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010534 FnDecl))
10535 return ExprError();
10536
John McCallb268a282010-08-23 23:25:46 +000010537 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010538 } else {
10539 // We matched a built-in operator. Convert the arguments, then
10540 // break out so that we will build the appropriate built-in
10541 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010542 ExprResult ArgsRes0 =
10543 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10544 Best->Conversions[0], AA_Passing);
10545 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010546 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010547 Args[0] = ArgsRes0.take();
10548
10549 ExprResult ArgsRes1 =
10550 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10551 Best->Conversions[1], AA_Passing);
10552 if (ArgsRes1.isInvalid())
10553 return ExprError();
10554 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010555
10556 break;
10557 }
10558 }
10559
10560 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010561 if (CandidateSet.empty())
10562 Diag(LLoc, diag::err_ovl_no_oper)
10563 << Args[0]->getType() << /*subscript*/ 0
10564 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10565 else
10566 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10567 << Args[0]->getType()
10568 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010569 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010570 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010571 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010572 }
10573
10574 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010575 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010576 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010577 << Args[0]->getType() << Args[1]->getType()
10578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010579 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010580 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010581 return ExprError();
10582
10583 case OR_Deleted:
10584 Diag(LLoc, diag::err_ovl_deleted_oper)
10585 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010586 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010587 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010588 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010589 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010590 return ExprError();
10591 }
10592
10593 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010594 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010595}
10596
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010597/// BuildCallToMemberFunction - Build a call to a member
10598/// function. MemExpr is the expression that refers to the member
10599/// function (and includes the object parameter), Args/NumArgs are the
10600/// arguments to the function call (not including the object
10601/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010602/// expression refers to a non-static member function or an overloaded
10603/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010604ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010605Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10606 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010607 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010608 assert(MemExprE->getType() == Context.BoundMemberTy ||
10609 MemExprE->getType() == Context.OverloadTy);
10610
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010611 // Dig out the member expression. This holds both the object
10612 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010613 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010614
John McCall0009fcc2011-04-26 20:42:42 +000010615 // Determine whether this is a call to a pointer-to-member function.
10616 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10617 assert(op->getType() == Context.BoundMemberTy);
10618 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10619
10620 QualType fnType =
10621 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10622
10623 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10624 QualType resultType = proto->getCallResultType(Context);
10625 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10626
10627 // Check that the object type isn't more qualified than the
10628 // member function we're calling.
10629 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10630
10631 QualType objectType = op->getLHS()->getType();
10632 if (op->getOpcode() == BO_PtrMemI)
10633 objectType = objectType->castAs<PointerType>()->getPointeeType();
10634 Qualifiers objectQuals = objectType.getQualifiers();
10635
10636 Qualifiers difference = objectQuals - funcQuals;
10637 difference.removeObjCGCAttr();
10638 difference.removeAddressSpace();
10639 if (difference) {
10640 std::string qualsString = difference.getAsString();
10641 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10642 << fnType.getUnqualifiedType()
10643 << qualsString
10644 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10645 }
10646
10647 CXXMemberCallExpr *call
Benjamin Kramerc215e762012-08-24 11:54:20 +000010648 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10649 llvm::makeArrayRef(Args, NumArgs),
John McCall0009fcc2011-04-26 20:42:42 +000010650 resultType, valueKind, RParenLoc);
10651
10652 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010653 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010654 call, 0))
10655 return ExprError();
10656
10657 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10658 return ExprError();
10659
10660 return MaybeBindToTemporary(call);
10661 }
10662
John McCall4124c492011-10-17 18:40:02 +000010663 UnbridgedCastsSet UnbridgedCasts;
10664 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10665 return ExprError();
10666
John McCall10eae182009-11-30 22:42:35 +000010667 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010668 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010669 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010670 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010671 if (isa<MemberExpr>(NakedMemExpr)) {
10672 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010673 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010674 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010675 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010676 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010677 } else {
10678 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010679 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010680
John McCall6e9f8f62009-12-03 04:06:58 +000010681 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010682 Expr::Classification ObjectClassification
10683 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10684 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010685
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010686 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010687 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010688
John McCall2d74de92009-12-01 22:10:20 +000010689 // FIXME: avoid copy.
10690 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10691 if (UnresExpr->hasExplicitTemplateArgs()) {
10692 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10693 TemplateArgs = &TemplateArgsBuffer;
10694 }
10695
John McCall10eae182009-11-30 22:42:35 +000010696 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10697 E = UnresExpr->decls_end(); I != E; ++I) {
10698
John McCall6e9f8f62009-12-03 04:06:58 +000010699 NamedDecl *Func = *I;
10700 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10701 if (isa<UsingShadowDecl>(Func))
10702 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10703
Douglas Gregor02824322011-01-26 19:30:28 +000010704
Francois Pichet64225792011-01-18 05:04:39 +000010705 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010706 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010707 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10708 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010709 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010710 // If explicit template arguments were provided, we can't call a
10711 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010712 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010713 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010714
John McCalla0296f72010-03-19 07:35:19 +000010715 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010716 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010717 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010718 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010719 } else {
John McCall10eae182009-11-30 22:42:35 +000010720 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010721 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010722 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010723 llvm::makeArrayRef(Args, NumArgs),
10724 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010725 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010726 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010727 }
Mike Stump11289f42009-09-09 15:08:12 +000010728
John McCall10eae182009-11-30 22:42:35 +000010729 DeclarationName DeclName = UnresExpr->getMemberName();
10730
John McCall4124c492011-10-17 18:40:02 +000010731 UnbridgedCasts.restore();
10732
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010733 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010734 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010735 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010736 case OR_Success:
10737 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010738 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010739 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010740 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010741 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010742 break;
10743
10744 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010745 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010746 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010747 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010748 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10749 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010752
10753 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010754 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010755 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010756 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10757 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010758 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010759 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010760
10761 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010762 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010763 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010764 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010765 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010766 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010767 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10768 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010769 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010770 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010771 }
10772
John McCall16df1e52010-03-30 21:47:33 +000010773 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010774
John McCall2d74de92009-12-01 22:10:20 +000010775 // If overload resolution picked a static member, build a
10776 // non-member call based on that function.
10777 if (Method->isStatic()) {
10778 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10779 Args, NumArgs, RParenLoc);
10780 }
10781
John McCall10eae182009-11-30 22:42:35 +000010782 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010783 }
10784
John McCall7decc9e2010-11-18 06:31:45 +000010785 QualType ResultType = Method->getResultType();
10786 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10787 ResultType = ResultType.getNonLValueExprType(Context);
10788
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010789 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010790 CXXMemberCallExpr *TheCall =
Benjamin Kramerc215e762012-08-24 11:54:20 +000010791 new (Context) CXXMemberCallExpr(Context, MemExprE,
10792 llvm::makeArrayRef(Args, NumArgs),
John McCall7decc9e2010-11-18 06:31:45 +000010793 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010794
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010795 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010796 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010797 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010798 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010799
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010800 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010801 // We only need to do this if there was actually an overload; otherwise
10802 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010803 if (!Method->isStatic()) {
10804 ExprResult ObjectArg =
10805 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10806 FoundDecl, Method);
10807 if (ObjectArg.isInvalid())
10808 return ExprError();
10809 MemExpr->setBase(ObjectArg.take());
10810 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010811
10812 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010813 const FunctionProtoType *Proto =
10814 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010815 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010816 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010817 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010818
Eli Friedmanff4b4072012-02-18 04:48:30 +000010819 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10820
Richard Smith55ce3522012-06-25 20:30:08 +000010821 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000010822 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010823
Anders Carlsson47061ee2011-05-06 14:25:31 +000010824 if ((isa<CXXConstructorDecl>(CurContext) ||
10825 isa<CXXDestructorDecl>(CurContext)) &&
10826 TheCall->getMethodDecl()->isPure()) {
10827 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10828
Chandler Carruth59259262011-06-27 08:31:58 +000010829 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010830 Diag(MemExpr->getLocStart(),
10831 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10832 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10833 << MD->getParent()->getDeclName();
10834
10835 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010836 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010837 }
John McCallb268a282010-08-23 23:25:46 +000010838 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010839}
10840
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010841/// BuildCallToObjectOfClassType - Build a call to an object of class
10842/// type (C++ [over.call.object]), which can end up invoking an
10843/// overloaded function call operator (@c operator()) or performing a
10844/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010845ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010846Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010847 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010848 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010849 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010850 if (checkPlaceholderForOverload(*this, Obj))
10851 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010852 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010853
10854 UnbridgedCastsSet UnbridgedCasts;
10855 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10856 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010857
John Wiegley01296292011-04-08 18:41:53 +000010858 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10859 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010860
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010861 // C++ [over.call.object]p1:
10862 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010863 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010864 // candidate functions includes at least the function call
10865 // operators of T. The function call operators of T are obtained by
10866 // ordinary lookup of the name operator() in the context of
10867 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010868 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010869 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010870
John Wiegley01296292011-04-08 18:41:53 +000010871 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010872 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010873 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010874
John McCall27b18f82009-11-17 02:14:36 +000010875 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10876 LookupQualifiedName(R, Record->getDecl());
10877 R.suppressDiagnostics();
10878
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010879 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010880 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010881 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10882 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010883 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010885
Douglas Gregorab7897a2008-11-19 22:57:39 +000010886 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010887 // In addition, for each (non-explicit in C++0x) conversion function
10888 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010889 //
10890 // operator conversion-type-id () cv-qualifier;
10891 //
10892 // where cv-qualifier is the same cv-qualification as, or a
10893 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010894 // denotes the type "pointer to function of (P1,...,Pn) returning
10895 // R", or the type "reference to pointer to function of
10896 // (P1,...,Pn) returning R", or the type "reference to function
10897 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010898 // is also considered as a candidate function. Similarly,
10899 // surrogate call functions are added to the set of candidate
10900 // functions for each conversion function declared in an
10901 // accessible base class provided the function is not hidden
10902 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010903 std::pair<CXXRecordDecl::conversion_iterator,
10904 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010905 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010906 for (CXXRecordDecl::conversion_iterator
10907 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010908 NamedDecl *D = *I;
10909 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10910 if (isa<UsingShadowDecl>(D))
10911 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010912
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010913 // Skip over templated conversion functions; they aren't
10914 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010915 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010916 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010917
John McCall6e9f8f62009-12-03 04:06:58 +000010918 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010919 if (!Conv->isExplicit()) {
10920 // Strip the reference type (if any) and then the pointer type (if
10921 // any) to get down to what might be a function type.
10922 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10923 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10924 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010925
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010926 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10927 {
10928 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010929 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10930 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010931 }
10932 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010933 }
Mike Stump11289f42009-09-09 15:08:12 +000010934
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010935 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10936
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010937 // Perform overload resolution.
10938 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010939 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010940 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010941 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010942 // Overload resolution succeeded; we'll build the appropriate call
10943 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010944 break;
10945
10946 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010947 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010948 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010949 << Object.get()->getType() << /*call*/ 1
10950 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010951 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010952 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010953 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010954 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10956 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010957 break;
10958
10959 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010960 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010961 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010962 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010963 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10964 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010965 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010966
10967 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010968 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010969 diag::err_ovl_deleted_object_call)
10970 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010971 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010972 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010973 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010974 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10975 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010976 break;
Mike Stump11289f42009-09-09 15:08:12 +000010977 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010978
Douglas Gregorb412e172010-07-25 18:17:45 +000010979 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010980 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010981
John McCall4124c492011-10-17 18:40:02 +000010982 UnbridgedCasts.restore();
10983
Douglas Gregorab7897a2008-11-19 22:57:39 +000010984 if (Best->Function == 0) {
10985 // Since there is no function declaration, this is one of the
10986 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010987 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010988 = cast<CXXConversionDecl>(
10989 Best->Conversions[0].UserDefined.ConversionFunction);
10990
John Wiegley01296292011-04-08 18:41:53 +000010991 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010992 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010993
Douglas Gregorab7897a2008-11-19 22:57:39 +000010994 // We selected one of the surrogate functions that converts the
10995 // object parameter to a function pointer. Perform the conversion
10996 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010997
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010998 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010999 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011000 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11001 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011002 if (Call.isInvalid())
11003 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011004 // Record usage of conversion in an implicit cast.
11005 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11006 CK_UserDefinedConversion,
11007 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011008
Douglas Gregor668443e2011-01-20 00:18:04 +000011009 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000011010 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011011 }
11012
Eli Friedmanfa0df832012-02-02 03:46:19 +000011013 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011014 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011015 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000011016
Douglas Gregorab7897a2008-11-19 22:57:39 +000011017 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11018 // that calls this method, using Object for the implicit object
11019 // parameter and passing along the remaining arguments.
11020 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011021
11022 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011023 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011024 return ExprError();
11025
Chandler Carruth8e543b32010-12-12 08:17:55 +000011026 const FunctionProtoType *Proto =
11027 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011028
11029 unsigned NumArgsInProto = Proto->getNumArgs();
11030 unsigned NumArgsToCheck = NumArgs;
11031
11032 // Build the full argument list for the method call (the
11033 // implicit object parameter is placed at the beginning of the
11034 // list).
11035 Expr **MethodArgs;
11036 if (NumArgs < NumArgsInProto) {
11037 NumArgsToCheck = NumArgsInProto;
11038 MethodArgs = new Expr*[NumArgsInProto + 1];
11039 } else {
11040 MethodArgs = new Expr*[NumArgs + 1];
11041 }
John Wiegley01296292011-04-08 18:41:53 +000011042 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011043 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11044 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000011045
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011046 DeclarationNameInfo OpLocInfo(
11047 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11048 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011049 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011050 HadMultipleCandidates,
11051 OpLocInfo.getLoc(),
11052 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011053 if (NewFn.isInvalid())
11054 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011055
11056 // Once we've built TheCall, all of the expressions are properly
11057 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011058 QualType ResultTy = Method->getResultType();
11059 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11060 ResultTy = ResultTy.getNonLValueExprType(Context);
11061
John McCallb268a282010-08-23 23:25:46 +000011062 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011063 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011064 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hames5de91cc2012-10-02 04:45:10 +000011065 ResultTy, VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011066 delete [] MethodArgs;
11067
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011068 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011069 Method))
11070 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011071
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011072 // We may have default arguments. If so, we need to allocate more
11073 // slots in the call for them.
11074 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011075 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011076 else if (NumArgs > NumArgsInProto)
11077 NumArgsToCheck = NumArgsInProto;
11078
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011079 bool IsError = false;
11080
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011081 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011082 ExprResult ObjRes =
11083 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11084 Best->FoundDecl, Method);
11085 if (ObjRes.isInvalid())
11086 IsError = true;
11087 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011088 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011089 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011090
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011091 // Check the argument types.
11092 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011093 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011094 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011095 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011096
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011097 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011098
John McCalldadc5752010-08-24 06:29:42 +000011099 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011100 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011101 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011102 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011103 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011104
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011105 IsError |= InputInit.isInvalid();
11106 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011107 } else {
John McCalldadc5752010-08-24 06:29:42 +000011108 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011109 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11110 if (DefArg.isInvalid()) {
11111 IsError = true;
11112 break;
11113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011114
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011115 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011116 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011117
11118 TheCall->setArg(i + 1, Arg);
11119 }
11120
11121 // If this is a variadic call, handle args passed through "...".
11122 if (Proto->isVariadic()) {
11123 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman9bca21e2012-07-20 20:40:35 +000011124 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011125 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11126 IsError |= Arg.isInvalid();
11127 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011128 }
11129 }
11130
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011131 if (IsError) return true;
11132
Eli Friedmanff4b4072012-02-18 04:48:30 +000011133 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11134
Richard Smith55ce3522012-06-25 20:30:08 +000011135 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011136 return true;
11137
John McCalle172be52010-08-24 06:09:16 +000011138 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011139}
11140
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011141/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011142/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011143/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011144ExprResult
John McCallb268a282010-08-23 23:25:46 +000011145Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011146 assert(Base->getType()->isRecordType() &&
11147 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011148
John McCall4124c492011-10-17 18:40:02 +000011149 if (checkPlaceholderForOverload(*this, Base))
11150 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011151
John McCallbc077cf2010-02-08 23:07:23 +000011152 SourceLocation Loc = Base->getExprLoc();
11153
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011154 // C++ [over.ref]p1:
11155 //
11156 // [...] An expression x->m is interpreted as (x.operator->())->m
11157 // for a class object x of type T if T::operator->() exists and if
11158 // the operator is selected as the best match function by the
11159 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011160 DeclarationName OpName =
11161 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011162 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011163 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011164
John McCallbc077cf2010-02-08 23:07:23 +000011165 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011166 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011167 return ExprError();
11168
John McCall27b18f82009-11-17 02:14:36 +000011169 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11170 LookupQualifiedName(R, BaseRecord->getDecl());
11171 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011172
11173 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011174 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011175 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11176 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011177 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011178
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011179 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11180
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011181 // Perform overload resolution.
11182 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011183 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011184 case OR_Success:
11185 // Overload resolution succeeded; we'll build the call below.
11186 break;
11187
11188 case OR_No_Viable_Function:
11189 if (CandidateSet.empty())
11190 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011191 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011192 else
11193 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011194 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011195 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011196 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011197
11198 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011199 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11200 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011201 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011202 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011203
11204 case OR_Deleted:
11205 Diag(OpLoc, diag::err_ovl_deleted_oper)
11206 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011207 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011208 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011209 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011210 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011211 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011212 }
11213
Eli Friedmanfa0df832012-02-02 03:46:19 +000011214 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011215 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011216 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011217
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011218 // Convert the object parameter.
11219 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011220 ExprResult BaseResult =
11221 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11222 Best->FoundDecl, Method);
11223 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011224 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011225 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011226
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011227 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011228 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011229 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011230 if (FnExpr.isInvalid())
11231 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011232
John McCall7decc9e2010-11-18 06:31:45 +000011233 QualType ResultTy = Method->getResultType();
11234 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11235 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011236 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011237 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011238 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011239
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011240 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011241 Method))
11242 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011243
11244 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011245}
11246
Richard Smithbcc22fc2012-03-09 08:00:36 +000011247/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11248/// a literal operator described by the provided lookup results.
11249ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11250 DeclarationNameInfo &SuffixInfo,
11251 ArrayRef<Expr*> Args,
11252 SourceLocation LitEndLoc,
11253 TemplateArgumentListInfo *TemplateArgs) {
11254 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011255
Richard Smithbcc22fc2012-03-09 08:00:36 +000011256 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11257 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11258 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011259
Richard Smithbcc22fc2012-03-09 08:00:36 +000011260 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11261
Richard Smithbcc22fc2012-03-09 08:00:36 +000011262 // Perform overload resolution. This will usually be trivial, but might need
11263 // to perform substitutions for a literal operator template.
11264 OverloadCandidateSet::iterator Best;
11265 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11266 case OR_Success:
11267 case OR_Deleted:
11268 break;
11269
11270 case OR_No_Viable_Function:
11271 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11272 << R.getLookupName();
11273 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11274 return ExprError();
11275
11276 case OR_Ambiguous:
11277 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11278 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11279 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011280 }
11281
Richard Smithbcc22fc2012-03-09 08:00:36 +000011282 FunctionDecl *FD = Best->Function;
11283 MarkFunctionReferenced(UDSuffixLoc, FD);
11284 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011285
Richard Smithbcc22fc2012-03-09 08:00:36 +000011286 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11287 SuffixInfo.getLoc(),
11288 SuffixInfo.getInfo());
11289 if (Fn.isInvalid())
11290 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011291
11292 // Check the argument types. This should almost always be a no-op, except
11293 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011294 Expr *ConvArgs[2];
11295 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11296 ExprResult InputInit = PerformCopyInitialization(
11297 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11298 SourceLocation(), Args[ArgIdx]);
11299 if (InputInit.isInvalid())
11300 return true;
11301 ConvArgs[ArgIdx] = InputInit.take();
11302 }
11303
Richard Smithc67fdd42012-03-07 08:35:16 +000011304 QualType ResultTy = FD->getResultType();
11305 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11306 ResultTy = ResultTy.getNonLValueExprType(Context);
11307
Richard Smithc67fdd42012-03-07 08:35:16 +000011308 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011309 new (Context) UserDefinedLiteral(Context, Fn.take(),
11310 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011311 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11312
11313 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11314 return ExprError();
11315
Richard Smith55ce3522012-06-25 20:30:08 +000011316 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011317 return ExprError();
11318
11319 return MaybeBindToTemporary(UDL);
11320}
11321
Sam Panzer0f384432012-08-21 00:52:01 +000011322/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11323/// given LookupResult is non-empty, it is assumed to describe a member which
11324/// will be invoked. Otherwise, the function will be found via argument
11325/// dependent lookup.
11326/// CallExpr is set to a valid expression and FRS_Success returned on success,
11327/// otherwise CallExpr is set to ExprError() and some non-success value
11328/// is returned.
11329Sema::ForRangeStatus
11330Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11331 SourceLocation RangeLoc, VarDecl *Decl,
11332 BeginEndFunction BEF,
11333 const DeclarationNameInfo &NameInfo,
11334 LookupResult &MemberLookup,
11335 OverloadCandidateSet *CandidateSet,
11336 Expr *Range, ExprResult *CallExpr) {
11337 CandidateSet->clear();
11338 if (!MemberLookup.empty()) {
11339 ExprResult MemberRef =
11340 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11341 /*IsPtr=*/false, CXXScopeSpec(),
11342 /*TemplateKWLoc=*/SourceLocation(),
11343 /*FirstQualifierInScope=*/0,
11344 MemberLookup,
11345 /*TemplateArgs=*/0);
11346 if (MemberRef.isInvalid()) {
11347 *CallExpr = ExprError();
11348 Diag(Range->getLocStart(), diag::note_in_for_range)
11349 << RangeLoc << BEF << Range->getType();
11350 return FRS_DiagnosticIssued;
11351 }
11352 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11353 if (CallExpr->isInvalid()) {
11354 *CallExpr = ExprError();
11355 Diag(Range->getLocStart(), diag::note_in_for_range)
11356 << RangeLoc << BEF << Range->getType();
11357 return FRS_DiagnosticIssued;
11358 }
11359 } else {
11360 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011361 UnresolvedLookupExpr *Fn =
11362 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11363 NestedNameSpecifierLoc(), NameInfo,
11364 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011365 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011366
11367 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11368 CandidateSet, CallExpr);
11369 if (CandidateSet->empty() || CandidateSetError) {
11370 *CallExpr = ExprError();
11371 return FRS_NoViableFunction;
11372 }
11373 OverloadCandidateSet::iterator Best;
11374 OverloadingResult OverloadResult =
11375 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11376
11377 if (OverloadResult == OR_No_Viable_Function) {
11378 *CallExpr = ExprError();
11379 return FRS_NoViableFunction;
11380 }
11381 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11382 Loc, 0, CandidateSet, &Best,
11383 OverloadResult,
11384 /*AllowTypoCorrection=*/false);
11385 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11386 *CallExpr = ExprError();
11387 Diag(Range->getLocStart(), diag::note_in_for_range)
11388 << RangeLoc << BEF << Range->getType();
11389 return FRS_DiagnosticIssued;
11390 }
11391 }
11392 return FRS_Success;
11393}
11394
11395
Douglas Gregorcd695e52008-11-10 20:40:00 +000011396/// FixOverloadedFunctionReference - E is an expression that refers to
11397/// a C++ overloaded function (possibly with some parentheses and
11398/// perhaps a '&' around it). We have resolved the overloaded function
11399/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011400/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011401Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011402 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011403 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011404 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11405 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011406 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011407 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011408
Douglas Gregor51c538b2009-11-20 19:42:02 +000011409 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011410 }
11411
Douglas Gregor51c538b2009-11-20 19:42:02 +000011412 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011413 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11414 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011415 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011416 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011417 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011418 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011419 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011420 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011421
11422 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011423 ICE->getCastKind(),
11424 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011425 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011426 }
11427
Douglas Gregor51c538b2009-11-20 19:42:02 +000011428 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011429 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011430 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11432 if (Method->isStatic()) {
11433 // Do nothing: static member functions aren't any different
11434 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011435 } else {
John McCalle66edc12009-11-24 19:00:30 +000011436 // Fix the sub expression, which really has to be an
11437 // UnresolvedLookupExpr holding an overloaded member function
11438 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011439 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11440 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011441 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011442 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011443
John McCalld14a8642009-11-21 08:51:07 +000011444 assert(isa<DeclRefExpr>(SubExpr)
11445 && "fixed to something other than a decl ref");
11446 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11447 && "fixed to a member ref with no nested name qualifier");
11448
11449 // We have taken the address of a pointer to member
11450 // function. Perform the computation here so that we get the
11451 // appropriate pointer to member type.
11452 QualType ClassType
11453 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11454 QualType MemPtrType
11455 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11456
John McCall7decc9e2010-11-18 06:31:45 +000011457 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11458 VK_RValue, OK_Ordinary,
11459 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011460 }
11461 }
John McCall16df1e52010-03-30 21:47:33 +000011462 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11463 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011464 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011465 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011466
John McCalle3027922010-08-25 11:45:40 +000011467 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011468 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011469 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011470 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011471 }
John McCalld14a8642009-11-21 08:51:07 +000011472
11473 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011474 // FIXME: avoid copy.
11475 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011476 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011477 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11478 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011479 }
11480
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011481 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11482 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011483 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011484 Fn,
John McCall113bee02012-03-10 09:33:50 +000011485 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011486 ULE->getNameLoc(),
11487 Fn->getType(),
11488 VK_LValue,
11489 Found.getDecl(),
11490 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011491 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011492 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11493 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011494 }
11495
John McCall10eae182009-11-30 22:42:35 +000011496 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011497 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011498 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11499 if (MemExpr->hasExplicitTemplateArgs()) {
11500 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11501 TemplateArgs = &TemplateArgsBuffer;
11502 }
John McCall6b51f282009-11-23 01:53:49 +000011503
John McCall2d74de92009-12-01 22:10:20 +000011504 Expr *Base;
11505
John McCall7decc9e2010-11-18 06:31:45 +000011506 // If we're filling in a static method where we used to have an
11507 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011508 if (MemExpr->isImplicitAccess()) {
11509 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011510 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11511 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011512 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011513 Fn,
John McCall113bee02012-03-10 09:33:50 +000011514 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011515 MemExpr->getMemberLoc(),
11516 Fn->getType(),
11517 VK_LValue,
11518 Found.getDecl(),
11519 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011520 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011521 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11522 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011523 } else {
11524 SourceLocation Loc = MemExpr->getMemberLoc();
11525 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011526 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011527 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011528 Base = new (Context) CXXThisExpr(Loc,
11529 MemExpr->getBaseType(),
11530 /*isImplicit=*/true);
11531 }
John McCall2d74de92009-12-01 22:10:20 +000011532 } else
John McCallc3007a22010-10-26 07:05:15 +000011533 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011534
John McCall4adb38c2011-04-27 00:36:17 +000011535 ExprValueKind valueKind;
11536 QualType type;
11537 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11538 valueKind = VK_LValue;
11539 type = Fn->getType();
11540 } else {
11541 valueKind = VK_RValue;
11542 type = Context.BoundMemberTy;
11543 }
11544
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011545 MemberExpr *ME = MemberExpr::Create(Context, Base,
11546 MemExpr->isArrow(),
11547 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011548 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011549 Fn,
11550 Found,
11551 MemExpr->getMemberNameInfo(),
11552 TemplateArgs,
11553 type, valueKind, OK_Ordinary);
11554 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000011555 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011556 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011558
John McCallc3007a22010-10-26 07:05:15 +000011559 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011560}
11561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011562ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011563 DeclAccessPair Found,
11564 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011565 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011566}
11567
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011568} // end namespace clang