blob: b99a638bdac762d5cf766b99b55437929fbddf66 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
John McCall7decc9e2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley01296292011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
52 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000053}
54
John McCall5c32be02010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000060
61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62 QualType &ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
65 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000066static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68 UserDefinedConversionSequence& User,
69 OverloadCandidateSet& Conversions,
70 bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75 const StandardConversionSequence& SCS1,
76 const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88
89
Douglas Gregor5251f1b2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000093GetConversionCategory(ImplicitConversionKind Kind) {
94 static const ImplicitConversionCategory
95 Category[(int)ICK_Num_Conversion_Kinds] = {
96 ICC_Identity,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Conversion
118 };
119 return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125 static const ImplicitConversionRank
126 Rank[(int)ICK_Num_Conversion_Kinds] = {
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190 First = ICK_Identity;
191 Second = ICK_Identity;
192 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203}
204
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209 ImplicitConversionRank Rank = ICR_Exact_Match;
210 if (GetConversionRank(First) > Rank)
211 Rank = GetConversionRank(First);
212 if (GetConversionRank(Second) > Rank)
213 Rank = GetConversionRank(Second);
214 if (GetConversionRank(Third) > Rank)
215 Rank = GetConversionRank(Third);
216 return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer or function-to-pointer implicit conversions, so
226 // check for their presence as well as checking whether FromType is
227 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000243bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith66e05fe2012-01-18 05:21:49 +0000262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266 switch (ICE->getCastKind()) {
267 case CK_NoOp:
268 case CK_IntegralCast:
269 case CK_IntegralToBoolean:
270 case CK_IntegralToFloating:
271 case CK_FloatingToIntegral:
272 case CK_FloatingToBoolean:
273 case CK_FloatingCast:
274 Converted = ICE->getSubExpr();
275 continue;
276
277 default:
278 return Converted;
279 }
280 }
281
282 return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx The AST context.
289/// \param Converted The result of applying this standard conversion sequence.
290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
291/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
293/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000300
301 // C++11 [dcl.init.list]p7:
302 // A narrowing conversion is an implicit conversion ...
303 QualType FromType = getToType(0);
304 QualType ToType = getToType(1);
305 switch (Second) {
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000365 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
392 (FromWidth == ToWidth && FromSigned != ToSigned)) {
393 // Not all values of FromType can be represented in ToType.
394 llvm::APSInt InitializerValue;
395 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
396 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
397 ConstantValue = APValue(InitializerValue);
398
399 // Add a bit to the InitializerValue so we don't have to worry about
400 // signed vs. unsigned comparisons.
401 InitializerValue = InitializerValue.extend(
402 InitializerValue.getBitWidth() + 1);
403 // Convert the initializer to and from the target width and signed-ness.
404 llvm::APSInt ConvertedValue = InitializerValue;
405 ConvertedValue = ConvertedValue.trunc(ToWidth);
406 ConvertedValue.setIsSigned(ToSigned);
407 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
408 ConvertedValue.setIsSigned(InitializerValue.isSigned());
409 // If the result is different, this was a narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000410 if (ConvertedValue != InitializerValue) {
411 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000412 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000413 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000414 } else {
415 // Variables are always narrowings.
416 return NK_Variable_Narrowing;
417 }
418 }
419 return NK_Not_Narrowing;
420 }
421
422 default:
423 // Other kinds of conversions are not narrowings.
424 return NK_Not_Narrowing;
425 }
426}
427
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000428/// DebugPrint - Print this standard conversion sequence to standard
429/// error. Useful for debugging overloading issues.
430void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000431 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000432 bool PrintedSomething = false;
433 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000434 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000435 PrintedSomething = true;
436 }
437
438 if (Second != ICK_Identity) {
439 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000442 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443
444 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000450 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (Third != ICK_Identity) {
455 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000459 PrintedSomething = true;
460 }
461
462 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 }
465}
466
467/// DebugPrint - Print this user-defined conversion sequence to standard
468/// error. Useful for debugging overloading issues.
469void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000470 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471 if (Before.First || Before.Second || Before.Third) {
472 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000475 if (ConversionFunction)
476 OS << '\'' << *ConversionFunction << '\'';
477 else
478 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481 After.DebugPrint();
482 }
483}
484
485/// DebugPrint - Print this implicit conversion sequence to standard
486/// error. Useful for debugging overloading issues.
487void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 Standard.DebugPrint();
493 break;
494 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 UserDefined.DebugPrint();
497 break;
498 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
John McCall0d1da222010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000503 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510}
511
John McCall0d1da222010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527namespace {
528 // Structure used by OverloadCandidate::DeductionFailureInfo to store
529 // template parameter and template argument information.
530 struct DFIParamWithArguments {
531 TemplateParameter Param;
532 TemplateArgument FirstArg;
533 TemplateArgument SecondArg;
534 };
535}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537/// \brief Convert from Sema's representation of template deduction information
538/// to the form used in overload-candidate information.
539OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000540static MakeDeductionFailureInfo(ASTContext &Context,
541 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000542 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000543 OverloadCandidate::DeductionFailureInfo Result;
544 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000545 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546 Result.Data = 0;
547 switch (TDK) {
548 case Sema::TDK_Success:
549 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000550 case Sema::TDK_TooManyArguments:
551 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000555 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000556 Result.Data = Info.Param.getOpaqueValue();
557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000560 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000561 // FIXME: Should allocate from normal heap so that we can free this later.
562 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 Saved->Param = Info.Param;
564 Saved->FirstArg = Info.FirstArg;
565 Saved->SecondArg = Info.SecondArg;
566 Result.Data = Saved;
567 break;
568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000570 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000571 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000572 if (Info.hasSFINAEDiagnostic()) {
573 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
574 SourceLocation(), PartialDiagnostic::NullDiagnostic());
575 Info.takeSFINAEDiagnostic(*Diag);
576 Result.HasDiagnostic = true;
577 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000578 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 return Result;
586}
John McCall0d1da222010-01-12 00:44:57 +0000587
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588void OverloadCandidate::DeductionFailureInfo::Destroy() {
589 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
590 case Sema::TDK_Success:
591 case Sema::TDK_InstantiationDepth:
592 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000593 case Sema::TDK_TooManyArguments:
594 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000595 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000598 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000599 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000600 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601 Data = 0;
602 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000603
604 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000605 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000606 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000607 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
608 Diag->~PartialDiagnosticAt();
609 HasDiagnostic = false;
610 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor461761d2010-05-08 18:20:53 +0000613 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000614 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 case Sema::TDK_FailedOverloadResolution:
616 break;
617 }
618}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Richard Smith9ca64612012-05-07 09:03:25 +0000620PartialDiagnosticAt *
621OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
622 if (HasDiagnostic)
623 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
624 return 0;
625}
626
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000634 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000637 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000638 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640
641 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000642 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 case Sema::TDK_FailedOverloadResolution:
648 break;
649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 return TemplateParameter();
652}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregord09efd42010-05-08 20:07:26 +0000654TemplateArgumentList *
655OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
656 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
657 case Sema::TDK_Success:
658 case Sema::TDK_InstantiationDepth:
659 case Sema::TDK_TooManyArguments:
660 case Sema::TDK_TooFewArguments:
661 case Sema::TDK_Incomplete:
662 case Sema::TDK_InvalidExplicitArguments:
663 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000665 return 0;
666
667 case Sema::TDK_SubstitutionFailure:
668 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregord09efd42010-05-08 20:07:26 +0000670 // Unhandled
671 case Sema::TDK_NonDeducedMismatch:
672 case Sema::TDK_FailedOverloadResolution:
673 break;
674 }
675
676 return 0;
677}
678
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000679const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681 case Sema::TDK_Success:
682 case Sema::TDK_InstantiationDepth:
683 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000684 case Sema::TDK_TooManyArguments:
685 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000686 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000687 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 return 0;
689
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000691 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693
Douglas Gregor461761d2010-05-08 18:20:53 +0000694 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 case Sema::TDK_FailedOverloadResolution:
697 break;
698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702
703const TemplateArgument *
704OverloadCandidate::DeductionFailureInfo::getSecondArg() {
705 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
706 case Sema::TDK_Success:
707 case Sema::TDK_InstantiationDepth:
708 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000709 case Sema::TDK_TooManyArguments:
710 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000711 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000712 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 return 0;
714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000716 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
718
Douglas Gregor461761d2010-05-08 18:20:53 +0000719 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 case Sema::TDK_FailedOverloadResolution:
722 break;
723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 return 0;
726}
727
728void OverloadCandidateSet::clear() {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000729 for (iterator i = begin(), e = end(); i != e; ++i)
730 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
731 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000732 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000733 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000734 Functions.clear();
735}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
John McCall4124c492011-10-17 18:40:02 +0000737namespace {
738 class UnbridgedCastsSet {
739 struct Entry {
740 Expr **Addr;
741 Expr *Saved;
742 };
743 SmallVector<Entry, 2> Entries;
744
745 public:
746 void save(Sema &S, Expr *&E) {
747 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
748 Entry entry = { &E, E };
749 Entries.push_back(entry);
750 E = S.stripARCUnbridgedCast(E);
751 }
752
753 void restore() {
754 for (SmallVectorImpl<Entry>::iterator
755 i = Entries.begin(), e = Entries.end(); i != e; ++i)
756 *i->Addr = i->Saved;
757 }
758 };
759}
760
761/// checkPlaceholderForOverload - Do any interesting placeholder-like
762/// preprocessing on the given expression.
763///
764/// \param unbridgedCasts a collection to which to add unbridged casts;
765/// without this, they will be immediately diagnosed as errors
766///
767/// Return true on unrecoverable error.
768static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
769 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000770 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
771 // We can't handle overloaded expressions here because overload
772 // resolution might reasonably tweak them.
773 if (placeholder->getKind() == BuiltinType::Overload) return false;
774
775 // If the context potentially accepts unbridged ARC casts, strip
776 // the unbridged cast and add it to the collection for later restoration.
777 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
778 unbridgedCasts) {
779 unbridgedCasts->save(S, E);
780 return false;
781 }
782
783 // Go ahead and check everything else.
784 ExprResult result = S.CheckPlaceholderExpr(E);
785 if (result.isInvalid())
786 return true;
787
788 E = result.take();
789 return false;
790 }
791
792 // Nothing to do.
793 return false;
794}
795
796/// checkArgPlaceholdersForOverload - Check a set of call operands for
797/// placeholders.
798static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
799 unsigned numArgs,
800 UnbridgedCastsSet &unbridged) {
801 for (unsigned i = 0; i != numArgs; ++i)
802 if (checkPlaceholderForOverload(S, args[i], &unbridged))
803 return true;
804
805 return false;
806}
807
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000809// overload of the declarations in Old. This routine returns false if
810// New and Old cannot be overloaded, e.g., if New has the same
811// signature as some function in Old (C++ 1.3.10) or if the Old
812// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000813// it does return false, MatchedDecl will point to the decl that New
814// cannot be overloaded with. This decl may be a UsingShadowDecl on
815// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816//
817// Example: Given the following input:
818//
819// void f(int, float); // #1
820// void f(int, int); // #2
821// int f(int, int); // #3
822//
823// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000824// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000825//
John McCall3d988d92009-12-02 08:47:38 +0000826// When we process #2, Old contains only the FunctionDecl for #1. By
827// comparing the parameter types, we see that #1 and #2 are overloaded
828// (since they have different signatures), so this routine returns
829// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830//
John McCall3d988d92009-12-02 08:47:38 +0000831// When we process #3, Old is an overload set containing #1 and #2. We
832// compare the signatures of #3 to #1 (they're overloaded, so we do
833// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
834// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000835// signature), IsOverload returns false and MatchedDecl will be set to
836// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000837//
838// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
839// into a class by a using declaration. The rules for whether to hide
840// shadow declarations ignore some properties which otherwise figure
841// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000842Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000843Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
844 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000845 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000846 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000847 NamedDecl *OldD = *I;
848
849 bool OldIsUsingDecl = false;
850 if (isa<UsingShadowDecl>(OldD)) {
851 OldIsUsingDecl = true;
852
853 // We can always introduce two using declarations into the same
854 // context, even if they have identical signatures.
855 if (NewIsUsingDecl) continue;
856
857 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
858 }
859
860 // If either declaration was introduced by a using declaration,
861 // we'll need to use slightly different rules for matching.
862 // Essentially, these rules are the normal rules, except that
863 // function templates hide function templates with different
864 // return types or template parameter lists.
865 bool UseMemberUsingDeclRules =
866 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
867
John McCall3d988d92009-12-02 08:47:38 +0000868 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000869 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
870 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
871 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
872 continue;
873 }
874
John McCalldaa3d6b2009-12-09 03:35:25 +0000875 Match = *I;
876 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877 }
John McCall3d988d92009-12-02 08:47:38 +0000878 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000879 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
880 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
881 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
882 continue;
883 }
884
John McCalldaa3d6b2009-12-09 03:35:25 +0000885 Match = *I;
886 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000887 }
John McCalla8987a2942010-11-10 03:01:53 +0000888 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000889 // We can overload with these, which can show up when doing
890 // redeclaration checks for UsingDecls.
891 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000892 } else if (isa<TagDecl>(OldD)) {
893 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000894 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
895 // Optimistically assume that an unresolved using decl will
896 // overload; if it doesn't, we'll have to diagnose during
897 // template instantiation.
898 } else {
John McCall1f82f242009-11-18 22:49:29 +0000899 // (C++ 13p1):
900 // Only function declarations can be overloaded; object and type
901 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000902 Match = *I;
903 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000904 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905 }
John McCall1f82f242009-11-18 22:49:29 +0000906
John McCalldaa3d6b2009-12-09 03:35:25 +0000907 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000908}
909
John McCalle9cccd82010-06-16 08:42:20 +0000910bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
911 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000912 // If both of the functions are extern "C", then they are not
913 // overloads.
914 if (Old->isExternC() && New->isExternC())
915 return false;
916
John McCall1f82f242009-11-18 22:49:29 +0000917 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
918 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
919
920 // C++ [temp.fct]p2:
921 // A function template can be overloaded with other function templates
922 // and with normal (non-template) functions.
923 if ((OldTemplate == 0) != (NewTemplate == 0))
924 return true;
925
926 // Is the function New an overload of the function Old?
927 QualType OldQType = Context.getCanonicalType(Old->getType());
928 QualType NewQType = Context.getCanonicalType(New->getType());
929
930 // Compare the signatures (C++ 1.3.10) of the two functions to
931 // determine whether they are overloads. If we find any mismatch
932 // in the signature, they are overloads.
933
934 // If either of these functions is a K&R-style function (no
935 // prototype), then we consider them to have matching signatures.
936 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
937 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
938 return false;
939
John McCall424cec92011-01-19 06:33:43 +0000940 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
941 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000942
943 // The signature of a function includes the types of its
944 // parameters (C++ 1.3.10), which includes the presence or absence
945 // of the ellipsis; see C++ DR 357).
946 if (OldQType != NewQType &&
947 (OldType->getNumArgs() != NewType->getNumArgs() ||
948 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000949 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000950 return true;
951
952 // C++ [temp.over.link]p4:
953 // The signature of a function template consists of its function
954 // signature, its return type and its template parameter list. The names
955 // of the template parameters are significant only for establishing the
956 // relationship between the template parameters and the rest of the
957 // signature.
958 //
959 // We check the return type and template parameter lists for function
960 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000961 //
962 // However, we don't consider either of these when deciding whether
963 // a member introduced by a shadow declaration is hidden.
964 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000965 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
966 OldTemplate->getTemplateParameters(),
967 false, TPL_TemplateMatch) ||
968 OldType->getResultType() != NewType->getResultType()))
969 return true;
970
971 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000972 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000973 //
974 // As part of this, also check whether one of the member functions
975 // is static, in which case they are not overloads (C++
976 // 13.1p2). While not part of the definition of the signature,
977 // this check is important to determine whether these functions
978 // can be overloaded.
979 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
980 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
981 if (OldMethod && NewMethod &&
982 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000983 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000984 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
985 if (!UseUsingDeclRules &&
986 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
987 (OldMethod->getRefQualifier() == RQ_None ||
988 NewMethod->getRefQualifier() == RQ_None)) {
989 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000990 // - Member function declarations with the same name and the same
991 // parameter-type-list as well as member function template
992 // declarations with the same name, the same parameter-type-list, and
993 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000994 // them, but not all, have a ref-qualifier (8.3.5).
995 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
996 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
997 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
John McCall1f82f242009-11-18 22:49:29 +00001000 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002
John McCall1f82f242009-11-18 22:49:29 +00001003 // The signatures match; this is not an overload.
1004 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005}
1006
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001007/// \brief Checks availability of the function depending on the current
1008/// function context. Inside an unavailable function, unavailability is ignored.
1009///
1010/// \returns true if \arg FD is unavailable and current context is inside
1011/// an available function, false otherwise.
1012bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1013 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1014}
1015
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001016/// \brief Tries a user-defined conversion from From to ToType.
1017///
1018/// Produces an implicit conversion sequence for when a standard conversion
1019/// is not an option. See TryImplicitConversion for more information.
1020static ImplicitConversionSequence
1021TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1022 bool SuppressUserConversions,
1023 bool AllowExplicit,
1024 bool InOverloadResolution,
1025 bool CStyle,
1026 bool AllowObjCWritebackConversion) {
1027 ImplicitConversionSequence ICS;
1028
1029 if (SuppressUserConversions) {
1030 // We're not in the case above, so there is no conversion that
1031 // we can perform.
1032 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1033 return ICS;
1034 }
1035
1036 // Attempt user-defined conversion.
1037 OverloadCandidateSet Conversions(From->getExprLoc());
1038 OverloadingResult UserDefResult
1039 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1040 AllowExplicit);
1041
1042 if (UserDefResult == OR_Success) {
1043 ICS.setUserDefined();
1044 // C++ [over.ics.user]p4:
1045 // A conversion of an expression of class type to the same class
1046 // type is given Exact Match rank, and a conversion of an
1047 // expression of class type to a base class of that type is
1048 // given Conversion rank, in spite of the fact that a copy
1049 // constructor (i.e., a user-defined conversion function) is
1050 // called for those cases.
1051 if (CXXConstructorDecl *Constructor
1052 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1053 QualType FromCanon
1054 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1055 QualType ToCanon
1056 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1057 if (Constructor->isCopyConstructor() &&
1058 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1059 // Turn this into a "standard" conversion sequence, so that it
1060 // gets ranked with standard conversion sequences.
1061 ICS.setStandard();
1062 ICS.Standard.setAsIdentityConversion();
1063 ICS.Standard.setFromType(From->getType());
1064 ICS.Standard.setAllToTypes(ToType);
1065 ICS.Standard.CopyConstructor = Constructor;
1066 if (ToCanon != FromCanon)
1067 ICS.Standard.Second = ICK_Derived_To_Base;
1068 }
1069 }
1070
1071 // C++ [over.best.ics]p4:
1072 // However, when considering the argument of a user-defined
1073 // conversion function that is a candidate by 13.3.1.3 when
1074 // invoked for the copying of the temporary in the second step
1075 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1076 // 13.3.1.6 in all cases, only standard conversion sequences and
1077 // ellipsis conversion sequences are allowed.
1078 if (SuppressUserConversions && ICS.isUserDefined()) {
1079 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1080 }
1081 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1082 ICS.setAmbiguous();
1083 ICS.Ambiguous.setFromType(From->getType());
1084 ICS.Ambiguous.setToType(ToType);
1085 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1086 Cand != Conversions.end(); ++Cand)
1087 if (Cand->Viable)
1088 ICS.Ambiguous.addConversion(Cand->Function);
1089 } else {
1090 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1091 }
1092
1093 return ICS;
1094}
1095
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001096/// TryImplicitConversion - Attempt to perform an implicit conversion
1097/// from the given expression (Expr) to the given type (ToType). This
1098/// function returns an implicit conversion sequence that can be used
1099/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100///
1101/// void f(float f);
1102/// void g(int i) { f(i); }
1103///
1104/// this routine would produce an implicit conversion sequence to
1105/// describe the initialization of f from i, which will be a standard
1106/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1107/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1108//
1109/// Note that this routine only determines how the conversion can be
1110/// performed; it does not actually perform the conversion. As such,
1111/// it will not produce any diagnostics if no conversion is available,
1112/// but will instead return an implicit conversion sequence of kind
1113/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001114///
1115/// If @p SuppressUserConversions, then user-defined conversions are
1116/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001117/// If @p AllowExplicit, then explicit user-defined conversions are
1118/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001119///
1120/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1121/// writeback conversion, which allows __autoreleasing id* parameters to
1122/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001123static ImplicitConversionSequence
1124TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1125 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001126 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001127 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001128 bool CStyle,
1129 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001131 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001132 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001133 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001134 return ICS;
1135 }
1136
David Blaikiebbafb8a2012-03-11 07:00:24 +00001137 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001138 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001139 return ICS;
1140 }
1141
Douglas Gregor836a7e82010-08-11 02:15:33 +00001142 // C++ [over.ics.user]p4:
1143 // A conversion of an expression of class type to the same class
1144 // type is given Exact Match rank, and a conversion of an
1145 // expression of class type to a base class of that type is
1146 // given Conversion rank, in spite of the fact that a copy/move
1147 // constructor (i.e., a user-defined conversion function) is
1148 // called for those cases.
1149 QualType FromType = From->getType();
1150 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001151 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1152 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001153 ICS.setStandard();
1154 ICS.Standard.setAsIdentityConversion();
1155 ICS.Standard.setFromType(FromType);
1156 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
Douglas Gregor5ab11652010-04-17 22:01:05 +00001158 // We don't actually check at this point whether there is a valid
1159 // copy/move constructor, since overloading just assumes that it
1160 // exists. When we actually perform initialization, we'll find the
1161 // appropriate constructor to copy the returned object, if needed.
1162 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163
Douglas Gregor5ab11652010-04-17 22:01:05 +00001164 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001165 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001166 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001167
Douglas Gregor836a7e82010-08-11 02:15:33 +00001168 return ICS;
1169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001171 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1172 AllowExplicit, InOverloadResolution, CStyle,
1173 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001174}
1175
John McCall31168b02011-06-15 23:02:42 +00001176ImplicitConversionSequence
1177Sema::TryImplicitConversion(Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
1179 bool AllowExplicit,
1180 bool InOverloadResolution,
1181 bool CStyle,
1182 bool AllowObjCWritebackConversion) {
1183 return clang::TryImplicitConversion(*this, From, ToType,
1184 SuppressUserConversions, AllowExplicit,
1185 InOverloadResolution, CStyle,
1186 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001187}
1188
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001189/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001190/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001191/// converted expression. Flavor is the kind of conversion we're
1192/// performing, used in the error message. If @p AllowExplicit,
1193/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001194ExprResult
1195Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001196 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001197 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001198 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001199}
1200
John Wiegley01296292011-04-08 18:41:53 +00001201ExprResult
1202Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001203 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001204 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001205 if (checkPlaceholderForOverload(*this, From))
1206 return ExprError();
1207
John McCall31168b02011-06-15 23:02:42 +00001208 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1209 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001210 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001211 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001212
John McCall5c32be02010-08-24 20:38:10 +00001213 ICS = clang::TryImplicitConversion(*this, From, ToType,
1214 /*SuppressUserConversions=*/false,
1215 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001216 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001217 /*CStyle=*/false,
1218 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001219 return PerformImplicitConversion(From, ToType, ICS, Action);
1220}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
1222/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001223/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001224bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1225 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001226 if (Context.hasSameUnqualifiedType(FromType, ToType))
1227 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228
John McCall991eb4b2010-12-21 00:44:39 +00001229 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1230 // where F adds one of the following at most once:
1231 // - a pointer
1232 // - a member pointer
1233 // - a block pointer
1234 CanQualType CanTo = Context.getCanonicalType(ToType);
1235 CanQualType CanFrom = Context.getCanonicalType(FromType);
1236 Type::TypeClass TyClass = CanTo->getTypeClass();
1237 if (TyClass != CanFrom->getTypeClass()) return false;
1238 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1239 if (TyClass == Type::Pointer) {
1240 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1241 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1242 } else if (TyClass == Type::BlockPointer) {
1243 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1244 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1245 } else if (TyClass == Type::MemberPointer) {
1246 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1247 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1248 } else {
1249 return false;
1250 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001251
John McCall991eb4b2010-12-21 00:44:39 +00001252 TyClass = CanTo->getTypeClass();
1253 if (TyClass != CanFrom->getTypeClass()) return false;
1254 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1255 return false;
1256 }
1257
1258 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1259 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1260 if (!EInfo.getNoReturn()) return false;
1261
1262 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1263 assert(QualType(FromFn, 0).isCanonical());
1264 if (QualType(FromFn, 0) != CanTo) return false;
1265
1266 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001267 return true;
1268}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269
Douglas Gregor46188682010-05-18 22:42:18 +00001270/// \brief Determine whether the conversion from FromType to ToType is a valid
1271/// vector conversion.
1272///
1273/// \param ICK Will be set to the vector conversion kind, if this is a vector
1274/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1276 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001277 // We need at least one of these types to be a vector type to have a vector
1278 // conversion.
1279 if (!ToType->isVectorType() && !FromType->isVectorType())
1280 return false;
1281
1282 // Identical types require no conversions.
1283 if (Context.hasSameUnqualifiedType(FromType, ToType))
1284 return false;
1285
1286 // There are no conversions between extended vector types, only identity.
1287 if (ToType->isExtVectorType()) {
1288 // There are no conversions between extended vector types other than the
1289 // identity conversion.
1290 if (FromType->isExtVectorType())
1291 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
Douglas Gregor46188682010-05-18 22:42:18 +00001293 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001294 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001295 ICK = ICK_Vector_Splat;
1296 return true;
1297 }
1298 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001299
1300 // We can perform the conversion between vector types in the following cases:
1301 // 1)vector types are equivalent AltiVec and GCC vector types
1302 // 2)lax vector conversions are permitted and the vector types are of the
1303 // same size
1304 if (ToType->isVectorType() && FromType->isVectorType()) {
1305 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001306 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001307 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001308 ICK = ICK_Vector_Conversion;
1309 return true;
1310 }
Douglas Gregor46188682010-05-18 22:42:18 +00001311 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001312
Douglas Gregor46188682010-05-18 22:42:18 +00001313 return false;
1314}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001316static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1317 bool InOverloadResolution,
1318 StandardConversionSequence &SCS,
1319 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001320
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001321/// IsStandardConversion - Determines whether there is a standard
1322/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1323/// expression From to the type ToType. Standard conversion sequences
1324/// only consider non-class types; for conversions that involve class
1325/// types, use TryImplicitConversion. If a conversion exists, SCS will
1326/// contain the standard conversion sequence required to perform this
1327/// conversion and this routine will return true. Otherwise, this
1328/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001329static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1330 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001331 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001332 bool CStyle,
1333 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001334 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001336 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001337 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001338 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001339 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001340 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001341 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001342
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001343 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001344 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001345 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001346 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001347 return false;
1348
Mike Stump11289f42009-09-09 15:08:12 +00001349 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001350 }
1351
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 // The first conversion can be an lvalue-to-rvalue conversion,
1353 // array-to-pointer conversion, or function-to-pointer conversion
1354 // (C++ 4p1).
1355
John McCall5c32be02010-08-24 20:38:10 +00001356 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001357 DeclAccessPair AccessPair;
1358 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001360 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001361 // We were able to resolve the address of the overloaded function,
1362 // so we can convert to the type of that function.
1363 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001364
1365 // we can sometimes resolve &foo<int> regardless of ToType, so check
1366 // if the type matches (identity) or we are converting to bool
1367 if (!S.Context.hasSameUnqualifiedType(
1368 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1369 QualType resultTy;
1370 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001371 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001372 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1373 // otherwise, only a boolean conversion is standard
1374 if (!ToType->isBooleanType())
1375 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Chandler Carruthffce2452011-03-29 08:08:18 +00001378 // Check if the "from" expression is taking the address of an overloaded
1379 // function and recompute the FromType accordingly. Take advantage of the
1380 // fact that non-static member functions *must* have such an address-of
1381 // expression.
1382 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1383 if (Method && !Method->isStatic()) {
1384 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1385 "Non-unary operator on non-static member address");
1386 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1387 == UO_AddrOf &&
1388 "Non-address-of operator on non-static member address");
1389 const Type *ClassType
1390 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1391 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001392 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1393 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1394 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001395 "Non-address-of operator for overloaded function expression");
1396 FromType = S.Context.getPointerType(FromType);
1397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398
Douglas Gregor980fb162010-04-29 18:24:40 +00001399 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001400 assert(S.Context.hasSameType(
1401 FromType,
1402 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001403 } else {
1404 return false;
1405 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001406 }
John McCall154a2fd2011-08-30 00:57:29 +00001407 // Lvalue-to-rvalue conversion (C++11 4.1):
1408 // A glvalue (3.10) of a non-function, non-array type T can
1409 // be converted to a prvalue.
1410 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001411 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001412 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001413 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001414 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415
Douglas Gregorc79862f2012-04-12 17:51:55 +00001416 // C11 6.3.2.1p2:
1417 // ... if the lvalue has atomic type, the value has the non-atomic version
1418 // of the type of the lvalue ...
1419 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1420 FromType = Atomic->getValueType();
1421
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001422 // If T is a non-class type, the type of the rvalue is the
1423 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001424 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1425 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001426 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001427 } else if (FromType->isArrayType()) {
1428 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001429 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001430
1431 // An lvalue or rvalue of type "array of N T" or "array of unknown
1432 // bound of T" can be converted to an rvalue of type "pointer to
1433 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001434 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435
John McCall5c32be02010-08-24 20:38:10 +00001436 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001437 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001438 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001439
1440 // For the purpose of ranking in overload resolution
1441 // (13.3.3.1.1), this conversion is considered an
1442 // array-to-pointer conversion followed by a qualification
1443 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 SCS.Second = ICK_Identity;
1445 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001446 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001447 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001448 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449 }
John McCall086a4642010-11-24 05:12:34 +00001450 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001451 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453
1454 // An lvalue of function type T can be converted to an rvalue of
1455 // type "pointer to T." The result is a pointer to the
1456 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001457 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001458 } else {
1459 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001460 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001462 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001463
1464 // The second conversion can be an integral promotion, floating
1465 // point promotion, integral conversion, floating point conversion,
1466 // floating-integral conversion, pointer conversion,
1467 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001468 // For overloading in C, this can also be a "compatible-type"
1469 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001470 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001471 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001472 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 // The unqualified versions of the types are the same: there's no
1474 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001475 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001476 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001477 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001478 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001480 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001481 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001484 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001485 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001486 SCS.Second = ICK_Complex_Promotion;
1487 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001488 } else if (ToType->isBooleanType() &&
1489 (FromType->isArithmeticType() ||
1490 FromType->isAnyPointerType() ||
1491 FromType->isBlockPointerType() ||
1492 FromType->isMemberPointerType() ||
1493 FromType->isNullPtrType())) {
1494 // Boolean conversions (C++ 4.12).
1495 SCS.Second = ICK_Boolean_Conversion;
1496 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001497 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001498 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001499 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001502 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001503 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001504 SCS.Second = ICK_Complex_Conversion;
1505 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001506 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1507 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001508 // Complex-real conversions (C99 6.3.1.7)
1509 SCS.Second = ICK_Complex_Real;
1510 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001511 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001512 // Floating point conversions (C++ 4.8).
1513 SCS.Second = ICK_Floating_Conversion;
1514 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001516 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001517 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001518 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001519 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001522 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001523 SCS.Second = ICK_Block_Pointer_Conversion;
1524 } else if (AllowObjCWritebackConversion &&
1525 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1526 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001527 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1528 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001529 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001531 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001532 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001534 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001535 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001536 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001537 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001538 SCS.Second = SecondICK;
1539 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001540 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001541 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001542 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001543 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001544 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001545 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001546 // Treat a conversion that strips "noreturn" as an identity conversion.
1547 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001548 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1549 InOverloadResolution,
1550 SCS, CStyle)) {
1551 SCS.Second = ICK_TransparentUnionConversion;
1552 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001553 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1554 CStyle)) {
1555 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001556 // appropriately.
1557 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 } else {
1559 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001562 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001563
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001564 QualType CanonFrom;
1565 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001567 bool ObjCLifetimeConversion;
1568 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1569 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001571 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001573 CanonFrom = S.Context.getCanonicalType(FromType);
1574 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001575 } else {
1576 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001577 SCS.Third = ICK_Identity;
1578
Mike Stump11289f42009-09-09 15:08:12 +00001579 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580 // [...] Any difference in top-level cv-qualification is
1581 // subsumed by the initialization itself and does not constitute
1582 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001583 CanonFrom = S.Context.getCanonicalType(FromType);
1584 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001586 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001587 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001588 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1589 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001590 FromType = ToType;
1591 CanonFrom = CanonTo;
1592 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001594 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595
1596 // If we have not converted the argument type to the parameter type,
1597 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001598 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001599 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001601 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001603
1604static bool
1605IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1606 QualType &ToType,
1607 bool InOverloadResolution,
1608 StandardConversionSequence &SCS,
1609 bool CStyle) {
1610
1611 const RecordType *UT = ToType->getAsUnionType();
1612 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1613 return false;
1614 // The field to initialize within the transparent union.
1615 RecordDecl *UD = UT->getDecl();
1616 // It's compatible if the expression matches any of the fields.
1617 for (RecordDecl::field_iterator it = UD->field_begin(),
1618 itend = UD->field_end();
1619 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001620 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1621 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001622 ToType = it->getType();
1623 return true;
1624 }
1625 }
1626 return false;
1627}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628
1629/// IsIntegralPromotion - Determines whether the conversion from the
1630/// expression From (whose potentially-adjusted type is FromType) to
1631/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1632/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001633bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001634 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001635 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001636 if (!To) {
1637 return false;
1638 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
1640 // An rvalue of type char, signed char, unsigned char, short int, or
1641 // unsigned short int can be converted to an rvalue of type int if
1642 // int can represent all the values of the source type; otherwise,
1643 // the source rvalue can be converted to an rvalue of type unsigned
1644 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001645 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1646 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 if (// We can promote any signed, promotable integer type to an int
1648 (FromType->isSignedIntegerType() ||
1649 // We can promote any unsigned integer type whose size is
1650 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001651 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001652 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001654 }
1655
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656 return To->getKind() == BuiltinType::UInt;
1657 }
1658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001659 // C++0x [conv.prom]p3:
1660 // A prvalue of an unscoped enumeration type whose underlying type is not
1661 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1662 // following types that can represent all the values of the enumeration
1663 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1664 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001665 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001667 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668 // with lowest integer conversion rank (4.13) greater than the rank of long
1669 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001670 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001671 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1672 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1673 // provided for a scoped enumeration.
1674 if (FromEnumType->getDecl()->isScoped())
1675 return false;
1676
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001677 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001679 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001680 return Context.hasSameUnqualifiedType(ToType,
1681 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001682 }
John McCall56774992009-12-09 09:09:27 +00001683
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001684 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1686 // to an rvalue a prvalue of the first of the following types that can
1687 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001688 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001690 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001692 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001694 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695 // Determine whether the type we're converting from is signed or
1696 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001697 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 // The types we'll try to promote to, in the appropriate
1701 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001702 QualType PromoteTypes[6] = {
1703 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001704 Context.LongTy, Context.UnsignedLongTy ,
1705 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001707 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1709 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001710 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1712 // We found the type that we can promote to. If this is the
1713 // type we wanted, we have a promotion. Otherwise, no
1714 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001715 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716 }
1717 }
1718 }
1719
1720 // An rvalue for an integral bit-field (9.6) can be converted to an
1721 // rvalue of type int if int can represent all the values of the
1722 // bit-field; otherwise, it can be converted to unsigned int if
1723 // unsigned int can represent all the values of the bit-field. If
1724 // the bit-field is larger yet, no integral promotion applies to
1725 // it. If the bit-field has an enumerated type, it is treated as any
1726 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001727 // FIXME: We should delay checking of bit-fields until we actually perform the
1728 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001729 using llvm::APSInt;
1730 if (From)
1731 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001732 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001733 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001734 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1735 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1736 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001737
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001738 // Are we promoting to an int from a bitfield that fits in an int?
1739 if (BitWidth < ToSize ||
1740 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1741 return To->getKind() == BuiltinType::Int;
1742 }
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001744 // Are we promoting to an unsigned int from an unsigned bitfield
1745 // that fits into an unsigned int?
1746 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1747 return To->getKind() == BuiltinType::UInt;
1748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001750 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001751 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001752 }
Mike Stump11289f42009-09-09 15:08:12 +00001753
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001754 // An rvalue of type bool can be converted to an rvalue of type int,
1755 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001756 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001758 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001759
1760 return false;
1761}
1762
1763/// IsFloatingPointPromotion - Determines whether the conversion from
1764/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1765/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001766bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001767 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1768 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001769 /// An rvalue of type float can be converted to an rvalue of type
1770 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 if (FromBuiltin->getKind() == BuiltinType::Float &&
1772 ToBuiltin->getKind() == BuiltinType::Double)
1773 return true;
1774
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001775 // C99 6.3.1.5p1:
1776 // When a float is promoted to double or long double, or a
1777 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001778 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001779 (FromBuiltin->getKind() == BuiltinType::Float ||
1780 FromBuiltin->getKind() == BuiltinType::Double) &&
1781 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1782 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001783
1784 // Half can be promoted to float.
1785 if (FromBuiltin->getKind() == BuiltinType::Half &&
1786 ToBuiltin->getKind() == BuiltinType::Float)
1787 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001788 }
1789
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001790 return false;
1791}
1792
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001793/// \brief Determine if a conversion is a complex promotion.
1794///
1795/// A complex promotion is defined as a complex -> complex conversion
1796/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001797/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001798bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001799 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001800 if (!FromComplex)
1801 return false;
1802
John McCall9dd450b2009-09-21 23:43:11 +00001803 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001804 if (!ToComplex)
1805 return false;
1806
1807 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001808 ToComplex->getElementType()) ||
1809 IsIntegralPromotion(0, FromComplex->getElementType(),
1810 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001811}
1812
Douglas Gregor237f96c2008-11-26 23:31:11 +00001813/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1814/// the pointer type FromPtr to a pointer to type ToPointee, with the
1815/// same type qualifiers as FromPtr has on its pointee type. ToType,
1816/// if non-empty, will be a pointer to ToType that may or may not have
1817/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001818///
Mike Stump11289f42009-09-09 15:08:12 +00001819static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001820BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001821 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001822 ASTContext &Context,
1823 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001824 assert((FromPtr->getTypeClass() == Type::Pointer ||
1825 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1826 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001827
John McCall31168b02011-06-15 23:02:42 +00001828 /// Conversions to 'id' subsume cv-qualifier conversions.
1829 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001830 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831
1832 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001833 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001834 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001835 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001836
John McCall31168b02011-06-15 23:02:42 +00001837 if (StripObjCLifetime)
1838 Quals.removeObjCLifetime();
1839
Mike Stump11289f42009-09-09 15:08:12 +00001840 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001841 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001842 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001843 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001844 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001845
1846 // Build a pointer to ToPointee. It has the right qualifiers
1847 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001848 if (isa<ObjCObjectPointerType>(ToType))
1849 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001850 return Context.getPointerType(ToPointee);
1851 }
1852
1853 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001854 QualType QualifiedCanonToPointee
1855 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001857 if (isa<ObjCObjectPointerType>(ToType))
1858 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1859 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001860}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Mike Stump11289f42009-09-09 15:08:12 +00001862static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001863 bool InOverloadResolution,
1864 ASTContext &Context) {
1865 // Handle value-dependent integral null pointer constants correctly.
1866 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1867 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001868 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001869 return !InOverloadResolution;
1870
Douglas Gregor56751b52009-09-25 04:25:58 +00001871 return Expr->isNullPointerConstant(Context,
1872 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1873 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001874}
Mike Stump11289f42009-09-09 15:08:12 +00001875
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876/// IsPointerConversion - Determines whether the conversion of the
1877/// expression From, which has the (possibly adjusted) type FromType,
1878/// can be converted to the type ToType via a pointer conversion (C++
1879/// 4.10). If so, returns true and places the converted type (that
1880/// might differ from ToType in its cv-qualifiers at some level) into
1881/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001882///
Douglas Gregora29dc052008-11-27 01:19:21 +00001883/// This routine also supports conversions to and from block pointers
1884/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1885/// pointers to interfaces. FIXME: Once we've determined the
1886/// appropriate overloading rules for Objective-C, we may want to
1887/// split the Objective-C checks into a different routine; however,
1888/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001889/// conversions, so for now they live here. IncompatibleObjC will be
1890/// set if the conversion is an allowed Objective-C conversion that
1891/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001892bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001893 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001894 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001895 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001896 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001897 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1898 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001899 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001900
Mike Stump11289f42009-09-09 15:08:12 +00001901 // Conversion from a null pointer constant to any Objective-C pointer type.
1902 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001903 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001904 ConvertedType = ToType;
1905 return true;
1906 }
1907
Douglas Gregor231d1c62008-11-27 00:15:41 +00001908 // Blocks: Block pointers can be converted to void*.
1909 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001910 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001911 ConvertedType = ToType;
1912 return true;
1913 }
1914 // Blocks: A null pointer constant can be converted to a block
1915 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001916 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001917 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001918 ConvertedType = ToType;
1919 return true;
1920 }
1921
Sebastian Redl576fd422009-05-10 18:38:11 +00001922 // If the left-hand-side is nullptr_t, the right side can be a null
1923 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001924 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001925 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001926 ConvertedType = ToType;
1927 return true;
1928 }
1929
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001930 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931 if (!ToTypePtr)
1932 return false;
1933
1934 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001935 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936 ConvertedType = ToType;
1937 return true;
1938 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001941 // , including objective-c pointers.
1942 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001943 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001944 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945 ConvertedType = BuildSimilarlyQualifiedPointerType(
1946 FromType->getAs<ObjCObjectPointerType>(),
1947 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001948 ToType, Context);
1949 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001950 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001951 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001952 if (!FromTypePtr)
1953 return false;
1954
1955 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001956
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001958 // pointer conversion, so don't do all of the work below.
1959 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1960 return false;
1961
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001962 // An rvalue of type "pointer to cv T," where T is an object type,
1963 // can be converted to an rvalue of type "pointer to cv void" (C++
1964 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001965 if (FromPointeeType->isIncompleteOrObjectType() &&
1966 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001968 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001969 ToType, Context,
1970 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001971 return true;
1972 }
1973
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001974 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001975 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001976 ToPointeeType->isVoidType()) {
1977 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1978 ToPointeeType,
1979 ToType, Context);
1980 return true;
1981 }
1982
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001983 // When we're overloading in C, we allow a special kind of pointer
1984 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001985 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001986 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001988 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001989 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001990 return true;
1991 }
1992
Douglas Gregor5c407d92008-10-23 00:40:37 +00001993 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001994 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001995 // An rvalue of type "pointer to cv D," where D is a class type,
1996 // can be converted to an rvalue of type "pointer to cv B," where
1997 // B is a base class (clause 10) of D. If B is an inaccessible
1998 // (clause 11) or ambiguous (10.2) base class of D, a program that
1999 // necessitates this conversion is ill-formed. The result of the
2000 // conversion is a pointer to the base class sub-object of the
2001 // derived class object. The null pointer value is converted to
2002 // the null pointer value of the destination type.
2003 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002004 // Note that we do not check for ambiguity or inaccessibility
2005 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002006 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002007 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002008 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002009 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002010 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002011 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002012 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002013 ToType, Context);
2014 return true;
2015 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002016
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002017 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2018 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2020 ToPointeeType,
2021 ToType, Context);
2022 return true;
2023 }
2024
Douglas Gregora119f102008-12-19 19:13:09 +00002025 return false;
2026}
Douglas Gregoraec25842011-04-26 23:16:46 +00002027
2028/// \brief Adopt the given qualifiers for the given type.
2029static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2030 Qualifiers TQs = T.getQualifiers();
2031
2032 // Check whether qualifiers already match.
2033 if (TQs == Qs)
2034 return T;
2035
2036 if (Qs.compatiblyIncludes(TQs))
2037 return Context.getQualifiedType(T, Qs);
2038
2039 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2040}
Douglas Gregora119f102008-12-19 19:13:09 +00002041
2042/// isObjCPointerConversion - Determines whether this is an
2043/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2044/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002045bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002046 QualType& ConvertedType,
2047 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002049 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050
Douglas Gregoraec25842011-04-26 23:16:46 +00002051 // The set of qualifiers on the type we're converting from.
2052 Qualifiers FromQualifiers = FromType.getQualifiers();
2053
Steve Naroff7cae42b2009-07-10 23:34:53 +00002054 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002055 const ObjCObjectPointerType* ToObjCPtr =
2056 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002057 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002058 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002059
Steve Naroff7cae42b2009-07-10 23:34:53 +00002060 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002061 // If the pointee types are the same (ignoring qualifications),
2062 // then this is not a pointer conversion.
2063 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2064 FromObjCPtr->getPointeeType()))
2065 return false;
2066
Douglas Gregoraec25842011-04-26 23:16:46 +00002067 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002068 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002069 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002070 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002071 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002072 return true;
2073 }
2074 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002075 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002076 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002077 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002078 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002079 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002080 return true;
2081 }
2082 // Objective C++: We're able to convert from a pointer to an
2083 // interface to a pointer to a different interface.
2084 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002085 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2086 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002087 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002088 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2089 FromObjCPtr->getPointeeType()))
2090 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002092 ToObjCPtr->getPointeeType(),
2093 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002094 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002095 return true;
2096 }
2097
2098 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2099 // Okay: this is some kind of implicit downcast of Objective-C
2100 // interfaces, which is permitted. However, we're going to
2101 // complain about it.
2102 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002104 ToObjCPtr->getPointeeType(),
2105 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002107 return true;
2108 }
Mike Stump11289f42009-09-09 15:08:12 +00002109 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002110 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002111 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002112 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002113 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002115 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002116 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002117 // to a block pointer type.
2118 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002119 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002120 return true;
2121 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002122 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002125 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002126 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002127 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002128 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002129 return true;
2130 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002131 else
Douglas Gregora119f102008-12-19 19:13:09 +00002132 return false;
2133
Douglas Gregor033f56d2008-12-23 00:53:59 +00002134 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002135 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002136 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002137 else if (const BlockPointerType *FromBlockPtr =
2138 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002139 FromPointeeType = FromBlockPtr->getPointeeType();
2140 else
Douglas Gregora119f102008-12-19 19:13:09 +00002141 return false;
2142
Douglas Gregora119f102008-12-19 19:13:09 +00002143 // If we have pointers to pointers, recursively check whether this
2144 // is an Objective-C conversion.
2145 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2146 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2147 IncompatibleObjC)) {
2148 // We always complain about this conversion.
2149 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002150 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002152 return true;
2153 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002154 // Allow conversion of pointee being objective-c pointer to another one;
2155 // as in I* to id.
2156 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2157 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2159 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002160
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002161 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002162 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002163 return true;
2164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Douglas Gregor033f56d2008-12-23 00:53:59 +00002166 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002167 // differences in the argument and result types are in Objective-C
2168 // pointer conversions. If so, we permit the conversion (but
2169 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002170 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002171 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002172 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002173 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002174 if (FromFunctionType && ToFunctionType) {
2175 // If the function types are exactly the same, this isn't an
2176 // Objective-C pointer conversion.
2177 if (Context.getCanonicalType(FromPointeeType)
2178 == Context.getCanonicalType(ToPointeeType))
2179 return false;
2180
2181 // Perform the quick checks that will tell us whether these
2182 // function types are obviously different.
2183 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2184 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2185 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2186 return false;
2187
2188 bool HasObjCConversion = false;
2189 if (Context.getCanonicalType(FromFunctionType->getResultType())
2190 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2191 // Okay, the types match exactly. Nothing to do.
2192 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2193 ToFunctionType->getResultType(),
2194 ConvertedType, IncompatibleObjC)) {
2195 // Okay, we have an Objective-C pointer conversion.
2196 HasObjCConversion = true;
2197 } else {
2198 // Function types are too different. Abort.
2199 return false;
2200 }
Mike Stump11289f42009-09-09 15:08:12 +00002201
Douglas Gregora119f102008-12-19 19:13:09 +00002202 // Check argument types.
2203 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2204 ArgIdx != NumArgs; ++ArgIdx) {
2205 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2206 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2207 if (Context.getCanonicalType(FromArgType)
2208 == Context.getCanonicalType(ToArgType)) {
2209 // Okay, the types match exactly. Nothing to do.
2210 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2211 ConvertedType, IncompatibleObjC)) {
2212 // Okay, we have an Objective-C pointer conversion.
2213 HasObjCConversion = true;
2214 } else {
2215 // Argument types are too different. Abort.
2216 return false;
2217 }
2218 }
2219
2220 if (HasObjCConversion) {
2221 // We had an Objective-C conversion. Allow this pointer
2222 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002224 IncompatibleObjC = true;
2225 return true;
2226 }
2227 }
2228
Sebastian Redl72b597d2009-01-25 19:43:20 +00002229 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002230}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002231
John McCall31168b02011-06-15 23:02:42 +00002232/// \brief Determine whether this is an Objective-C writeback conversion,
2233/// used for parameter passing when performing automatic reference counting.
2234///
2235/// \param FromType The type we're converting form.
2236///
2237/// \param ToType The type we're converting to.
2238///
2239/// \param ConvertedType The type that will be produced after applying
2240/// this conversion.
2241bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2242 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002243 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002244 Context.hasSameUnqualifiedType(FromType, ToType))
2245 return false;
2246
2247 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2248 QualType ToPointee;
2249 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2250 ToPointee = ToPointer->getPointeeType();
2251 else
2252 return false;
2253
2254 Qualifiers ToQuals = ToPointee.getQualifiers();
2255 if (!ToPointee->isObjCLifetimeType() ||
2256 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002257 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002258 return false;
2259
2260 // Argument must be a pointer to __strong to __weak.
2261 QualType FromPointee;
2262 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2263 FromPointee = FromPointer->getPointeeType();
2264 else
2265 return false;
2266
2267 Qualifiers FromQuals = FromPointee.getQualifiers();
2268 if (!FromPointee->isObjCLifetimeType() ||
2269 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2270 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2271 return false;
2272
2273 // Make sure that we have compatible qualifiers.
2274 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2275 if (!ToQuals.compatiblyIncludes(FromQuals))
2276 return false;
2277
2278 // Remove qualifiers from the pointee type we're converting from; they
2279 // aren't used in the compatibility check belong, and we'll be adding back
2280 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2281 FromPointee = FromPointee.getUnqualifiedType();
2282
2283 // The unqualified form of the pointee types must be compatible.
2284 ToPointee = ToPointee.getUnqualifiedType();
2285 bool IncompatibleObjC;
2286 if (Context.typesAreCompatible(FromPointee, ToPointee))
2287 FromPointee = ToPointee;
2288 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2289 IncompatibleObjC))
2290 return false;
2291
2292 /// \brief Construct the type we're converting to, which is a pointer to
2293 /// __autoreleasing pointee.
2294 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2295 ConvertedType = Context.getPointerType(FromPointee);
2296 return true;
2297}
2298
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002299bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2300 QualType& ConvertedType) {
2301 QualType ToPointeeType;
2302 if (const BlockPointerType *ToBlockPtr =
2303 ToType->getAs<BlockPointerType>())
2304 ToPointeeType = ToBlockPtr->getPointeeType();
2305 else
2306 return false;
2307
2308 QualType FromPointeeType;
2309 if (const BlockPointerType *FromBlockPtr =
2310 FromType->getAs<BlockPointerType>())
2311 FromPointeeType = FromBlockPtr->getPointeeType();
2312 else
2313 return false;
2314 // We have pointer to blocks, check whether the only
2315 // differences in the argument and result types are in Objective-C
2316 // pointer conversions. If so, we permit the conversion.
2317
2318 const FunctionProtoType *FromFunctionType
2319 = FromPointeeType->getAs<FunctionProtoType>();
2320 const FunctionProtoType *ToFunctionType
2321 = ToPointeeType->getAs<FunctionProtoType>();
2322
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002323 if (!FromFunctionType || !ToFunctionType)
2324 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002325
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002326 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002327 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002328
2329 // Perform the quick checks that will tell us whether these
2330 // function types are obviously different.
2331 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2332 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2333 return false;
2334
2335 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2336 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2337 if (FromEInfo != ToEInfo)
2338 return false;
2339
2340 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002341 if (Context.hasSameType(FromFunctionType->getResultType(),
2342 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002343 // Okay, the types match exactly. Nothing to do.
2344 } else {
2345 QualType RHS = FromFunctionType->getResultType();
2346 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002347 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002348 !RHS.hasQualifiers() && LHS.hasQualifiers())
2349 LHS = LHS.getUnqualifiedType();
2350
2351 if (Context.hasSameType(RHS,LHS)) {
2352 // OK exact match.
2353 } else if (isObjCPointerConversion(RHS, LHS,
2354 ConvertedType, IncompatibleObjC)) {
2355 if (IncompatibleObjC)
2356 return false;
2357 // Okay, we have an Objective-C pointer conversion.
2358 }
2359 else
2360 return false;
2361 }
2362
2363 // Check argument types.
2364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2365 ArgIdx != NumArgs; ++ArgIdx) {
2366 IncompatibleObjC = false;
2367 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2368 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2369 if (Context.hasSameType(FromArgType, ToArgType)) {
2370 // Okay, the types match exactly. Nothing to do.
2371 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2372 ConvertedType, IncompatibleObjC)) {
2373 if (IncompatibleObjC)
2374 return false;
2375 // Okay, we have an Objective-C pointer conversion.
2376 } else
2377 // Argument types are too different. Abort.
2378 return false;
2379 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002380 if (LangOpts.ObjCAutoRefCount &&
2381 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2382 ToFunctionType))
2383 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002384
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002385 ConvertedType = ToType;
2386 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002387}
2388
Richard Trieucaff2472011-11-23 22:32:32 +00002389enum {
2390 ft_default,
2391 ft_different_class,
2392 ft_parameter_arity,
2393 ft_parameter_mismatch,
2394 ft_return_type,
2395 ft_qualifer_mismatch
2396};
2397
2398/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2399/// function types. Catches different number of parameter, mismatch in
2400/// parameter types, and different return types.
2401void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2402 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002403 // If either type is not valid, include no extra info.
2404 if (FromType.isNull() || ToType.isNull()) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
Richard Trieucaff2472011-11-23 22:32:32 +00002409 // Get the function type from the pointers.
2410 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2411 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2412 *ToMember = ToType->getAs<MemberPointerType>();
2413 if (FromMember->getClass() != ToMember->getClass()) {
2414 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2415 << QualType(FromMember->getClass(), 0);
2416 return;
2417 }
2418 FromType = FromMember->getPointeeType();
2419 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002420 }
2421
Richard Trieu96ed5b62011-12-13 23:19:45 +00002422 if (FromType->isPointerType())
2423 FromType = FromType->getPointeeType();
2424 if (ToType->isPointerType())
2425 ToType = ToType->getPointeeType();
2426
2427 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002428 FromType = FromType.getNonReferenceType();
2429 ToType = ToType.getNonReferenceType();
2430
Richard Trieucaff2472011-11-23 22:32:32 +00002431 // Don't print extra info for non-specialized template functions.
2432 if (FromType->isInstantiationDependentType() &&
2433 !FromType->getAs<TemplateSpecializationType>()) {
2434 PDiag << ft_default;
2435 return;
2436 }
2437
Richard Trieu96ed5b62011-12-13 23:19:45 +00002438 // No extra info for same types.
2439 if (Context.hasSameType(FromType, ToType)) {
2440 PDiag << ft_default;
2441 return;
2442 }
2443
Richard Trieucaff2472011-11-23 22:32:32 +00002444 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2445 *ToFunction = ToType->getAs<FunctionProtoType>();
2446
2447 // Both types need to be function types.
2448 if (!FromFunction || !ToFunction) {
2449 PDiag << ft_default;
2450 return;
2451 }
2452
2453 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2454 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2455 << FromFunction->getNumArgs();
2456 return;
2457 }
2458
2459 // Handle different parameter types.
2460 unsigned ArgPos;
2461 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2462 PDiag << ft_parameter_mismatch << ArgPos + 1
2463 << ToFunction->getArgType(ArgPos)
2464 << FromFunction->getArgType(ArgPos);
2465 return;
2466 }
2467
2468 // Handle different return type.
2469 if (!Context.hasSameType(FromFunction->getResultType(),
2470 ToFunction->getResultType())) {
2471 PDiag << ft_return_type << ToFunction->getResultType()
2472 << FromFunction->getResultType();
2473 return;
2474 }
2475
2476 unsigned FromQuals = FromFunction->getTypeQuals(),
2477 ToQuals = ToFunction->getTypeQuals();
2478 if (FromQuals != ToQuals) {
2479 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2480 return;
2481 }
2482
2483 // Unable to find a difference, so add no extra info.
2484 PDiag << ft_default;
2485}
2486
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002487/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002488/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002489/// they have same number of arguments. This routine assumes that Objective-C
2490/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002491/// If the parameters are different, ArgPos will have the the parameter index
2492/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002493bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002494 const FunctionProtoType *NewType,
2495 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002496 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002497 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2498 N = NewType->arg_type_begin(),
2499 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2500 if (!Context.hasSameType(*O, *N)) {
2501 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2502 return false;
2503 }
2504 }
2505 return true;
2506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002508 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2509 N = NewType->arg_type_begin(),
2510 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2511 QualType ToType = (*O);
2512 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002513 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002514 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2515 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002516 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2517 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2518 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2519 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002520 continue;
2521 }
John McCall8b07ec22010-05-15 11:32:37 +00002522 else if (const ObjCObjectPointerType *PTTo =
2523 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002525 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002526 if (Context.hasSameUnqualifiedType(
2527 PTTo->getObjectType()->getBaseType(),
2528 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002529 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002530 }
Richard Trieucaff2472011-11-23 22:32:32 +00002531 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002533 }
2534 }
2535 return true;
2536}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002537
Douglas Gregor39c16d42008-10-24 04:54:22 +00002538/// CheckPointerConversion - Check the pointer conversion from the
2539/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002540/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002541/// conversions for which IsPointerConversion has already returned
2542/// true. It returns true and produces a diagnostic if there was an
2543/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002544bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002545 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002546 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002547 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002548 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002549 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002550
John McCall8cb679e2010-11-15 09:13:47 +00002551 Kind = CK_BitCast;
2552
Chandler Carruthffab8732011-04-09 07:32:05 +00002553 if (!IsCStyleOrFunctionalCast &&
2554 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2555 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2556 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002557 PDiag(diag::warn_impcast_bool_to_null_pointer)
2558 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002559
John McCall9320b872011-09-09 05:25:32 +00002560 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2561 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002562 QualType FromPointeeType = FromPtrType->getPointeeType(),
2563 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002564
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002565 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2566 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002567 // We must have a derived-to-base conversion. Check an
2568 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002569 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2570 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002571 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002572 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002573 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002575 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002576 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002577 }
2578 }
John McCall9320b872011-09-09 05:25:32 +00002579 } else if (const ObjCObjectPointerType *ToPtrType =
2580 ToType->getAs<ObjCObjectPointerType>()) {
2581 if (const ObjCObjectPointerType *FromPtrType =
2582 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002583 // Objective-C++ conversions are always okay.
2584 // FIXME: We should have a different class of conversions for the
2585 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002586 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002587 return false;
John McCall9320b872011-09-09 05:25:32 +00002588 } else if (FromType->isBlockPointerType()) {
2589 Kind = CK_BlockPointerToObjCPointerCast;
2590 } else {
2591 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002592 }
John McCall9320b872011-09-09 05:25:32 +00002593 } else if (ToType->isBlockPointerType()) {
2594 if (!FromType->isBlockPointerType())
2595 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002596 }
John McCall8cb679e2010-11-15 09:13:47 +00002597
2598 // We shouldn't fall into this case unless it's valid for other
2599 // reasons.
2600 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2601 Kind = CK_NullToPointer;
2602
Douglas Gregor39c16d42008-10-24 04:54:22 +00002603 return false;
2604}
2605
Sebastian Redl72b597d2009-01-25 19:43:20 +00002606/// IsMemberPointerConversion - Determines whether the conversion of the
2607/// expression From, which has the (possibly adjusted) type FromType, can be
2608/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2609/// If so, returns true and places the converted type (that might differ from
2610/// ToType in its cv-qualifiers at some level) into ConvertedType.
2611bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002613 bool InOverloadResolution,
2614 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002615 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002616 if (!ToTypePtr)
2617 return false;
2618
2619 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002620 if (From->isNullPointerConstant(Context,
2621 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2622 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002623 ConvertedType = ToType;
2624 return true;
2625 }
2626
2627 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002628 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002629 if (!FromTypePtr)
2630 return false;
2631
2632 // A pointer to member of B can be converted to a pointer to member of D,
2633 // where D is derived from B (C++ 4.11p2).
2634 QualType FromClass(FromTypePtr->getClass(), 0);
2635 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002636
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002637 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002638 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002639 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002640 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2641 ToClass.getTypePtr());
2642 return true;
2643 }
2644
2645 return false;
2646}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647
Sebastian Redl72b597d2009-01-25 19:43:20 +00002648/// CheckMemberPointerConversion - Check the member pointer conversion from the
2649/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002650/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002651/// for which IsMemberPointerConversion has already returned true. It returns
2652/// true and produces a diagnostic if there was an error, or returns false
2653/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002654bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002655 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002656 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002657 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002658 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002659 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002660 if (!FromPtrType) {
2661 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002663 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002664 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002665 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002666 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002667 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002668
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002669 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002670 assert(ToPtrType && "No member pointer cast has a target type "
2671 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002672
Sebastian Redled8f2002009-01-28 18:33:18 +00002673 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2674 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002675
Sebastian Redled8f2002009-01-28 18:33:18 +00002676 // FIXME: What about dependent types?
2677 assert(FromClass->isRecordType() && "Pointer into non-class.");
2678 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002679
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002680 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002681 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002682 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2683 assert(DerivationOkay &&
2684 "Should not have been called if derivation isn't OK.");
2685 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002686
Sebastian Redled8f2002009-01-28 18:33:18 +00002687 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2688 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002689 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2690 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2691 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2692 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002693 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002694
Douglas Gregor89ee6822009-02-28 01:32:25 +00002695 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002696 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2697 << FromClass << ToClass << QualType(VBase, 0)
2698 << From->getSourceRange();
2699 return true;
2700 }
2701
John McCall5b0829a2010-02-10 09:31:12 +00002702 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002703 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2704 Paths.front(),
2705 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002706
Anders Carlssond7923c62009-08-22 23:33:40 +00002707 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002708 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002709 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002710 return false;
2711}
2712
Douglas Gregor9a657932008-10-21 23:43:52 +00002713/// IsQualificationConversion - Determines whether the conversion from
2714/// an rvalue of type FromType to ToType is a qualification conversion
2715/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002716///
2717/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2718/// when the qualification conversion involves a change in the Objective-C
2719/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002720bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002722 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002723 FromType = Context.getCanonicalType(FromType);
2724 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002725 ObjCLifetimeConversion = false;
2726
Douglas Gregor9a657932008-10-21 23:43:52 +00002727 // If FromType and ToType are the same type, this is not a
2728 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002729 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002730 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002731
Douglas Gregor9a657932008-10-21 23:43:52 +00002732 // (C++ 4.4p4):
2733 // A conversion can add cv-qualifiers at levels other than the first
2734 // in multi-level pointers, subject to the following rules: [...]
2735 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002736 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002737 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002738 // Within each iteration of the loop, we check the qualifiers to
2739 // determine if this still looks like a qualification
2740 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002741 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002742 // until there are no more pointers or pointers-to-members left to
2743 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002744 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002745
Douglas Gregor90609aa2011-04-25 18:40:17 +00002746 Qualifiers FromQuals = FromType.getQualifiers();
2747 Qualifiers ToQuals = ToType.getQualifiers();
2748
John McCall31168b02011-06-15 23:02:42 +00002749 // Objective-C ARC:
2750 // Check Objective-C lifetime conversions.
2751 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2752 UnwrappedAnyPointer) {
2753 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2754 ObjCLifetimeConversion = true;
2755 FromQuals.removeObjCLifetime();
2756 ToQuals.removeObjCLifetime();
2757 } else {
2758 // Qualification conversions cannot cast between different
2759 // Objective-C lifetime qualifiers.
2760 return false;
2761 }
2762 }
2763
Douglas Gregorf30053d2011-05-08 06:09:53 +00002764 // Allow addition/removal of GC attributes but not changing GC attributes.
2765 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2766 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2767 FromQuals.removeObjCGCAttr();
2768 ToQuals.removeObjCGCAttr();
2769 }
2770
Douglas Gregor9a657932008-10-21 23:43:52 +00002771 // -- for every j > 0, if const is in cv 1,j then const is in cv
2772 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002773 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002774 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregor9a657932008-10-21 23:43:52 +00002776 // -- if the cv 1,j and cv 2,j are different, then const is in
2777 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002778 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002779 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002780 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002781
Douglas Gregor9a657932008-10-21 23:43:52 +00002782 // Keep track of whether all prior cv-qualifiers in the "to" type
2783 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002784 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002785 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002786 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002787
2788 // We are left with FromType and ToType being the pointee types
2789 // after unwrapping the original FromType and ToType the same number
2790 // of types. If we unwrapped any pointers, and if FromType and
2791 // ToType have the same unqualified type (since we checked
2792 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002793 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002794}
2795
Douglas Gregorc79862f2012-04-12 17:51:55 +00002796/// \brief - Determine whether this is a conversion from a scalar type to an
2797/// atomic type.
2798///
2799/// If successful, updates \c SCS's second and third steps in the conversion
2800/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002801static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2802 bool InOverloadResolution,
2803 StandardConversionSequence &SCS,
2804 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002805 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2806 if (!ToAtomic)
2807 return false;
2808
2809 StandardConversionSequence InnerSCS;
2810 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2811 InOverloadResolution, InnerSCS,
2812 CStyle, /*AllowObjCWritebackConversion=*/false))
2813 return false;
2814
2815 SCS.Second = InnerSCS.Second;
2816 SCS.setToType(1, InnerSCS.getToType(1));
2817 SCS.Third = InnerSCS.Third;
2818 SCS.QualificationIncludesObjCLifetime
2819 = InnerSCS.QualificationIncludesObjCLifetime;
2820 SCS.setToType(2, InnerSCS.getToType(2));
2821 return true;
2822}
2823
Sebastian Redle5417162012-03-27 18:33:03 +00002824static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2825 CXXConstructorDecl *Constructor,
2826 QualType Type) {
2827 const FunctionProtoType *CtorType =
2828 Constructor->getType()->getAs<FunctionProtoType>();
2829 if (CtorType->getNumArgs() > 0) {
2830 QualType FirstArg = CtorType->getArgType(0);
2831 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2832 return true;
2833 }
2834 return false;
2835}
2836
Sebastian Redl82ace982012-02-11 23:51:08 +00002837static OverloadingResult
2838IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2839 CXXRecordDecl *To,
2840 UserDefinedConversionSequence &User,
2841 OverloadCandidateSet &CandidateSet,
2842 bool AllowExplicit) {
2843 DeclContext::lookup_iterator Con, ConEnd;
2844 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2845 Con != ConEnd; ++Con) {
2846 NamedDecl *D = *Con;
2847 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2848
2849 // Find the constructor (which may be a template).
2850 CXXConstructorDecl *Constructor = 0;
2851 FunctionTemplateDecl *ConstructorTmpl
2852 = dyn_cast<FunctionTemplateDecl>(D);
2853 if (ConstructorTmpl)
2854 Constructor
2855 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2856 else
2857 Constructor = cast<CXXConstructorDecl>(D);
2858
2859 bool Usable = !Constructor->isInvalidDecl() &&
2860 S.isInitListConstructor(Constructor) &&
2861 (AllowExplicit || !Constructor->isExplicit());
2862 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002863 // If the first argument is (a reference to) the target type,
2864 // suppress conversions.
2865 bool SuppressUserConversions =
2866 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002867 if (ConstructorTmpl)
2868 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2869 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002870 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002871 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002872 else
2873 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002874 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002875 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002876 }
2877 }
2878
2879 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2880
2881 OverloadCandidateSet::iterator Best;
2882 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2883 case OR_Success: {
2884 // Record the standard conversion we used and the conversion function.
2885 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2886 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2887
2888 QualType ThisType = Constructor->getThisType(S.Context);
2889 // Initializer lists don't have conversions as such.
2890 User.Before.setAsIdentityConversion();
2891 User.HadMultipleCandidates = HadMultipleCandidates;
2892 User.ConversionFunction = Constructor;
2893 User.FoundConversionFunction = Best->FoundDecl;
2894 User.After.setAsIdentityConversion();
2895 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2896 User.After.setAllToTypes(ToType);
2897 return OR_Success;
2898 }
2899
2900 case OR_No_Viable_Function:
2901 return OR_No_Viable_Function;
2902 case OR_Deleted:
2903 return OR_Deleted;
2904 case OR_Ambiguous:
2905 return OR_Ambiguous;
2906 }
2907
2908 llvm_unreachable("Invalid OverloadResult!");
2909}
2910
Douglas Gregor576e98c2009-01-30 23:27:23 +00002911/// Determines whether there is a user-defined conversion sequence
2912/// (C++ [over.ics.user]) that converts expression From to the type
2913/// ToType. If such a conversion exists, User will contain the
2914/// user-defined conversion sequence that performs such a conversion
2915/// and this routine will return true. Otherwise, this routine returns
2916/// false and User is unspecified.
2917///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002918/// \param AllowExplicit true if the conversion should consider C++0x
2919/// "explicit" conversion functions as well as non-explicit conversion
2920/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002921static OverloadingResult
2922IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002923 UserDefinedConversionSequence &User,
2924 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002925 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002926 // Whether we will only visit constructors.
2927 bool ConstructorsOnly = false;
2928
2929 // If the type we are conversion to is a class type, enumerate its
2930 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002931 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002932 // C++ [over.match.ctor]p1:
2933 // When objects of class type are direct-initialized (8.5), or
2934 // copy-initialized from an expression of the same or a
2935 // derived class type (8.5), overload resolution selects the
2936 // constructor. [...] For copy-initialization, the candidate
2937 // functions are all the converting constructors (12.3.1) of
2938 // that class. The argument list is the expression-list within
2939 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002940 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002941 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002942 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002943 ConstructorsOnly = true;
2944
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002945 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002946 // RequireCompleteType may have returned true due to some invalid decl
2947 // during template instantiation, but ToType may be complete enough now
2948 // to try to recover.
2949 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002950 // We're not going to find any constructors.
2951 } else if (CXXRecordDecl *ToRecordDecl
2952 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002953
2954 Expr **Args = &From;
2955 unsigned NumArgs = 1;
2956 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002957 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002958 // But first, see if there is an init-list-contructor that will work.
2959 OverloadingResult Result = IsInitializerListConstructorConversion(
2960 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2961 if (Result != OR_No_Viable_Function)
2962 return Result;
2963 // Never mind.
2964 CandidateSet.clear();
2965
2966 // If we're list-initializing, we pass the individual elements as
2967 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002968 Args = InitList->getInits();
2969 NumArgs = InitList->getNumInits();
2970 ListInitializing = true;
2971 }
2972
Douglas Gregor89ee6822009-02-28 01:32:25 +00002973 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002974 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002975 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002976 NamedDecl *D = *Con;
2977 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2978
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002979 // Find the constructor (which may be a template).
2980 CXXConstructorDecl *Constructor = 0;
2981 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002982 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002983 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002984 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002985 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2986 else
John McCalla0296f72010-03-19 07:35:19 +00002987 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002989 bool Usable = !Constructor->isInvalidDecl();
2990 if (ListInitializing)
2991 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2992 else
2993 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2994 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00002995 bool SuppressUserConversions = !ConstructorsOnly;
2996 if (SuppressUserConversions && ListInitializing) {
2997 SuppressUserConversions = false;
2998 if (NumArgs == 1) {
2999 // If the first argument is (a reference to) the target type,
3000 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003001 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3002 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003003 }
3004 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003005 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003006 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3007 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003008 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003009 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003010 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003011 // Allow one user-defined conversion when user specifies a
3012 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003013 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003014 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003015 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003016 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003017 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003018 }
3019 }
3020
Douglas Gregor5ab11652010-04-17 22:01:05 +00003021 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003022 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003023 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003024 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003025 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003026 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003027 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003028 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3029 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00003030 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003031 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003032 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003033 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003034 DeclAccessPair FoundDecl = I.getPair();
3035 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003036 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3037 if (isa<UsingShadowDecl>(D))
3038 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3039
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003040 CXXConversionDecl *Conv;
3041 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003042 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3043 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003044 else
John McCallda4458e2010-03-31 01:36:47 +00003045 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003046
3047 if (AllowExplicit || !Conv->isExplicit()) {
3048 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003049 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3050 ActingContext, From, ToType,
3051 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003052 else
John McCall5c32be02010-08-24 20:38:10 +00003053 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3054 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003055 }
3056 }
3057 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003058 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003059
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003060 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3061
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003062 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003063 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003064 case OR_Success:
3065 // Record the standard conversion we used and the conversion function.
3066 if (CXXConstructorDecl *Constructor
3067 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003068 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003069
John McCall5c32be02010-08-24 20:38:10 +00003070 // C++ [over.ics.user]p1:
3071 // If the user-defined conversion is specified by a
3072 // constructor (12.3.1), the initial standard conversion
3073 // sequence converts the source type to the type required by
3074 // the argument of the constructor.
3075 //
3076 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003077 if (isa<InitListExpr>(From)) {
3078 // Initializer lists don't have conversions as such.
3079 User.Before.setAsIdentityConversion();
3080 } else {
3081 if (Best->Conversions[0].isEllipsis())
3082 User.EllipsisConversion = true;
3083 else {
3084 User.Before = Best->Conversions[0].Standard;
3085 User.EllipsisConversion = false;
3086 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003087 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003088 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003089 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003090 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003091 User.After.setAsIdentityConversion();
3092 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3093 User.After.setAllToTypes(ToType);
3094 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003095 }
3096 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003097 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003098 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003099
John McCall5c32be02010-08-24 20:38:10 +00003100 // C++ [over.ics.user]p1:
3101 //
3102 // [...] If the user-defined conversion is specified by a
3103 // conversion function (12.3.2), the initial standard
3104 // conversion sequence converts the source type to the
3105 // implicit object parameter of the conversion function.
3106 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003107 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003108 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003109 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003110 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003111
John McCall5c32be02010-08-24 20:38:10 +00003112 // C++ [over.ics.user]p2:
3113 // The second standard conversion sequence converts the
3114 // result of the user-defined conversion to the target type
3115 // for the sequence. Since an implicit conversion sequence
3116 // is an initialization, the special rules for
3117 // initialization by user-defined conversion apply when
3118 // selecting the best user-defined conversion for a
3119 // user-defined conversion sequence (see 13.3.3 and
3120 // 13.3.3.1).
3121 User.After = Best->FinalConversion;
3122 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003123 }
David Blaikie8a40f702012-01-17 06:56:22 +00003124 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003125
John McCall5c32be02010-08-24 20:38:10 +00003126 case OR_No_Viable_Function:
3127 return OR_No_Viable_Function;
3128 case OR_Deleted:
3129 // No conversion here! We're done.
3130 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131
John McCall5c32be02010-08-24 20:38:10 +00003132 case OR_Ambiguous:
3133 return OR_Ambiguous;
3134 }
3135
David Blaikie8a40f702012-01-17 06:56:22 +00003136 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003137}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003139bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003140Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003141 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003142 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003144 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003145 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003146 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003147 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003148 diag::err_typecheck_ambiguous_condition)
3149 << From->getType() << ToType << From->getSourceRange();
3150 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003151 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003152 diag::err_typecheck_nonviable_condition)
3153 << From->getType() << ToType << From->getSourceRange();
3154 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003155 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003158}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003159
Douglas Gregor2837aa22012-02-22 17:32:19 +00003160/// \brief Compare the user-defined conversion functions or constructors
3161/// of two user-defined conversion sequences to determine whether any ordering
3162/// is possible.
3163static ImplicitConversionSequence::CompareKind
3164compareConversionFunctions(Sema &S,
3165 FunctionDecl *Function1,
3166 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003167 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003168 return ImplicitConversionSequence::Indistinguishable;
3169
3170 // Objective-C++:
3171 // If both conversion functions are implicitly-declared conversions from
3172 // a lambda closure type to a function pointer and a block pointer,
3173 // respectively, always prefer the conversion to a function pointer,
3174 // because the function pointer is more lightweight and is more likely
3175 // to keep code working.
3176 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3177 if (!Conv1)
3178 return ImplicitConversionSequence::Indistinguishable;
3179
3180 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3181 if (!Conv2)
3182 return ImplicitConversionSequence::Indistinguishable;
3183
3184 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3185 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3186 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3187 if (Block1 != Block2)
3188 return Block1? ImplicitConversionSequence::Worse
3189 : ImplicitConversionSequence::Better;
3190 }
3191
3192 return ImplicitConversionSequence::Indistinguishable;
3193}
3194
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003195/// CompareImplicitConversionSequences - Compare two implicit
3196/// conversion sequences to determine whether one is better than the
3197/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003198static ImplicitConversionSequence::CompareKind
3199CompareImplicitConversionSequences(Sema &S,
3200 const ImplicitConversionSequence& ICS1,
3201 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003202{
3203 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3204 // conversion sequences (as defined in 13.3.3.1)
3205 // -- a standard conversion sequence (13.3.3.1.1) is a better
3206 // conversion sequence than a user-defined conversion sequence or
3207 // an ellipsis conversion sequence, and
3208 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3209 // conversion sequence than an ellipsis conversion sequence
3210 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003211 //
John McCall0d1da222010-01-12 00:44:57 +00003212 // C++0x [over.best.ics]p10:
3213 // For the purpose of ranking implicit conversion sequences as
3214 // described in 13.3.3.2, the ambiguous conversion sequence is
3215 // treated as a user-defined sequence that is indistinguishable
3216 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003217 if (ICS1.getKindRank() < ICS2.getKindRank())
3218 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003219 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003220 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003221
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003222 // The following checks require both conversion sequences to be of
3223 // the same kind.
3224 if (ICS1.getKind() != ICS2.getKind())
3225 return ImplicitConversionSequence::Indistinguishable;
3226
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003227 ImplicitConversionSequence::CompareKind Result =
3228 ImplicitConversionSequence::Indistinguishable;
3229
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003230 // Two implicit conversion sequences of the same form are
3231 // indistinguishable conversion sequences unless one of the
3232 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003233 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003234 Result = CompareStandardConversionSequences(S,
3235 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003236 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003237 // User-defined conversion sequence U1 is a better conversion
3238 // sequence than another user-defined conversion sequence U2 if
3239 // they contain the same user-defined conversion function or
3240 // constructor and if the second standard conversion sequence of
3241 // U1 is better than the second standard conversion sequence of
3242 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003243 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003244 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003245 Result = CompareStandardConversionSequences(S,
3246 ICS1.UserDefined.After,
3247 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003248 else
3249 Result = compareConversionFunctions(S,
3250 ICS1.UserDefined.ConversionFunction,
3251 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003252 }
3253
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003254 // List-initialization sequence L1 is a better conversion sequence than
3255 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3256 // for some X and L2 does not.
3257 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003258 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003259 ICS1.isListInitializationSequence() &&
3260 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003261 if (ICS1.isStdInitializerListElement() &&
3262 !ICS2.isStdInitializerListElement())
3263 return ImplicitConversionSequence::Better;
3264 if (!ICS1.isStdInitializerListElement() &&
3265 ICS2.isStdInitializerListElement())
3266 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003267 }
3268
3269 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003270}
3271
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003272static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3273 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3274 Qualifiers Quals;
3275 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003279 return Context.hasSameUnqualifiedType(T1, T2);
3280}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003281
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003282// Per 13.3.3.2p3, compare the given standard conversion sequences to
3283// determine if one is a proper subset of the other.
3284static ImplicitConversionSequence::CompareKind
3285compareStandardConversionSubsets(ASTContext &Context,
3286 const StandardConversionSequence& SCS1,
3287 const StandardConversionSequence& SCS2) {
3288 ImplicitConversionSequence::CompareKind Result
3289 = ImplicitConversionSequence::Indistinguishable;
3290
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003292 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003293 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3294 return ImplicitConversionSequence::Better;
3295 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3296 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003298 if (SCS1.Second != SCS2.Second) {
3299 if (SCS1.Second == ICK_Identity)
3300 Result = ImplicitConversionSequence::Better;
3301 else if (SCS2.Second == ICK_Identity)
3302 Result = ImplicitConversionSequence::Worse;
3303 else
3304 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003305 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003306 return ImplicitConversionSequence::Indistinguishable;
3307
3308 if (SCS1.Third == SCS2.Third) {
3309 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3310 : ImplicitConversionSequence::Indistinguishable;
3311 }
3312
3313 if (SCS1.Third == ICK_Identity)
3314 return Result == ImplicitConversionSequence::Worse
3315 ? ImplicitConversionSequence::Indistinguishable
3316 : ImplicitConversionSequence::Better;
3317
3318 if (SCS2.Third == ICK_Identity)
3319 return Result == ImplicitConversionSequence::Better
3320 ? ImplicitConversionSequence::Indistinguishable
3321 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003323 return ImplicitConversionSequence::Indistinguishable;
3324}
3325
Douglas Gregore696ebb2011-01-26 14:52:12 +00003326/// \brief Determine whether one of the given reference bindings is better
3327/// than the other based on what kind of bindings they are.
3328static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3329 const StandardConversionSequence &SCS2) {
3330 // C++0x [over.ics.rank]p3b4:
3331 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3332 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003334 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003336 // reference*.
3337 //
3338 // FIXME: Rvalue references. We're going rogue with the above edits,
3339 // because the semantics in the current C++0x working paper (N3225 at the
3340 // time of this writing) break the standard definition of std::forward
3341 // and std::reference_wrapper when dealing with references to functions.
3342 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003343 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3344 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3345 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
Douglas Gregore696ebb2011-01-26 14:52:12 +00003347 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3348 SCS2.IsLvalueReference) ||
3349 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3350 !SCS2.IsLvalueReference);
3351}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003353/// CompareStandardConversionSequences - Compare two standard
3354/// conversion sequences to determine whether one is better than the
3355/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003356static ImplicitConversionSequence::CompareKind
3357CompareStandardConversionSequences(Sema &S,
3358 const StandardConversionSequence& SCS1,
3359 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003360{
3361 // Standard conversion sequence S1 is a better conversion sequence
3362 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3363
3364 // -- S1 is a proper subsequence of S2 (comparing the conversion
3365 // sequences in the canonical form defined by 13.3.3.1.1,
3366 // excluding any Lvalue Transformation; the identity conversion
3367 // sequence is considered to be a subsequence of any
3368 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003369 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003370 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003371 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003372
3373 // -- the rank of S1 is better than the rank of S2 (by the rules
3374 // defined below), or, if not that,
3375 ImplicitConversionRank Rank1 = SCS1.getRank();
3376 ImplicitConversionRank Rank2 = SCS2.getRank();
3377 if (Rank1 < Rank2)
3378 return ImplicitConversionSequence::Better;
3379 else if (Rank2 < Rank1)
3380 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003381
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003382 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3383 // are indistinguishable unless one of the following rules
3384 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003385
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003386 // A conversion that is not a conversion of a pointer, or
3387 // pointer to member, to bool is better than another conversion
3388 // that is such a conversion.
3389 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3390 return SCS2.isPointerConversionToBool()
3391 ? ImplicitConversionSequence::Better
3392 : ImplicitConversionSequence::Worse;
3393
Douglas Gregor5c407d92008-10-23 00:40:37 +00003394 // C++ [over.ics.rank]p4b2:
3395 //
3396 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003397 // conversion of B* to A* is better than conversion of B* to
3398 // void*, and conversion of A* to void* is better than conversion
3399 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003400 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003401 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003402 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003403 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003404 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3405 // Exactly one of the conversion sequences is a conversion to
3406 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003407 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3408 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003409 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3410 // Neither conversion sequence converts to a void pointer; compare
3411 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003412 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003413 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003414 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003415 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3416 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003417 // Both conversion sequences are conversions to void
3418 // pointers. Compare the source types to determine if there's an
3419 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003420 QualType FromType1 = SCS1.getFromType();
3421 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003422
3423 // Adjust the types we're converting from via the array-to-pointer
3424 // conversion, if we need to.
3425 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003426 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003427 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003428 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003429
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003430 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3431 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003432
John McCall5c32be02010-08-24 20:38:10 +00003433 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003434 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003435 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003436 return ImplicitConversionSequence::Worse;
3437
3438 // Objective-C++: If one interface is more specific than the
3439 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003440 const ObjCObjectPointerType* FromObjCPtr1
3441 = FromType1->getAs<ObjCObjectPointerType>();
3442 const ObjCObjectPointerType* FromObjCPtr2
3443 = FromType2->getAs<ObjCObjectPointerType>();
3444 if (FromObjCPtr1 && FromObjCPtr2) {
3445 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3446 FromObjCPtr2);
3447 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3448 FromObjCPtr1);
3449 if (AssignLeft != AssignRight) {
3450 return AssignLeft? ImplicitConversionSequence::Better
3451 : ImplicitConversionSequence::Worse;
3452 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003453 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003454 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003455
3456 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3457 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003458 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003459 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003460 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003461
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003462 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003463 // Check for a better reference binding based on the kind of bindings.
3464 if (isBetterReferenceBindingKind(SCS1, SCS2))
3465 return ImplicitConversionSequence::Better;
3466 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3467 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Sebastian Redlb28b4072009-03-22 23:49:27 +00003469 // C++ [over.ics.rank]p3b4:
3470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3471 // which the references refer are the same type except for
3472 // top-level cv-qualifiers, and the type to which the reference
3473 // initialized by S2 refers is more cv-qualified than the type
3474 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003475 QualType T1 = SCS1.getToType(2);
3476 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003477 T1 = S.Context.getCanonicalType(T1);
3478 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003479 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003482 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003483 // Objective-C++ ARC: If the references refer to objects with different
3484 // lifetimes, prefer bindings that don't change lifetime.
3485 if (SCS1.ObjCLifetimeConversionBinding !=
3486 SCS2.ObjCLifetimeConversionBinding) {
3487 return SCS1.ObjCLifetimeConversionBinding
3488 ? ImplicitConversionSequence::Worse
3489 : ImplicitConversionSequence::Better;
3490 }
3491
Chandler Carruth8e543b32010-12-12 08:17:55 +00003492 // If the type is an array type, promote the element qualifiers to the
3493 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003494 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003495 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003496 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003497 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003498 if (T2.isMoreQualifiedThan(T1))
3499 return ImplicitConversionSequence::Better;
3500 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003501 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003502 }
3503 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003504
Francois Pichet08d2fa02011-09-18 21:37:37 +00003505 // In Microsoft mode, prefer an integral conversion to a
3506 // floating-to-integral conversion if the integral conversion
3507 // is between types of the same size.
3508 // For example:
3509 // void f(float);
3510 // void f(int);
3511 // int main {
3512 // long a;
3513 // f(a);
3514 // }
3515 // Here, MSVC will call f(int) instead of generating a compile error
3516 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003517 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003518 SCS1.Second == ICK_Integral_Conversion &&
3519 SCS2.Second == ICK_Floating_Integral &&
3520 S.Context.getTypeSize(SCS1.getFromType()) ==
3521 S.Context.getTypeSize(SCS1.getToType(2)))
3522 return ImplicitConversionSequence::Better;
3523
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003524 return ImplicitConversionSequence::Indistinguishable;
3525}
3526
3527/// CompareQualificationConversions - Compares two standard conversion
3528/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003529/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3530ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003531CompareQualificationConversions(Sema &S,
3532 const StandardConversionSequence& SCS1,
3533 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003534 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003535 // -- S1 and S2 differ only in their qualification conversion and
3536 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3537 // cv-qualification signature of type T1 is a proper subset of
3538 // the cv-qualification signature of type T2, and S1 is not the
3539 // deprecated string literal array-to-pointer conversion (4.2).
3540 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3541 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3542 return ImplicitConversionSequence::Indistinguishable;
3543
3544 // FIXME: the example in the standard doesn't use a qualification
3545 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003546 QualType T1 = SCS1.getToType(2);
3547 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003548 T1 = S.Context.getCanonicalType(T1);
3549 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003550 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003551 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3552 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003553
3554 // If the types are the same, we won't learn anything by unwrapped
3555 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003556 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003557 return ImplicitConversionSequence::Indistinguishable;
3558
Chandler Carruth607f38e2009-12-29 07:16:59 +00003559 // If the type is an array type, promote the element qualifiers to the type
3560 // for comparison.
3561 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003562 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003563 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003564 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003565
Mike Stump11289f42009-09-09 15:08:12 +00003566 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003567 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003568
3569 // Objective-C++ ARC:
3570 // Prefer qualification conversions not involving a change in lifetime
3571 // to qualification conversions that do not change lifetime.
3572 if (SCS1.QualificationIncludesObjCLifetime !=
3573 SCS2.QualificationIncludesObjCLifetime) {
3574 Result = SCS1.QualificationIncludesObjCLifetime
3575 ? ImplicitConversionSequence::Worse
3576 : ImplicitConversionSequence::Better;
3577 }
3578
John McCall5c32be02010-08-24 20:38:10 +00003579 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003580 // Within each iteration of the loop, we check the qualifiers to
3581 // determine if this still looks like a qualification
3582 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003583 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003584 // until there are no more pointers or pointers-to-members left
3585 // to unwrap. This essentially mimics what
3586 // IsQualificationConversion does, but here we're checking for a
3587 // strict subset of qualifiers.
3588 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3589 // The qualifiers are the same, so this doesn't tell us anything
3590 // about how the sequences rank.
3591 ;
3592 else if (T2.isMoreQualifiedThan(T1)) {
3593 // T1 has fewer qualifiers, so it could be the better sequence.
3594 if (Result == ImplicitConversionSequence::Worse)
3595 // Neither has qualifiers that are a subset of the other's
3596 // qualifiers.
3597 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003598
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003599 Result = ImplicitConversionSequence::Better;
3600 } else if (T1.isMoreQualifiedThan(T2)) {
3601 // T2 has fewer qualifiers, so it could be the better sequence.
3602 if (Result == ImplicitConversionSequence::Better)
3603 // Neither has qualifiers that are a subset of the other's
3604 // qualifiers.
3605 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003607 Result = ImplicitConversionSequence::Worse;
3608 } else {
3609 // Qualifiers are disjoint.
3610 return ImplicitConversionSequence::Indistinguishable;
3611 }
3612
3613 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003614 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003615 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003616 }
3617
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003618 // Check that the winning standard conversion sequence isn't using
3619 // the deprecated string literal array to pointer conversion.
3620 switch (Result) {
3621 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003622 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003623 Result = ImplicitConversionSequence::Indistinguishable;
3624 break;
3625
3626 case ImplicitConversionSequence::Indistinguishable:
3627 break;
3628
3629 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003630 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003631 Result = ImplicitConversionSequence::Indistinguishable;
3632 break;
3633 }
3634
3635 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003636}
3637
Douglas Gregor5c407d92008-10-23 00:40:37 +00003638/// CompareDerivedToBaseConversions - Compares two standard conversion
3639/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003640/// various kinds of derived-to-base conversions (C++
3641/// [over.ics.rank]p4b3). As part of these checks, we also look at
3642/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003643ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003644CompareDerivedToBaseConversions(Sema &S,
3645 const StandardConversionSequence& SCS1,
3646 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003647 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003648 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003649 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003650 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003651
3652 // Adjust the types we're converting from via the array-to-pointer
3653 // conversion, if we need to.
3654 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003655 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003656 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003657 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003658
3659 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003660 FromType1 = S.Context.getCanonicalType(FromType1);
3661 ToType1 = S.Context.getCanonicalType(ToType1);
3662 FromType2 = S.Context.getCanonicalType(FromType2);
3663 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003664
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003665 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003666 //
3667 // If class B is derived directly or indirectly from class A and
3668 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003669 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003670 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003671 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003672 SCS2.Second == ICK_Pointer_Conversion &&
3673 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3674 FromType1->isPointerType() && FromType2->isPointerType() &&
3675 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003676 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003677 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003678 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003679 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003680 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003681 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003682 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003684
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003685 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003686 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003687 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003688 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003689 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003690 return ImplicitConversionSequence::Worse;
3691 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003692
3693 // -- conversion of B* to A* is better than conversion of C* to A*,
3694 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003695 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003696 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003697 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003698 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003699 }
3700 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3701 SCS2.Second == ICK_Pointer_Conversion) {
3702 const ObjCObjectPointerType *FromPtr1
3703 = FromType1->getAs<ObjCObjectPointerType>();
3704 const ObjCObjectPointerType *FromPtr2
3705 = FromType2->getAs<ObjCObjectPointerType>();
3706 const ObjCObjectPointerType *ToPtr1
3707 = ToType1->getAs<ObjCObjectPointerType>();
3708 const ObjCObjectPointerType *ToPtr2
3709 = ToType2->getAs<ObjCObjectPointerType>();
3710
3711 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3712 // Apply the same conversion ranking rules for Objective-C pointer types
3713 // that we do for C++ pointers to class types. However, we employ the
3714 // Objective-C pseudo-subtyping relationship used for assignment of
3715 // Objective-C pointer types.
3716 bool FromAssignLeft
3717 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3718 bool FromAssignRight
3719 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3720 bool ToAssignLeft
3721 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3722 bool ToAssignRight
3723 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3724
3725 // A conversion to an a non-id object pointer type or qualified 'id'
3726 // type is better than a conversion to 'id'.
3727 if (ToPtr1->isObjCIdType() &&
3728 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3729 return ImplicitConversionSequence::Worse;
3730 if (ToPtr2->isObjCIdType() &&
3731 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3732 return ImplicitConversionSequence::Better;
3733
3734 // A conversion to a non-id object pointer type is better than a
3735 // conversion to a qualified 'id' type
3736 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3737 return ImplicitConversionSequence::Worse;
3738 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3739 return ImplicitConversionSequence::Better;
3740
3741 // A conversion to an a non-Class object pointer type or qualified 'Class'
3742 // type is better than a conversion to 'Class'.
3743 if (ToPtr1->isObjCClassType() &&
3744 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3745 return ImplicitConversionSequence::Worse;
3746 if (ToPtr2->isObjCClassType() &&
3747 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3748 return ImplicitConversionSequence::Better;
3749
3750 // A conversion to a non-Class object pointer type is better than a
3751 // conversion to a qualified 'Class' type.
3752 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3753 return ImplicitConversionSequence::Worse;
3754 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3755 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003756
Douglas Gregor058d3de2011-01-31 18:51:41 +00003757 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3758 if (S.Context.hasSameType(FromType1, FromType2) &&
3759 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3760 (ToAssignLeft != ToAssignRight))
3761 return ToAssignLeft? ImplicitConversionSequence::Worse
3762 : ImplicitConversionSequence::Better;
3763
3764 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3765 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3766 (FromAssignLeft != FromAssignRight))
3767 return FromAssignLeft? ImplicitConversionSequence::Better
3768 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003769 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003770 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003771
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003772 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003773 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3774 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3775 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003777 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003779 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003781 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003783 ToType2->getAs<MemberPointerType>();
3784 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3785 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3786 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3787 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3788 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3789 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3790 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3791 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003792 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003793 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003794 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003795 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003796 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003797 return ImplicitConversionSequence::Better;
3798 }
3799 // conversion of B::* to C::* is better than conversion of A::* to C::*
3800 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003801 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003802 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003803 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003804 return ImplicitConversionSequence::Worse;
3805 }
3806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807
Douglas Gregor5ab11652010-04-17 22:01:05 +00003808 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003809 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003810 // -- binding of an expression of type C to a reference of type
3811 // B& is better than binding an expression of type C to a
3812 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003813 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3814 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3815 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003816 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003817 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003818 return ImplicitConversionSequence::Worse;
3819 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003820
Douglas Gregor2fe98832008-11-03 19:09:14 +00003821 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003822 // -- binding of an expression of type B to a reference of type
3823 // A& is better than binding an expression of type C to a
3824 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003825 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3826 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3827 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003828 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003829 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003830 return ImplicitConversionSequence::Worse;
3831 }
3832 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003833
Douglas Gregor5c407d92008-10-23 00:40:37 +00003834 return ImplicitConversionSequence::Indistinguishable;
3835}
3836
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003837/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3838/// determine whether they are reference-related,
3839/// reference-compatible, reference-compatible with added
3840/// qualification, or incompatible, for use in C++ initialization by
3841/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3842/// type, and the first type (T1) is the pointee type of the reference
3843/// type being initialized.
3844Sema::ReferenceCompareResult
3845Sema::CompareReferenceRelationship(SourceLocation Loc,
3846 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003847 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003848 bool &ObjCConversion,
3849 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003850 assert(!OrigT1->isReferenceType() &&
3851 "T1 must be the pointee type of the reference type");
3852 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3853
3854 QualType T1 = Context.getCanonicalType(OrigT1);
3855 QualType T2 = Context.getCanonicalType(OrigT2);
3856 Qualifiers T1Quals, T2Quals;
3857 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3858 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3859
3860 // C++ [dcl.init.ref]p4:
3861 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3862 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3863 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003864 DerivedToBase = false;
3865 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003866 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003867 if (UnqualT1 == UnqualT2) {
3868 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003869 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003870 IsDerivedFrom(UnqualT2, UnqualT1))
3871 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003872 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3873 UnqualT2->isObjCObjectOrInterfaceType() &&
3874 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3875 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003876 else
3877 return Ref_Incompatible;
3878
3879 // At this point, we know that T1 and T2 are reference-related (at
3880 // least).
3881
3882 // If the type is an array type, promote the element qualifiers to the type
3883 // for comparison.
3884 if (isa<ArrayType>(T1) && T1Quals)
3885 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3886 if (isa<ArrayType>(T2) && T2Quals)
3887 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3888
3889 // C++ [dcl.init.ref]p4:
3890 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3891 // reference-related to T2 and cv1 is the same cv-qualification
3892 // as, or greater cv-qualification than, cv2. For purposes of
3893 // overload resolution, cases for which cv1 is greater
3894 // cv-qualification than cv2 are identified as
3895 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003896 //
3897 // Note that we also require equivalence of Objective-C GC and address-space
3898 // qualifiers when performing these computations, so that e.g., an int in
3899 // address space 1 is not reference-compatible with an int in address
3900 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003901 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3902 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3903 T1Quals.removeObjCLifetime();
3904 T2Quals.removeObjCLifetime();
3905 ObjCLifetimeConversion = true;
3906 }
3907
Douglas Gregord517d552011-04-28 17:56:11 +00003908 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003909 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003910 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003911 return Ref_Compatible_With_Added_Qualification;
3912 else
3913 return Ref_Related;
3914}
3915
Douglas Gregor836a7e82010-08-11 02:15:33 +00003916/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003917/// with DeclType. Return true if something definite is found.
3918static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003919FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3920 QualType DeclType, SourceLocation DeclLoc,
3921 Expr *Init, QualType T2, bool AllowRvalues,
3922 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003923 assert(T2->isRecordType() && "Can only find conversions of record types.");
3924 CXXRecordDecl *T2RecordDecl
3925 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3926
3927 OverloadCandidateSet CandidateSet(DeclLoc);
3928 const UnresolvedSetImpl *Conversions
3929 = T2RecordDecl->getVisibleConversionFunctions();
3930 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3931 E = Conversions->end(); I != E; ++I) {
3932 NamedDecl *D = *I;
3933 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3934 if (isa<UsingShadowDecl>(D))
3935 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3936
3937 FunctionTemplateDecl *ConvTemplate
3938 = dyn_cast<FunctionTemplateDecl>(D);
3939 CXXConversionDecl *Conv;
3940 if (ConvTemplate)
3941 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3942 else
3943 Conv = cast<CXXConversionDecl>(D);
3944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003946 // explicit conversions, skip it.
3947 if (!AllowExplicit && Conv->isExplicit())
3948 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949
Douglas Gregor836a7e82010-08-11 02:15:33 +00003950 if (AllowRvalues) {
3951 bool DerivedToBase = false;
3952 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003953 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003954
3955 // If we are initializing an rvalue reference, don't permit conversion
3956 // functions that return lvalues.
3957 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3958 const ReferenceType *RefType
3959 = Conv->getConversionType()->getAs<LValueReferenceType>();
3960 if (RefType && !RefType->getPointeeType()->isFunctionType())
3961 continue;
3962 }
3963
Douglas Gregor836a7e82010-08-11 02:15:33 +00003964 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003965 S.CompareReferenceRelationship(
3966 DeclLoc,
3967 Conv->getConversionType().getNonReferenceType()
3968 .getUnqualifiedType(),
3969 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003970 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003971 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003972 continue;
3973 } else {
3974 // If the conversion function doesn't return a reference type,
3975 // it can't be considered for this conversion. An rvalue reference
3976 // is only acceptable if its referencee is a function type.
3977
3978 const ReferenceType *RefType =
3979 Conv->getConversionType()->getAs<ReferenceType>();
3980 if (!RefType ||
3981 (!RefType->isLValueReferenceType() &&
3982 !RefType->getPointeeType()->isFunctionType()))
3983 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Douglas Gregor836a7e82010-08-11 02:15:33 +00003986 if (ConvTemplate)
3987 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003988 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003989 else
3990 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003991 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003992 }
3993
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003994 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3995
Sebastian Redld92badf2010-06-30 18:13:39 +00003996 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003997 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003998 case OR_Success:
3999 // C++ [over.ics.ref]p1:
4000 //
4001 // [...] If the parameter binds directly to the result of
4002 // applying a conversion function to the argument
4003 // expression, the implicit conversion sequence is a
4004 // user-defined conversion sequence (13.3.3.1.2), with the
4005 // second standard conversion sequence either an identity
4006 // conversion or, if the conversion function returns an
4007 // entity of a type that is a derived class of the parameter
4008 // type, a derived-to-base Conversion.
4009 if (!Best->FinalConversion.DirectBinding)
4010 return false;
4011
Chandler Carruth30141632011-02-25 19:41:05 +00004012 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004013 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004014 ICS.setUserDefined();
4015 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4016 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004017 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004018 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004019 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004020 ICS.UserDefined.EllipsisConversion = false;
4021 assert(ICS.UserDefined.After.ReferenceBinding &&
4022 ICS.UserDefined.After.DirectBinding &&
4023 "Expected a direct reference binding!");
4024 return true;
4025
4026 case OR_Ambiguous:
4027 ICS.setAmbiguous();
4028 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4029 Cand != CandidateSet.end(); ++Cand)
4030 if (Cand->Viable)
4031 ICS.Ambiguous.addConversion(Cand->Function);
4032 return true;
4033
4034 case OR_No_Viable_Function:
4035 case OR_Deleted:
4036 // There was no suitable conversion, or we found a deleted
4037 // conversion; continue with other checks.
4038 return false;
4039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
David Blaikie8a40f702012-01-17 06:56:22 +00004041 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004042}
4043
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004044/// \brief Compute an implicit conversion sequence for reference
4045/// initialization.
4046static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004047TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004048 SourceLocation DeclLoc,
4049 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004050 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004051 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4052
4053 // Most paths end in a failed conversion.
4054 ImplicitConversionSequence ICS;
4055 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4056
4057 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4058 QualType T2 = Init->getType();
4059
4060 // If the initializer is the address of an overloaded function, try
4061 // to resolve the overloaded function. If all goes well, T2 is the
4062 // type of the resulting function.
4063 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4064 DeclAccessPair Found;
4065 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4066 false, Found))
4067 T2 = Fn->getType();
4068 }
4069
4070 // Compute some basic properties of the types and the initializer.
4071 bool isRValRef = DeclType->isRValueReferenceType();
4072 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004073 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004074 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004075 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004076 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004077 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004078 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004079
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004080
Sebastian Redld92badf2010-06-30 18:13:39 +00004081 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004082 // A reference to type "cv1 T1" is initialized by an expression
4083 // of type "cv2 T2" as follows:
4084
Sebastian Redld92badf2010-06-30 18:13:39 +00004085 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004086 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004087 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4088 // reference-compatible with "cv2 T2," or
4089 //
4090 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4091 if (InitCategory.isLValue() &&
4092 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004093 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004094 // When a parameter of reference type binds directly (8.5.3)
4095 // to an argument expression, the implicit conversion sequence
4096 // is the identity conversion, unless the argument expression
4097 // has a type that is a derived class of the parameter type,
4098 // in which case the implicit conversion sequence is a
4099 // derived-to-base Conversion (13.3.3.1).
4100 ICS.setStandard();
4101 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004102 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4103 : ObjCConversion? ICK_Compatible_Conversion
4104 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004105 ICS.Standard.Third = ICK_Identity;
4106 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4107 ICS.Standard.setToType(0, T2);
4108 ICS.Standard.setToType(1, T1);
4109 ICS.Standard.setToType(2, T1);
4110 ICS.Standard.ReferenceBinding = true;
4111 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004112 ICS.Standard.IsLvalueReference = !isRValRef;
4113 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4114 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004115 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004116 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004117 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004118
Sebastian Redld92badf2010-06-30 18:13:39 +00004119 // Nothing more to do: the inaccessibility/ambiguity check for
4120 // derived-to-base conversions is suppressed when we're
4121 // computing the implicit conversion sequence (C++
4122 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004123 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004124 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004125
Sebastian Redld92badf2010-06-30 18:13:39 +00004126 // -- has a class type (i.e., T2 is a class type), where T1 is
4127 // not reference-related to T2, and can be implicitly
4128 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4129 // is reference-compatible with "cv3 T3" 92) (this
4130 // conversion is selected by enumerating the applicable
4131 // conversion functions (13.3.1.6) and choosing the best
4132 // one through overload resolution (13.3)),
4133 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004135 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004136 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4137 Init, T2, /*AllowRvalues=*/false,
4138 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004139 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004140 }
4141 }
4142
Sebastian Redld92badf2010-06-30 18:13:39 +00004143 // -- Otherwise, the reference shall be an lvalue reference to a
4144 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004145 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004147 // We actually handle one oddity of C++ [over.ics.ref] at this
4148 // point, which is that, due to p2 (which short-circuits reference
4149 // binding by only attempting a simple conversion for non-direct
4150 // bindings) and p3's strange wording, we allow a const volatile
4151 // reference to bind to an rvalue. Hence the check for the presence
4152 // of "const" rather than checking for "const" being the only
4153 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004154 // This is also the point where rvalue references and lvalue inits no longer
4155 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00004156 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004157 return ICS;
4158
Douglas Gregorf143cd52011-01-24 16:14:37 +00004159 // -- If the initializer expression
4160 //
4161 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004162 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004163 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4164 (InitCategory.isXValue() ||
4165 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4166 (InitCategory.isLValue() && T2->isFunctionType()))) {
4167 ICS.setStandard();
4168 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004170 : ObjCConversion? ICK_Compatible_Conversion
4171 : ICK_Identity;
4172 ICS.Standard.Third = ICK_Identity;
4173 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4174 ICS.Standard.setToType(0, T2);
4175 ICS.Standard.setToType(1, T1);
4176 ICS.Standard.setToType(2, T1);
4177 ICS.Standard.ReferenceBinding = true;
4178 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4179 // binding unless we're binding to a class prvalue.
4180 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4181 // allow the use of rvalue references in C++98/03 for the benefit of
4182 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004184 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004185 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004186 ICS.Standard.IsLvalueReference = !isRValRef;
4187 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004189 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004190 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004191 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
Douglas Gregorf143cd52011-01-24 16:14:37 +00004195 // -- has a class type (i.e., T2 is a class type), where T1 is not
4196 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 // an xvalue, class prvalue, or function lvalue of type
4198 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004199 // "cv3 T3",
4200 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004202 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004204 // class subobject).
4205 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004207 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4208 Init, T2, /*AllowRvalues=*/true,
4209 AllowExplicit)) {
4210 // In the second case, if the reference is an rvalue reference
4211 // and the second standard conversion sequence of the
4212 // user-defined conversion sequence includes an lvalue-to-rvalue
4213 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004215 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4216 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4217
Douglas Gregor95273c32011-01-21 16:36:05 +00004218 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004221 // -- Otherwise, a temporary of type "cv1 T1" is created and
4222 // initialized from the initializer expression using the
4223 // rules for a non-reference copy initialization (8.5). The
4224 // reference is then bound to the temporary. If T1 is
4225 // reference-related to T2, cv1 must be the same
4226 // cv-qualification as, or greater cv-qualification than,
4227 // cv2; otherwise, the program is ill-formed.
4228 if (RefRelationship == Sema::Ref_Related) {
4229 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4230 // we would be reference-compatible or reference-compatible with
4231 // added qualification. But that wasn't the case, so the reference
4232 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004233 //
4234 // Note that we only want to check address spaces and cvr-qualifiers here.
4235 // ObjC GC and lifetime qualifiers aren't important.
4236 Qualifiers T1Quals = T1.getQualifiers();
4237 Qualifiers T2Quals = T2.getQualifiers();
4238 T1Quals.removeObjCGCAttr();
4239 T1Quals.removeObjCLifetime();
4240 T2Quals.removeObjCGCAttr();
4241 T2Quals.removeObjCLifetime();
4242 if (!T1Quals.compatiblyIncludes(T2Quals))
4243 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004244 }
4245
4246 // If at least one of the types is a class type, the types are not
4247 // related, and we aren't allowed any user conversions, the
4248 // reference binding fails. This case is important for breaking
4249 // recursion, since TryImplicitConversion below will attempt to
4250 // create a temporary through the use of a copy constructor.
4251 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4252 (T1->isRecordType() || T2->isRecordType()))
4253 return ICS;
4254
Douglas Gregorcba72b12011-01-21 05:18:22 +00004255 // If T1 is reference-related to T2 and the reference is an rvalue
4256 // reference, the initializer expression shall not be an lvalue.
4257 if (RefRelationship >= Sema::Ref_Related &&
4258 isRValRef && Init->Classify(S.Context).isLValue())
4259 return ICS;
4260
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262 // When a parameter of reference type is not bound directly to
4263 // an argument expression, the conversion sequence is the one
4264 // required to convert the argument expression to the
4265 // underlying type of the reference according to
4266 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4267 // to copy-initializing a temporary of the underlying type with
4268 // the argument expression. Any difference in top-level
4269 // cv-qualification is subsumed by the initialization itself
4270 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004271 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4272 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004273 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004274 /*CStyle=*/false,
4275 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004276
4277 // Of course, that's still a reference binding.
4278 if (ICS.isStandard()) {
4279 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004280 ICS.Standard.IsLvalueReference = !isRValRef;
4281 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4282 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004283 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004284 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004285 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004286 // Don't allow rvalue references to bind to lvalues.
4287 if (DeclType->isRValueReferenceType()) {
4288 if (const ReferenceType *RefType
4289 = ICS.UserDefined.ConversionFunction->getResultType()
4290 ->getAs<LValueReferenceType>()) {
4291 if (!RefType->getPointeeType()->isFunctionType()) {
4292 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4293 DeclType);
4294 return ICS;
4295 }
4296 }
4297 }
4298
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004299 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004300 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4301 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4302 ICS.UserDefined.After.BindsToRvalue = true;
4303 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4304 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004305 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004306
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004307 return ICS;
4308}
4309
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004310static ImplicitConversionSequence
4311TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4312 bool SuppressUserConversions,
4313 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004314 bool AllowObjCWritebackConversion,
4315 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004316
4317/// TryListConversion - Try to copy-initialize a value of type ToType from the
4318/// initializer list From.
4319static ImplicitConversionSequence
4320TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4321 bool SuppressUserConversions,
4322 bool InOverloadResolution,
4323 bool AllowObjCWritebackConversion) {
4324 // C++11 [over.ics.list]p1:
4325 // When an argument is an initializer list, it is not an expression and
4326 // special rules apply for converting it to a parameter type.
4327
4328 ImplicitConversionSequence Result;
4329 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004330 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004331
Sebastian Redl09edce02012-01-23 22:09:39 +00004332 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004333 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004334 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004335 return Result;
4336
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004337 // C++11 [over.ics.list]p2:
4338 // If the parameter type is std::initializer_list<X> or "array of X" and
4339 // all the elements can be implicitly converted to X, the implicit
4340 // conversion sequence is the worst conversion necessary to convert an
4341 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004342 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004343 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004344 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004345 X = S.Context.getBaseElementType(ToType);
4346 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004347 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004348 if (!X.isNull()) {
4349 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4350 Expr *Init = From->getInit(i);
4351 ImplicitConversionSequence ICS =
4352 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4353 InOverloadResolution,
4354 AllowObjCWritebackConversion);
4355 // If a single element isn't convertible, fail.
4356 if (ICS.isBad()) {
4357 Result = ICS;
4358 break;
4359 }
4360 // Otherwise, look for the worst conversion.
4361 if (Result.isBad() ||
4362 CompareImplicitConversionSequences(S, ICS, Result) ==
4363 ImplicitConversionSequence::Worse)
4364 Result = ICS;
4365 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004366
4367 // For an empty list, we won't have computed any conversion sequence.
4368 // Introduce the identity conversion sequence.
4369 if (From->getNumInits() == 0) {
4370 Result.setStandard();
4371 Result.Standard.setAsIdentityConversion();
4372 Result.Standard.setFromType(ToType);
4373 Result.Standard.setAllToTypes(ToType);
4374 }
4375
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004376 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004377 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004378 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004379 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004380
4381 // C++11 [over.ics.list]p3:
4382 // Otherwise, if the parameter is a non-aggregate class X and overload
4383 // resolution chooses a single best constructor [...] the implicit
4384 // conversion sequence is a user-defined conversion sequence. If multiple
4385 // constructors are viable but none is better than the others, the
4386 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004387 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4388 // This function can deal with initializer lists.
4389 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4390 /*AllowExplicit=*/false,
4391 InOverloadResolution, /*CStyle=*/false,
4392 AllowObjCWritebackConversion);
4393 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004394 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004395 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004396
4397 // C++11 [over.ics.list]p4:
4398 // Otherwise, if the parameter has an aggregate type which can be
4399 // initialized from the initializer list [...] the implicit conversion
4400 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004401 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004402 // Type is an aggregate, argument is an init list. At this point it comes
4403 // down to checking whether the initialization works.
4404 // FIXME: Find out whether this parameter is consumed or not.
4405 InitializedEntity Entity =
4406 InitializedEntity::InitializeParameter(S.Context, ToType,
4407 /*Consumed=*/false);
4408 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4409 Result.setUserDefined();
4410 Result.UserDefined.Before.setAsIdentityConversion();
4411 // Initializer lists don't have a type.
4412 Result.UserDefined.Before.setFromType(QualType());
4413 Result.UserDefined.Before.setAllToTypes(QualType());
4414
4415 Result.UserDefined.After.setAsIdentityConversion();
4416 Result.UserDefined.After.setFromType(ToType);
4417 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004418 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004419 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004420 return Result;
4421 }
4422
4423 // C++11 [over.ics.list]p5:
4424 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004425 if (ToType->isReferenceType()) {
4426 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4427 // mention initializer lists in any way. So we go by what list-
4428 // initialization would do and try to extrapolate from that.
4429
4430 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4431
4432 // If the initializer list has a single element that is reference-related
4433 // to the parameter type, we initialize the reference from that.
4434 if (From->getNumInits() == 1) {
4435 Expr *Init = From->getInit(0);
4436
4437 QualType T2 = Init->getType();
4438
4439 // If the initializer is the address of an overloaded function, try
4440 // to resolve the overloaded function. If all goes well, T2 is the
4441 // type of the resulting function.
4442 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4443 DeclAccessPair Found;
4444 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4445 Init, ToType, false, Found))
4446 T2 = Fn->getType();
4447 }
4448
4449 // Compute some basic properties of the types and the initializer.
4450 bool dummy1 = false;
4451 bool dummy2 = false;
4452 bool dummy3 = false;
4453 Sema::ReferenceCompareResult RefRelationship
4454 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4455 dummy2, dummy3);
4456
4457 if (RefRelationship >= Sema::Ref_Related)
4458 return TryReferenceInit(S, Init, ToType,
4459 /*FIXME:*/From->getLocStart(),
4460 SuppressUserConversions,
4461 /*AllowExplicit=*/false);
4462 }
4463
4464 // Otherwise, we bind the reference to a temporary created from the
4465 // initializer list.
4466 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4467 InOverloadResolution,
4468 AllowObjCWritebackConversion);
4469 if (Result.isFailure())
4470 return Result;
4471 assert(!Result.isEllipsis() &&
4472 "Sub-initialization cannot result in ellipsis conversion.");
4473
4474 // Can we even bind to a temporary?
4475 if (ToType->isRValueReferenceType() ||
4476 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4477 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4478 Result.UserDefined.After;
4479 SCS.ReferenceBinding = true;
4480 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4481 SCS.BindsToRvalue = true;
4482 SCS.BindsToFunctionLvalue = false;
4483 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4484 SCS.ObjCLifetimeConversionBinding = false;
4485 } else
4486 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4487 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004488 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004489 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004490
4491 // C++11 [over.ics.list]p6:
4492 // Otherwise, if the parameter type is not a class:
4493 if (!ToType->isRecordType()) {
4494 // - if the initializer list has one element, the implicit conversion
4495 // sequence is the one required to convert the element to the
4496 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004497 unsigned NumInits = From->getNumInits();
4498 if (NumInits == 1)
4499 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4500 SuppressUserConversions,
4501 InOverloadResolution,
4502 AllowObjCWritebackConversion);
4503 // - if the initializer list has no elements, the implicit conversion
4504 // sequence is the identity conversion.
4505 else if (NumInits == 0) {
4506 Result.setStandard();
4507 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004508 Result.Standard.setFromType(ToType);
4509 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004510 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004511 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004512 return Result;
4513 }
4514
4515 // C++11 [over.ics.list]p7:
4516 // In all cases other than those enumerated above, no conversion is possible
4517 return Result;
4518}
4519
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004520/// TryCopyInitialization - Try to copy-initialize a value of type
4521/// ToType from the expression From. Return the implicit conversion
4522/// sequence required to pass this argument, which may be a bad
4523/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004524/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004525/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004526static ImplicitConversionSequence
4527TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004529 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004530 bool AllowObjCWritebackConversion,
4531 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004532 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4533 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4534 InOverloadResolution,AllowObjCWritebackConversion);
4535
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004536 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004537 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004538 /*FIXME:*/From->getLocStart(),
4539 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004540 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004541
John McCall5c32be02010-08-24 20:38:10 +00004542 return TryImplicitConversion(S, From, ToType,
4543 SuppressUserConversions,
4544 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004545 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004546 /*CStyle=*/false,
4547 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004548}
4549
Anna Zaks1b068122011-07-28 19:46:48 +00004550static bool TryCopyInitialization(const CanQualType FromQTy,
4551 const CanQualType ToQTy,
4552 Sema &S,
4553 SourceLocation Loc,
4554 ExprValueKind FromVK) {
4555 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4556 ImplicitConversionSequence ICS =
4557 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4558
4559 return !ICS.isBad();
4560}
4561
Douglas Gregor436424c2008-11-18 23:14:02 +00004562/// TryObjectArgumentInitialization - Try to initialize the object
4563/// parameter of the given member function (@c Method) from the
4564/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004565static ImplicitConversionSequence
4566TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004567 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004568 CXXMethodDecl *Method,
4569 CXXRecordDecl *ActingContext) {
4570 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004571 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4572 // const volatile object.
4573 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4574 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004575 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004576
4577 // Set up the conversion sequence as a "bad" conversion, to allow us
4578 // to exit early.
4579 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004580
4581 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004582 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004583 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004584 FromType = PT->getPointeeType();
4585
Douglas Gregor02824322011-01-26 19:30:28 +00004586 // When we had a pointer, it's implicitly dereferenced, so we
4587 // better have an lvalue.
4588 assert(FromClassification.isLValue());
4589 }
4590
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004591 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004592
Douglas Gregor02824322011-01-26 19:30:28 +00004593 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004595 // parameter is
4596 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004597 // - "lvalue reference to cv X" for functions declared without a
4598 // ref-qualifier or with the & ref-qualifier
4599 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004600 // ref-qualifier
4601 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004603 // cv-qualification on the member function declaration.
4604 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004606 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004607 // (C++ [over.match.funcs]p5). We perform a simplified version of
4608 // reference binding here, that allows class rvalues to bind to
4609 // non-constant references.
4610
Douglas Gregor02824322011-01-26 19:30:28 +00004611 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004612 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004614 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004615 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004616 ICS.setBad(BadConversionSequence::bad_qualifiers,
4617 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004618 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004619 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004620
4621 // Check that we have either the same type or a derived type. It
4622 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004623 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004624 ImplicitConversionKind SecondKind;
4625 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4626 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004627 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004628 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004629 else {
John McCall65eb8792010-02-25 01:37:24 +00004630 ICS.setBad(BadConversionSequence::unrelated_class,
4631 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004632 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004633 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004634
Douglas Gregor02824322011-01-26 19:30:28 +00004635 // Check the ref-qualifier.
4636 switch (Method->getRefQualifier()) {
4637 case RQ_None:
4638 // Do nothing; we don't care about lvalueness or rvalueness.
4639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor02824322011-01-26 19:30:28 +00004641 case RQ_LValue:
4642 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4643 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004644 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004645 ImplicitParamType);
4646 return ICS;
4647 }
4648 break;
4649
4650 case RQ_RValue:
4651 if (!FromClassification.isRValue()) {
4652 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004654 ImplicitParamType);
4655 return ICS;
4656 }
4657 break;
4658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659
Douglas Gregor436424c2008-11-18 23:14:02 +00004660 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004661 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004662 ICS.Standard.setAsIdentityConversion();
4663 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004664 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004665 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004666 ICS.Standard.ReferenceBinding = true;
4667 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004669 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004670 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4671 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4672 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004673 return ICS;
4674}
4675
4676/// PerformObjectArgumentInitialization - Perform initialization of
4677/// the implicit object parameter for the given Method with the given
4678/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004679ExprResult
4680Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004682 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004683 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004684 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004685 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004686 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004687
Douglas Gregor02824322011-01-26 19:30:28 +00004688 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004689 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004690 FromRecordType = PT->getPointeeType();
4691 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004692 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004693 } else {
4694 FromRecordType = From->getType();
4695 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004696 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004697 }
4698
John McCall6e9f8f62009-12-03 04:06:58 +00004699 // Note that we always use the true parent context when performing
4700 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004701 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004702 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4703 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004704 if (ICS.isBad()) {
4705 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4706 Qualifiers FromQs = FromRecordType.getQualifiers();
4707 Qualifiers ToQs = DestType.getQualifiers();
4708 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4709 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004710 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004711 diag::err_member_function_call_bad_cvr)
4712 << Method->getDeclName() << FromRecordType << (CVR - 1)
4713 << From->getSourceRange();
4714 Diag(Method->getLocation(), diag::note_previous_decl)
4715 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004716 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004717 }
4718 }
4719
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004720 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004721 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004722 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004723 }
Mike Stump11289f42009-09-09 15:08:12 +00004724
John Wiegley01296292011-04-08 18:41:53 +00004725 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4726 ExprResult FromRes =
4727 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4728 if (FromRes.isInvalid())
4729 return ExprError();
4730 From = FromRes.take();
4731 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004732
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004733 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004734 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004735 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004736 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004737}
4738
Douglas Gregor5fb53972009-01-14 15:45:31 +00004739/// TryContextuallyConvertToBool - Attempt to contextually convert the
4740/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004741static ImplicitConversionSequence
4742TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004743 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004744 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004745 // FIXME: Are these flags correct?
4746 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004747 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004748 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004749 /*CStyle=*/false,
4750 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004751}
4752
4753/// PerformContextuallyConvertToBool - Perform a contextual conversion
4754/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004755ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004756 if (checkPlaceholderForOverload(*this, From))
4757 return ExprError();
4758
John McCall5c32be02010-08-24 20:38:10 +00004759 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004760 if (!ICS.isBad())
4761 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Fariborz Jahanian76197412009-11-18 18:26:29 +00004763 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004764 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004765 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004766 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004767 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004768}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Richard Smithf8379a02012-01-18 23:55:52 +00004770/// Check that the specified conversion is permitted in a converted constant
4771/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4772/// is acceptable.
4773static bool CheckConvertedConstantConversions(Sema &S,
4774 StandardConversionSequence &SCS) {
4775 // Since we know that the target type is an integral or unscoped enumeration
4776 // type, most conversion kinds are impossible. All possible First and Third
4777 // conversions are fine.
4778 switch (SCS.Second) {
4779 case ICK_Identity:
4780 case ICK_Integral_Promotion:
4781 case ICK_Integral_Conversion:
4782 return true;
4783
4784 case ICK_Boolean_Conversion:
4785 // Conversion from an integral or unscoped enumeration type to bool is
4786 // classified as ICK_Boolean_Conversion, but it's also an integral
4787 // conversion, so it's permitted in a converted constant expression.
4788 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4789 SCS.getToType(2)->isBooleanType();
4790
4791 case ICK_Floating_Integral:
4792 case ICK_Complex_Real:
4793 return false;
4794
4795 case ICK_Lvalue_To_Rvalue:
4796 case ICK_Array_To_Pointer:
4797 case ICK_Function_To_Pointer:
4798 case ICK_NoReturn_Adjustment:
4799 case ICK_Qualification:
4800 case ICK_Compatible_Conversion:
4801 case ICK_Vector_Conversion:
4802 case ICK_Vector_Splat:
4803 case ICK_Derived_To_Base:
4804 case ICK_Pointer_Conversion:
4805 case ICK_Pointer_Member:
4806 case ICK_Block_Pointer_Conversion:
4807 case ICK_Writeback_Conversion:
4808 case ICK_Floating_Promotion:
4809 case ICK_Complex_Promotion:
4810 case ICK_Complex_Conversion:
4811 case ICK_Floating_Conversion:
4812 case ICK_TransparentUnionConversion:
4813 llvm_unreachable("unexpected second conversion kind");
4814
4815 case ICK_Num_Conversion_Kinds:
4816 break;
4817 }
4818
4819 llvm_unreachable("unknown conversion kind");
4820}
4821
4822/// CheckConvertedConstantExpression - Check that the expression From is a
4823/// converted constant expression of type T, perform the conversion and produce
4824/// the converted expression, per C++11 [expr.const]p3.
4825ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4826 llvm::APSInt &Value,
4827 CCEKind CCE) {
4828 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4829 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4830
4831 if (checkPlaceholderForOverload(*this, From))
4832 return ExprError();
4833
4834 // C++11 [expr.const]p3 with proposed wording fixes:
4835 // A converted constant expression of type T is a core constant expression,
4836 // implicitly converted to a prvalue of type T, where the converted
4837 // expression is a literal constant expression and the implicit conversion
4838 // sequence contains only user-defined conversions, lvalue-to-rvalue
4839 // conversions, integral promotions, and integral conversions other than
4840 // narrowing conversions.
4841 ImplicitConversionSequence ICS =
4842 TryImplicitConversion(From, T,
4843 /*SuppressUserConversions=*/false,
4844 /*AllowExplicit=*/false,
4845 /*InOverloadResolution=*/false,
4846 /*CStyle=*/false,
4847 /*AllowObjcWritebackConversion=*/false);
4848 StandardConversionSequence *SCS = 0;
4849 switch (ICS.getKind()) {
4850 case ImplicitConversionSequence::StandardConversion:
4851 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004852 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004853 diag::err_typecheck_converted_constant_expression_disallowed)
4854 << From->getType() << From->getSourceRange() << T;
4855 SCS = &ICS.Standard;
4856 break;
4857 case ImplicitConversionSequence::UserDefinedConversion:
4858 // We are converting from class type to an integral or enumeration type, so
4859 // the Before sequence must be trivial.
4860 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004861 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004862 diag::err_typecheck_converted_constant_expression_disallowed)
4863 << From->getType() << From->getSourceRange() << T;
4864 SCS = &ICS.UserDefined.After;
4865 break;
4866 case ImplicitConversionSequence::AmbiguousConversion:
4867 case ImplicitConversionSequence::BadConversion:
4868 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004869 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004870 diag::err_typecheck_converted_constant_expression)
4871 << From->getType() << From->getSourceRange() << T;
4872 return ExprError();
4873
4874 case ImplicitConversionSequence::EllipsisConversion:
4875 llvm_unreachable("ellipsis conversion in converted constant expression");
4876 }
4877
4878 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4879 if (Result.isInvalid())
4880 return Result;
4881
4882 // Check for a narrowing implicit conversion.
4883 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004884 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004885 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4886 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004887 case NK_Variable_Narrowing:
4888 // Implicit conversion to a narrower type, and the value is not a constant
4889 // expression. We'll diagnose this in a moment.
4890 case NK_Not_Narrowing:
4891 break;
4892
4893 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004894 Diag(From->getLocStart(),
4895 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4896 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004897 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004898 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004899 break;
4900
4901 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004902 Diag(From->getLocStart(),
4903 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4904 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004905 << CCE << /*Constant*/0 << From->getType() << T;
4906 break;
4907 }
4908
4909 // Check the expression is a constant expression.
4910 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4911 Expr::EvalResult Eval;
4912 Eval.Diag = &Notes;
4913
4914 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4915 // The expression can't be folded, so we can't keep it at this position in
4916 // the AST.
4917 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004918 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004919 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004920
4921 if (Notes.empty()) {
4922 // It's a constant expression.
4923 return Result;
4924 }
Richard Smithf8379a02012-01-18 23:55:52 +00004925 }
4926
4927 // It's not a constant expression. Produce an appropriate diagnostic.
4928 if (Notes.size() == 1 &&
4929 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4930 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4931 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004932 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004933 << CCE << From->getSourceRange();
4934 for (unsigned I = 0; I < Notes.size(); ++I)
4935 Diag(Notes[I].first, Notes[I].second);
4936 }
Richard Smith911e1422012-01-30 22:27:01 +00004937 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004938}
4939
John McCallfec112d2011-09-09 06:11:02 +00004940/// dropPointerConversions - If the given standard conversion sequence
4941/// involves any pointer conversions, remove them. This may change
4942/// the result type of the conversion sequence.
4943static void dropPointerConversion(StandardConversionSequence &SCS) {
4944 if (SCS.Second == ICK_Pointer_Conversion) {
4945 SCS.Second = ICK_Identity;
4946 SCS.Third = ICK_Identity;
4947 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4948 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004949}
John McCall5c32be02010-08-24 20:38:10 +00004950
John McCallfec112d2011-09-09 06:11:02 +00004951/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4952/// convert the expression From to an Objective-C pointer type.
4953static ImplicitConversionSequence
4954TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4955 // Do an implicit conversion to 'id'.
4956 QualType Ty = S.Context.getObjCIdType();
4957 ImplicitConversionSequence ICS
4958 = TryImplicitConversion(S, From, Ty,
4959 // FIXME: Are these flags correct?
4960 /*SuppressUserConversions=*/false,
4961 /*AllowExplicit=*/true,
4962 /*InOverloadResolution=*/false,
4963 /*CStyle=*/false,
4964 /*AllowObjCWritebackConversion=*/false);
4965
4966 // Strip off any final conversions to 'id'.
4967 switch (ICS.getKind()) {
4968 case ImplicitConversionSequence::BadConversion:
4969 case ImplicitConversionSequence::AmbiguousConversion:
4970 case ImplicitConversionSequence::EllipsisConversion:
4971 break;
4972
4973 case ImplicitConversionSequence::UserDefinedConversion:
4974 dropPointerConversion(ICS.UserDefined.After);
4975 break;
4976
4977 case ImplicitConversionSequence::StandardConversion:
4978 dropPointerConversion(ICS.Standard);
4979 break;
4980 }
4981
4982 return ICS;
4983}
4984
4985/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4986/// conversion of the expression From to an Objective-C pointer type.
4987ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004988 if (checkPlaceholderForOverload(*this, From))
4989 return ExprError();
4990
John McCall8b07ec22010-05-15 11:32:37 +00004991 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004992 ImplicitConversionSequence ICS =
4993 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004994 if (!ICS.isBad())
4995 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004996 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004997}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004998
Richard Smith8dd34252012-02-04 07:07:42 +00004999/// Determine whether the provided type is an integral type, or an enumeration
5000/// type of a permitted flavor.
5001static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5002 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5003 : T->isIntegralOrUnscopedEnumerationType();
5004}
5005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005007/// enumeration type.
5008///
5009/// This routine will attempt to convert an expression of class type to an
5010/// integral or enumeration type, if that class type only has a single
5011/// conversion to an integral or enumeration type.
5012///
Douglas Gregor4799d032010-06-30 00:20:43 +00005013/// \param Loc The source location of the construct that requires the
5014/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005015///
Douglas Gregor4799d032010-06-30 00:20:43 +00005016/// \param FromE The expression we're converting from.
5017///
5018/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5019/// have integral or enumeration type.
5020///
5021/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5022/// incomplete class type.
5023///
5024/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5025/// explicit conversion function (because no implicit conversion functions
5026/// were available). This is a recovery mode.
5027///
5028/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5029/// showing which conversion was picked.
5030///
5031/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5032/// conversion function that could convert to integral or enumeration type.
5033///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00005035/// usable conversion function.
5036///
5037/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5038/// function, which may be an extension in this case.
5039///
Richard Smith8dd34252012-02-04 07:07:42 +00005040/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5041/// enumerations should be considered.
5042///
Douglas Gregor4799d032010-06-30 00:20:43 +00005043/// \returns The expression, converted to an integral or enumeration type if
5044/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045ExprResult
John McCallb268a282010-08-23 23:25:46 +00005046Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005047 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005048 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005049 // We can't perform any more checking for type-dependent expressions.
5050 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005051 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Eli Friedman1da70392012-01-26 00:26:18 +00005053 // Process placeholders immediately.
5054 if (From->hasPlaceholderType()) {
5055 ExprResult result = CheckPlaceholderExpr(From);
5056 if (result.isInvalid()) return result;
5057 From = result.take();
5058 }
5059
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005060 // If the expression already has integral or enumeration type, we're golden.
5061 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005062 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005063 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005064
5065 // FIXME: Check for missing '()' if T is a function type?
5066
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067 // 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 +00005068 // expression of integral or enumeration type.
5069 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005070 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005071 if (!Diagnoser.Suppress)
5072 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005073 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005076 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005077 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005078 ICEConvertDiagnoser &Diagnoser;
5079 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005080
Douglas Gregore2b37442012-05-04 22:38:52 +00005081 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5082 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005083
5084 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005085 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005086 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005087 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005088
5089 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005090 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005092 // Look for a conversion to an integral or enumeration type.
5093 UnresolvedSet<4> ViableConversions;
5094 UnresolvedSet<4> ExplicitConversions;
5095 const UnresolvedSetImpl *Conversions
5096 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005098 bool HadMultipleCandidates = (Conversions->size() > 1);
5099
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005100 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101 E = Conversions->end();
5102 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005103 ++I) {
5104 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005105 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5106 if (isIntegralOrEnumerationType(
5107 Conversion->getConversionType().getNonReferenceType(),
5108 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005109 if (Conversion->isExplicit())
5110 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5111 else
5112 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5113 }
Richard Smith8dd34252012-02-04 07:07:42 +00005114 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005117 switch (ViableConversions.size()) {
5118 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005119 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005120 DeclAccessPair Found = ExplicitConversions[0];
5121 CXXConversionDecl *Conversion
5122 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005124 // The user probably meant to invoke the given explicit
5125 // conversion; use it.
5126 QualType ConvTy
5127 = Conversion->getConversionType().getNonReferenceType();
5128 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005129 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregore2b37442012-05-04 22:38:52 +00005131 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132 << FixItHint::CreateInsertion(From->getLocStart(),
5133 "static_cast<" + TypeStr + ">(")
5134 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5135 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005136 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137
5138 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005139 // explicit conversion function.
5140 if (isSFINAEContext())
5141 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005143 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005144 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5145 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005146 if (Result.isInvalid())
5147 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005148 // Record usage of conversion in an implicit cast.
5149 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5150 CK_UserDefinedConversion,
5151 Result.get(), 0,
5152 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005155 // We'll complain below about a non-integral condition type.
5156 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005158 case 1: {
5159 // Apply this conversion.
5160 DeclAccessPair Found = ViableConversions[0];
5161 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162
Douglas Gregor4799d032010-06-30 00:20:43 +00005163 CXXConversionDecl *Conversion
5164 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5165 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005167 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005168 if (isSFINAEContext())
5169 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170
Douglas Gregore2b37442012-05-04 22:38:52 +00005171 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5172 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005175 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5176 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005177 if (Result.isInvalid())
5178 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005179 // Record usage of conversion in an implicit cast.
5180 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5181 CK_UserDefinedConversion,
5182 Result.get(), 0,
5183 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005184 break;
5185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005187 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005188 if (Diagnoser.Suppress)
5189 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005190
Douglas Gregore2b37442012-05-04 22:38:52 +00005191 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005192 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5193 CXXConversionDecl *Conv
5194 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5195 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005196 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005197 }
John McCallb268a282010-08-23 23:25:46 +00005198 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Richard Smithf4c51d92012-02-04 09:53:13 +00005201 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005202 !Diagnoser.Suppress) {
5203 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5204 << From->getSourceRange();
5205 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005206
Eli Friedman1da70392012-01-26 00:26:18 +00005207 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005208}
5209
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005210/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005211/// candidate functions, using the given function call arguments. If
5212/// @p SuppressUserConversions, then don't allow user-defined
5213/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005214///
5215/// \para PartialOverloading true if we are performing "partial" overloading
5216/// based on an incomplete set of function arguments. This feature is used by
5217/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005218void
5219Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005220 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005221 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005222 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005223 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005224 bool PartialOverloading,
5225 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005226 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005227 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005228 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005229 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005230 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005231
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005233 if (!isa<CXXConstructorDecl>(Method)) {
5234 // If we get here, it's because we're calling a member function
5235 // that is named without a member access expression (e.g.,
5236 // "this->f") that was either written explicitly or created
5237 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005238 // function, e.g., X::f(). We use an empty type for the implied
5239 // object argument (C++ [over.call.func]p3), and the acting context
5240 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005241 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005243 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005244 return;
5245 }
5246 // We treat a constructor like a non-member function, since its object
5247 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005248 }
5249
Douglas Gregorff7028a2009-11-13 23:59:09 +00005250 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005251 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005252
Douglas Gregor27381f32009-11-23 12:27:39 +00005253 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005254 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005255
Douglas Gregorffe14e32009-11-14 01:20:54 +00005256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5257 // C++ [class.copy]p3:
5258 // A member function template is never instantiated to perform the copy
5259 // of a class object to an object of its class type.
5260 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005261 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005262 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005263 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5264 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005265 return;
5266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005268 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005269 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005270 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005271 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005272 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005273 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005274 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005275 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005276
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005277 unsigned NumArgsInProto = Proto->getNumArgs();
5278
5279 // (C++ 13.3.2p2): A candidate function having fewer than m
5280 // parameters is viable only if it has an ellipsis in its parameter
5281 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005282 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005283 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005284 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005285 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005286 return;
5287 }
5288
5289 // (C++ 13.3.2p2): A candidate function having more than m parameters
5290 // is viable only if the (m+1)st parameter has a default argument
5291 // (8.3.6). For the purposes of overload resolution, the
5292 // parameter list is truncated on the right, so that there are
5293 // exactly m parameters.
5294 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005295 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005296 // Not enough arguments.
5297 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005298 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005299 return;
5300 }
5301
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005302 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005303 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005304 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5305 if (CheckCUDATarget(Caller, Function)) {
5306 Candidate.Viable = false;
5307 Candidate.FailureKind = ovl_fail_bad_target;
5308 return;
5309 }
5310
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005311 // Determine the implicit conversion sequences for each of the
5312 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005313 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005314 if (ArgIdx < NumArgsInProto) {
5315 // (C++ 13.3.2p3): for F to be a viable function, there shall
5316 // exist for each argument an implicit conversion sequence
5317 // (13.3.3.1) that converts that argument to the corresponding
5318 // parameter of F.
5319 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005320 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005321 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005323 /*InOverloadResolution=*/true,
5324 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005325 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005326 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005327 if (Candidate.Conversions[ArgIdx].isBad()) {
5328 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005329 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005330 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005331 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005332 } else {
5333 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5334 // argument for which there is no corresponding parameter is
5335 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005336 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005337 }
5338 }
5339}
5340
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005341/// \brief Add all of the function declarations in the given function set to
5342/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005343void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005344 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005345 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005346 bool SuppressUserConversions,
5347 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005348 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005349 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5350 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005351 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005352 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005353 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005354 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005355 Args.slice(1), CandidateSet,
5356 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005357 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005358 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005359 SuppressUserConversions);
5360 } else {
John McCalla0296f72010-03-19 07:35:19 +00005361 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005362 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5363 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005364 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005365 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005366 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005368 Args[0]->Classify(Context), Args.slice(1),
5369 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005370 else
John McCalla0296f72010-03-19 07:35:19 +00005371 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005372 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005373 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005374 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005375 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005376}
5377
John McCallf0f1cf02009-11-17 07:50:12 +00005378/// AddMethodCandidate - Adds a named decl (which is some kind of
5379/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005380void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005381 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005382 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005383 Expr **Args, unsigned NumArgs,
5384 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005385 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005386 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005387 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005388
5389 if (isa<UsingShadowDecl>(Decl))
5390 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
John McCallf0f1cf02009-11-17 07:50:12 +00005392 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5393 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5394 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005395 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5396 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005397 ObjectType, ObjectClassification,
5398 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005399 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005400 } else {
John McCalla0296f72010-03-19 07:35:19 +00005401 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005402 ObjectType, ObjectClassification,
5403 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005404 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005405 }
5406}
5407
Douglas Gregor436424c2008-11-18 23:14:02 +00005408/// AddMethodCandidate - Adds the given C++ member function to the set
5409/// of candidate functions, using the given function call arguments
5410/// and the object argument (@c Object). For example, in a call
5411/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5412/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5413/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005414/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005415void
John McCalla0296f72010-03-19 07:35:19 +00005416Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005417 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005418 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005419 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005420 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005421 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005422 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005423 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005424 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005425 assert(!isa<CXXConstructorDecl>(Method) &&
5426 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005427
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005428 if (!CandidateSet.isNewCandidate(Method))
5429 return;
5430
Douglas Gregor27381f32009-11-23 12:27:39 +00005431 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005432 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005433
Douglas Gregor436424c2008-11-18 23:14:02 +00005434 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005435 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005436 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005437 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005438 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005439 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005440 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005441
5442 unsigned NumArgsInProto = Proto->getNumArgs();
5443
5444 // (C++ 13.3.2p2): A candidate function having fewer than m
5445 // parameters is viable only if it has an ellipsis in its parameter
5446 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005447 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005448 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005449 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005450 return;
5451 }
5452
5453 // (C++ 13.3.2p2): A candidate function having more than m parameters
5454 // is viable only if the (m+1)st parameter has a default argument
5455 // (8.3.6). For the purposes of overload resolution, the
5456 // parameter list is truncated on the right, so that there are
5457 // exactly m parameters.
5458 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005459 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005460 // Not enough arguments.
5461 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005462 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005463 return;
5464 }
5465
5466 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005467
John McCall6e9f8f62009-12-03 04:06:58 +00005468 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005469 // The implicit object argument is ignored.
5470 Candidate.IgnoreObjectArgument = true;
5471 else {
5472 // Determine the implicit conversion sequence for the object
5473 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005474 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005475 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5476 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005477 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005478 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005479 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005480 return;
5481 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005482 }
5483
5484 // Determine the implicit conversion sequences for each of the
5485 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005486 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005487 if (ArgIdx < NumArgsInProto) {
5488 // (C++ 13.3.2p3): for F to be a viable function, there shall
5489 // exist for each argument an implicit conversion sequence
5490 // (13.3.3.1) that converts that argument to the corresponding
5491 // parameter of F.
5492 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005493 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005494 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005495 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005496 /*InOverloadResolution=*/true,
5497 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005498 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005499 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005500 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005501 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005502 break;
5503 }
5504 } else {
5505 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5506 // argument for which there is no corresponding parameter is
5507 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005508 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005509 }
5510 }
5511}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005512
Douglas Gregor97628d62009-08-21 00:16:32 +00005513/// \brief Add a C++ member function template as a candidate to the candidate
5514/// set, using template argument deduction to produce an appropriate member
5515/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005516void
Douglas Gregor97628d62009-08-21 00:16:32 +00005517Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005518 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005519 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005520 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005521 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005522 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005523 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005524 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005525 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005526 if (!CandidateSet.isNewCandidate(MethodTmpl))
5527 return;
5528
Douglas Gregor97628d62009-08-21 00:16:32 +00005529 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005530 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005531 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005532 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005533 // candidate functions in the usual way.113) A given name can refer to one
5534 // or more function templates and also to a set of overloaded non-template
5535 // functions. In such a case, the candidate functions generated from each
5536 // function template are combined with the set of non-template candidate
5537 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005538 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005539 FunctionDecl *Specialization = 0;
5540 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005541 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5542 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005543 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005544 Candidate.FoundDecl = FoundDecl;
5545 Candidate.Function = MethodTmpl->getTemplatedDecl();
5546 Candidate.Viable = false;
5547 Candidate.FailureKind = ovl_fail_bad_deduction;
5548 Candidate.IsSurrogate = false;
5549 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005550 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005552 Info);
5553 return;
5554 }
Mike Stump11289f42009-09-09 15:08:12 +00005555
Douglas Gregor97628d62009-08-21 00:16:32 +00005556 // Add the function template specialization produced by template argument
5557 // deduction as a candidate.
5558 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005559 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005560 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005561 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005562 ActingContext, ObjectType, ObjectClassification, Args,
5563 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005564}
5565
Douglas Gregor05155d82009-08-21 23:19:43 +00005566/// \brief Add a C++ function template specialization as a candidate
5567/// in the candidate set, using template argument deduction to produce
5568/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005569void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005570Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005571 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005572 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005573 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005574 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005575 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005576 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5577 return;
5578
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005579 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005580 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005581 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005582 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005583 // candidate functions in the usual way.113) A given name can refer to one
5584 // or more function templates and also to a set of overloaded non-template
5585 // functions. In such a case, the candidate functions generated from each
5586 // function template are combined with the set of non-template candidate
5587 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005588 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005589 FunctionDecl *Specialization = 0;
5590 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005591 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5592 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005593 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005594 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005595 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5596 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005597 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005598 Candidate.IsSurrogate = false;
5599 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005600 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005602 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005603 return;
5604 }
Mike Stump11289f42009-09-09 15:08:12 +00005605
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005606 // Add the function template specialization produced by template argument
5607 // deduction as a candidate.
5608 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005609 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005610 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005611}
Mike Stump11289f42009-09-09 15:08:12 +00005612
Douglas Gregora1f013e2008-11-07 22:36:19 +00005613/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005614/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005615/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005616/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005617/// (which may or may not be the same type as the type that the
5618/// conversion function produces).
5619void
5620Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005621 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005622 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005623 Expr *From, QualType ToType,
5624 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005625 assert(!Conversion->getDescribedFunctionTemplate() &&
5626 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005627 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005628 if (!CandidateSet.isNewCandidate(Conversion))
5629 return;
5630
Douglas Gregor27381f32009-11-23 12:27:39 +00005631 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005632 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005633
Douglas Gregora1f013e2008-11-07 22:36:19 +00005634 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005635 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005636 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005637 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005638 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005639 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005640 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005641 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005642 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005643 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005644 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005645
Douglas Gregor6affc782010-08-19 15:37:02 +00005646 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647 // For conversion functions, the function is considered to be a member of
5648 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005649 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005650 //
5651 // Determine the implicit conversion sequence for the implicit
5652 // object parameter.
5653 QualType ImplicitParamType = From->getType();
5654 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5655 ImplicitParamType = FromPtrType->getPointeeType();
5656 CXXRecordDecl *ConversionContext
5657 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005659 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660 = TryObjectArgumentInitialization(*this, From->getType(),
5661 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005662 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
John McCall0d1da222010-01-12 00:44:57 +00005664 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005665 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005666 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005667 return;
5668 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005669
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005671 // derived to base as such conversions are given Conversion Rank. They only
5672 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5673 QualType FromCanon
5674 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5675 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5676 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5677 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005678 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005679 return;
5680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005681
Douglas Gregora1f013e2008-11-07 22:36:19 +00005682 // To determine what the conversion from the result of calling the
5683 // conversion function to the type we're eventually trying to
5684 // convert to (ToType), we need to synthesize a call to the
5685 // conversion function and attempt copy initialization from it. This
5686 // makes sure that we get the right semantics with respect to
5687 // lvalues/rvalues and the type. Fortunately, we can allocate this
5688 // call on the stack and we don't need its arguments to be
5689 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005690 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005691 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005692 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5693 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005694 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005695 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005696
Richard Smith48d24642011-07-13 22:53:21 +00005697 QualType ConversionType = Conversion->getConversionType();
5698 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005699 Candidate.Viable = false;
5700 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5701 return;
5702 }
5703
Richard Smith48d24642011-07-13 22:53:21 +00005704 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005705
Mike Stump11289f42009-09-09 15:08:12 +00005706 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005707 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5708 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005709 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005710 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005711 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005712 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005713 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005714 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005715 /*InOverloadResolution=*/false,
5716 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005717
John McCall0d1da222010-01-12 00:44:57 +00005718 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005719 case ImplicitConversionSequence::StandardConversion:
5720 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005722 // C++ [over.ics.user]p3:
5723 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005725 // shall have exact match rank.
5726 if (Conversion->getPrimaryTemplate() &&
5727 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5728 Candidate.Viable = false;
5729 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005731
Douglas Gregorcba72b12011-01-21 05:18:22 +00005732 // C++0x [dcl.init.ref]p5:
5733 // In the second case, if the reference is an rvalue reference and
5734 // the second standard conversion sequence of the user-defined
5735 // conversion sequence includes an lvalue-to-rvalue conversion, the
5736 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005738 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5739 Candidate.Viable = false;
5740 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5741 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005742 break;
5743
5744 case ImplicitConversionSequence::BadConversion:
5745 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005746 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005747 break;
5748
5749 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005750 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005751 "Can only end up with a standard conversion sequence or failure");
5752 }
5753}
5754
Douglas Gregor05155d82009-08-21 23:19:43 +00005755/// \brief Adds a conversion function template specialization
5756/// candidate to the overload set, using template argument deduction
5757/// to deduce the template arguments of the conversion function
5758/// template from the type that we are converting to (C++
5759/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005760void
Douglas Gregor05155d82009-08-21 23:19:43 +00005761Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005762 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005763 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005764 Expr *From, QualType ToType,
5765 OverloadCandidateSet &CandidateSet) {
5766 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5767 "Only conversion function templates permitted here");
5768
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005769 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5770 return;
5771
John McCallbc077cf2010-02-08 23:07:23 +00005772 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005773 CXXConversionDecl *Specialization = 0;
5774 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005775 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005776 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005777 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005778 Candidate.FoundDecl = FoundDecl;
5779 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5780 Candidate.Viable = false;
5781 Candidate.FailureKind = ovl_fail_bad_deduction;
5782 Candidate.IsSurrogate = false;
5783 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005784 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005786 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005787 return;
5788 }
Mike Stump11289f42009-09-09 15:08:12 +00005789
Douglas Gregor05155d82009-08-21 23:19:43 +00005790 // Add the conversion function template specialization produced by
5791 // template argument deduction as a candidate.
5792 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005793 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005794 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005795}
5796
Douglas Gregorab7897a2008-11-19 22:57:39 +00005797/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5798/// converts the given @c Object to a function pointer via the
5799/// conversion function @c Conversion, and then attempts to call it
5800/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5801/// the type of function that we'll eventually be calling.
5802void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005803 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005804 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005805 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005806 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005807 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005808 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005809 if (!CandidateSet.isNewCandidate(Conversion))
5810 return;
5811
Douglas Gregor27381f32009-11-23 12:27:39 +00005812 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005813 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005814
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005815 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005816 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005817 Candidate.Function = 0;
5818 Candidate.Surrogate = Conversion;
5819 Candidate.Viable = true;
5820 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005821 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005822 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005823
5824 // Determine the implicit conversion sequence for the implicit
5825 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005826 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005828 Object->Classify(Context),
5829 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005830 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005831 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005832 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005833 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005834 return;
5835 }
5836
5837 // The first conversion is actually a user-defined conversion whose
5838 // first conversion is ObjectInit's standard conversion (which is
5839 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005840 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005841 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005842 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005843 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005844 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005845 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005846 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005847 = Candidate.Conversions[0].UserDefined.Before;
5848 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5849
Mike Stump11289f42009-09-09 15:08:12 +00005850 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005851 unsigned NumArgsInProto = Proto->getNumArgs();
5852
5853 // (C++ 13.3.2p2): A candidate function having fewer than m
5854 // parameters is viable only if it has an ellipsis in its parameter
5855 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005856 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005857 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005858 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005859 return;
5860 }
5861
5862 // Function types don't have any default arguments, so just check if
5863 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005864 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005865 // Not enough arguments.
5866 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005867 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005868 return;
5869 }
5870
5871 // Determine the implicit conversion sequences for each of the
5872 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005873 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005874 if (ArgIdx < NumArgsInProto) {
5875 // (C++ 13.3.2p3): for F to be a viable function, there shall
5876 // exist for each argument an implicit conversion sequence
5877 // (13.3.3.1) that converts that argument to the corresponding
5878 // parameter of F.
5879 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005880 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005881 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005882 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005883 /*InOverloadResolution=*/false,
5884 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005885 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005886 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005887 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005888 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005889 break;
5890 }
5891 } else {
5892 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5893 // argument for which there is no corresponding parameter is
5894 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005895 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005896 }
5897 }
5898}
5899
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005900/// \brief Add overload candidates for overloaded operators that are
5901/// member functions.
5902///
5903/// Add the overloaded operator candidates that are member functions
5904/// for the operator Op that was used in an operator expression such
5905/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5906/// CandidateSet will store the added overload candidates. (C++
5907/// [over.match.oper]).
5908void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5909 SourceLocation OpLoc,
5910 Expr **Args, unsigned NumArgs,
5911 OverloadCandidateSet& CandidateSet,
5912 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005913 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5914
5915 // C++ [over.match.oper]p3:
5916 // For a unary operator @ with an operand of a type whose
5917 // cv-unqualified version is T1, and for a binary operator @ with
5918 // a left operand of a type whose cv-unqualified version is T1 and
5919 // a right operand of a type whose cv-unqualified version is T2,
5920 // three sets of candidate functions, designated member
5921 // candidates, non-member candidates and built-in candidates, are
5922 // constructed as follows:
5923 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005924
5925 // -- If T1 is a class type, the set of member candidates is the
5926 // result of the qualified lookup of T1::operator@
5927 // (13.3.1.1.1); otherwise, the set of member candidates is
5928 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005929 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005930 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005931 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005932 return;
Mike Stump11289f42009-09-09 15:08:12 +00005933
John McCall27b18f82009-11-17 02:14:36 +00005934 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5935 LookupQualifiedName(Operators, T1Rec->getDecl());
5936 Operators.suppressDiagnostics();
5937
Mike Stump11289f42009-09-09 15:08:12 +00005938 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005939 OperEnd = Operators.end();
5940 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005941 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005942 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005943 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005944 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005945 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005946 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005947}
5948
Douglas Gregora11693b2008-11-12 17:17:38 +00005949/// AddBuiltinCandidate - Add a candidate for a built-in
5950/// operator. ResultTy and ParamTys are the result and parameter types
5951/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005952/// arguments being passed to the candidate. IsAssignmentOperator
5953/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005954/// operator. NumContextualBoolArguments is the number of arguments
5955/// (at the beginning of the argument list) that will be contextually
5956/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005957void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005958 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005959 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005960 bool IsAssignmentOperator,
5961 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005962 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005963 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005964
Douglas Gregora11693b2008-11-12 17:17:38 +00005965 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005966 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005967 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005968 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005969 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005970 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005971 Candidate.BuiltinTypes.ResultTy = ResultTy;
5972 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5973 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5974
5975 // Determine the implicit conversion sequences for each of the
5976 // arguments.
5977 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005978 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005979 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005980 // C++ [over.match.oper]p4:
5981 // For the built-in assignment operators, conversions of the
5982 // left operand are restricted as follows:
5983 // -- no temporaries are introduced to hold the left operand, and
5984 // -- no user-defined conversions are applied to the left
5985 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005986 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005987 //
5988 // We block these conversions by turning off user-defined
5989 // conversions, since that is the only way that initialization of
5990 // a reference to a non-class type can occur from something that
5991 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005992 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005993 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005994 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005995 Candidate.Conversions[ArgIdx]
5996 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005997 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005998 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005999 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006000 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006001 /*InOverloadResolution=*/false,
6002 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006003 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006004 }
John McCall0d1da222010-01-12 00:44:57 +00006005 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006006 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006007 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006008 break;
6009 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006010 }
6011}
6012
6013/// BuiltinCandidateTypeSet - A set of types that will be used for the
6014/// candidate operator functions for built-in operators (C++
6015/// [over.built]). The types are separated into pointer types and
6016/// enumeration types.
6017class BuiltinCandidateTypeSet {
6018 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006019 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006020
6021 /// PointerTypes - The set of pointer types that will be used in the
6022 /// built-in candidates.
6023 TypeSet PointerTypes;
6024
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006025 /// MemberPointerTypes - The set of member pointer types that will be
6026 /// used in the built-in candidates.
6027 TypeSet MemberPointerTypes;
6028
Douglas Gregora11693b2008-11-12 17:17:38 +00006029 /// EnumerationTypes - The set of enumeration types that will be
6030 /// used in the built-in candidates.
6031 TypeSet EnumerationTypes;
6032
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006033 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006034 /// candidates.
6035 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006036
6037 /// \brief A flag indicating non-record types are viable candidates
6038 bool HasNonRecordTypes;
6039
6040 /// \brief A flag indicating whether either arithmetic or enumeration types
6041 /// were present in the candidate set.
6042 bool HasArithmeticOrEnumeralTypes;
6043
Douglas Gregor80af3132011-05-21 23:15:46 +00006044 /// \brief A flag indicating whether the nullptr type was present in the
6045 /// candidate set.
6046 bool HasNullPtrType;
6047
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006048 /// Sema - The semantic analysis instance where we are building the
6049 /// candidate type set.
6050 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006051
Douglas Gregora11693b2008-11-12 17:17:38 +00006052 /// Context - The AST context in which we will build the type sets.
6053 ASTContext &Context;
6054
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006055 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6056 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006057 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006058
6059public:
6060 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006061 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006062
Mike Stump11289f42009-09-09 15:08:12 +00006063 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006064 : HasNonRecordTypes(false),
6065 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006066 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006067 SemaRef(SemaRef),
6068 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006069
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006070 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006071 SourceLocation Loc,
6072 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006073 bool AllowExplicitConversions,
6074 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006075
6076 /// pointer_begin - First pointer type found;
6077 iterator pointer_begin() { return PointerTypes.begin(); }
6078
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006079 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006080 iterator pointer_end() { return PointerTypes.end(); }
6081
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006082 /// member_pointer_begin - First member pointer type found;
6083 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6084
6085 /// member_pointer_end - Past the last member pointer type found;
6086 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6087
Douglas Gregora11693b2008-11-12 17:17:38 +00006088 /// enumeration_begin - First enumeration type found;
6089 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6090
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006091 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006092 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006093
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006094 iterator vector_begin() { return VectorTypes.begin(); }
6095 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006096
6097 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6098 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006099 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006100};
6101
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006102/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006103/// the set of pointer types along with any more-qualified variants of
6104/// that type. For example, if @p Ty is "int const *", this routine
6105/// will add "int const *", "int const volatile *", "int const
6106/// restrict *", and "int const volatile restrict *" to the set of
6107/// pointer types. Returns true if the add of @p Ty itself succeeded,
6108/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006109///
6110/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006111bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006112BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6113 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006114
Douglas Gregora11693b2008-11-12 17:17:38 +00006115 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006116 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006117 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006118
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006119 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006120 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006121 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006122 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006123 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006124 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006125 buildObjCPtr = true;
6126 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006127 else
David Blaikie83d382b2011-09-23 05:06:16 +00006128 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006129 }
6130 else
6131 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006132
Sebastian Redl4990a632009-11-18 20:39:26 +00006133 // Don't add qualified variants of arrays. For one, they're not allowed
6134 // (the qualifier would sink to the element type), and for another, the
6135 // only overload situation where it matters is subscript or pointer +- int,
6136 // and those shouldn't have qualifier variants anyway.
6137 if (PointeeTy->isArrayType())
6138 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006139 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00006140 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00006141 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006142 bool hasVolatile = VisibleQuals.hasVolatile();
6143 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006144
John McCall8ccfcb52009-09-24 19:53:00 +00006145 // Iterate through all strict supersets of BaseCVR.
6146 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6147 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006148 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6149 // in the types.
6150 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6151 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00006152 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006153 if (!buildObjCPtr)
6154 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6155 else
6156 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00006157 }
6158
6159 return true;
6160}
6161
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006162/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6163/// to the set of pointer types along with any more-qualified variants of
6164/// that type. For example, if @p Ty is "int const *", this routine
6165/// will add "int const *", "int const volatile *", "int const
6166/// restrict *", and "int const volatile restrict *" to the set of
6167/// pointer types. Returns true if the add of @p Ty itself succeeded,
6168/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006169///
6170/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006171bool
6172BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6173 QualType Ty) {
6174 // Insert this type.
6175 if (!MemberPointerTypes.insert(Ty))
6176 return false;
6177
John McCall8ccfcb52009-09-24 19:53:00 +00006178 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6179 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006180
John McCall8ccfcb52009-09-24 19:53:00 +00006181 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006182 // Don't add qualified variants of arrays. For one, they're not allowed
6183 // (the qualifier would sink to the element type), and for another, the
6184 // only overload situation where it matters is subscript or pointer +- int,
6185 // and those shouldn't have qualifier variants anyway.
6186 if (PointeeTy->isArrayType())
6187 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006188 const Type *ClassTy = PointerTy->getClass();
6189
6190 // Iterate through all strict supersets of the pointee type's CVR
6191 // qualifiers.
6192 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6193 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6194 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006195
John McCall8ccfcb52009-09-24 19:53:00 +00006196 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006197 MemberPointerTypes.insert(
6198 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006199 }
6200
6201 return true;
6202}
6203
Douglas Gregora11693b2008-11-12 17:17:38 +00006204/// AddTypesConvertedFrom - Add each of the types to which the type @p
6205/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006206/// primarily interested in pointer types and enumeration types. We also
6207/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006208/// AllowUserConversions is true if we should look at the conversion
6209/// functions of a class type, and AllowExplicitConversions if we
6210/// should also include the explicit conversion functions of a class
6211/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006212void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006213BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006214 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006215 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006216 bool AllowExplicitConversions,
6217 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006218 // Only deal with canonical types.
6219 Ty = Context.getCanonicalType(Ty);
6220
6221 // Look through reference types; they aren't part of the type of an
6222 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006223 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006224 Ty = RefTy->getPointeeType();
6225
John McCall33ddac02011-01-19 10:06:00 +00006226 // If we're dealing with an array type, decay to the pointer.
6227 if (Ty->isArrayType())
6228 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6229
6230 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006231 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006232
Chandler Carruth00a38332010-12-13 01:44:01 +00006233 // Flag if we ever add a non-record type.
6234 const RecordType *TyRec = Ty->getAs<RecordType>();
6235 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6236
Chandler Carruth00a38332010-12-13 01:44:01 +00006237 // Flag if we encounter an arithmetic type.
6238 HasArithmeticOrEnumeralTypes =
6239 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6240
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006241 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6242 PointerTypes.insert(Ty);
6243 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006244 // Insert our type, and its more-qualified variants, into the set
6245 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006246 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006247 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006248 } else if (Ty->isMemberPointerType()) {
6249 // Member pointers are far easier, since the pointee can't be converted.
6250 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6251 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006252 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006253 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006254 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006255 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006256 // We treat vector types as arithmetic types in many contexts as an
6257 // extension.
6258 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006259 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006260 } else if (Ty->isNullPtrType()) {
6261 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006262 } else if (AllowUserConversions && TyRec) {
6263 // No conversion functions in incomplete types.
6264 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6265 return;
Mike Stump11289f42009-09-09 15:08:12 +00006266
Chandler Carruth00a38332010-12-13 01:44:01 +00006267 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6268 const UnresolvedSetImpl *Conversions
6269 = ClassDecl->getVisibleConversionFunctions();
6270 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6271 E = Conversions->end(); I != E; ++I) {
6272 NamedDecl *D = I.getDecl();
6273 if (isa<UsingShadowDecl>(D))
6274 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006275
Chandler Carruth00a38332010-12-13 01:44:01 +00006276 // Skip conversion function templates; they don't tell us anything
6277 // about which builtin types we can convert to.
6278 if (isa<FunctionTemplateDecl>(D))
6279 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006280
Chandler Carruth00a38332010-12-13 01:44:01 +00006281 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6282 if (AllowExplicitConversions || !Conv->isExplicit()) {
6283 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6284 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006285 }
6286 }
6287 }
6288}
6289
Douglas Gregor84605ae2009-08-24 13:43:27 +00006290/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6291/// the volatile- and non-volatile-qualified assignment operators for the
6292/// given type to the candidate set.
6293static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6294 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006295 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006296 unsigned NumArgs,
6297 OverloadCandidateSet &CandidateSet) {
6298 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006299
Douglas Gregor84605ae2009-08-24 13:43:27 +00006300 // T& operator=(T&, T)
6301 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6302 ParamTypes[1] = T;
6303 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6304 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006305
Douglas Gregor84605ae2009-08-24 13:43:27 +00006306 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6307 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006308 ParamTypes[0]
6309 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006310 ParamTypes[1] = T;
6311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006312 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006313 }
6314}
Mike Stump11289f42009-09-09 15:08:12 +00006315
Sebastian Redl1054fae2009-10-25 17:03:50 +00006316/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6317/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006318static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6319 Qualifiers VRQuals;
6320 const RecordType *TyRec;
6321 if (const MemberPointerType *RHSMPType =
6322 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006323 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006324 else
6325 TyRec = ArgExpr->getType()->getAs<RecordType>();
6326 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006327 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006328 VRQuals.addVolatile();
6329 VRQuals.addRestrict();
6330 return VRQuals;
6331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006333 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006334 if (!ClassDecl->hasDefinition())
6335 return VRQuals;
6336
John McCallad371252010-01-20 00:46:10 +00006337 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006338 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006339
John McCallad371252010-01-20 00:46:10 +00006340 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006341 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006342 NamedDecl *D = I.getDecl();
6343 if (isa<UsingShadowDecl>(D))
6344 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6345 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006346 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6347 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6348 CanTy = ResTypeRef->getPointeeType();
6349 // Need to go down the pointer/mempointer chain and add qualifiers
6350 // as see them.
6351 bool done = false;
6352 while (!done) {
6353 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6354 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006355 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006356 CanTy->getAs<MemberPointerType>())
6357 CanTy = ResTypeMPtr->getPointeeType();
6358 else
6359 done = true;
6360 if (CanTy.isVolatileQualified())
6361 VRQuals.addVolatile();
6362 if (CanTy.isRestrictQualified())
6363 VRQuals.addRestrict();
6364 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6365 return VRQuals;
6366 }
6367 }
6368 }
6369 return VRQuals;
6370}
John McCall52872982010-11-13 05:51:15 +00006371
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006372namespace {
John McCall52872982010-11-13 05:51:15 +00006373
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006374/// \brief Helper class to manage the addition of builtin operator overload
6375/// candidates. It provides shared state and utility methods used throughout
6376/// the process, as well as a helper method to add each group of builtin
6377/// operator overloads from the standard to a candidate set.
6378class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006379 // Common instance state available to all overload candidate addition methods.
6380 Sema &S;
6381 Expr **Args;
6382 unsigned NumArgs;
6383 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006384 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006385 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006386 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006387
Chandler Carruthc6586e52010-12-12 10:35:00 +00006388 // Define some constants used to index and iterate over the arithemetic types
6389 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006390 // The "promoted arithmetic types" are the arithmetic
6391 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006392 static const unsigned FirstIntegralType = 3;
6393 static const unsigned LastIntegralType = 18;
6394 static const unsigned FirstPromotedIntegralType = 3,
6395 LastPromotedIntegralType = 9;
6396 static const unsigned FirstPromotedArithmeticType = 0,
6397 LastPromotedArithmeticType = 9;
6398 static const unsigned NumArithmeticTypes = 18;
6399
Chandler Carruthc6586e52010-12-12 10:35:00 +00006400 /// \brief Get the canonical type for a given arithmetic type index.
6401 CanQualType getArithmeticType(unsigned index) {
6402 assert(index < NumArithmeticTypes);
6403 static CanQualType ASTContext::* const
6404 ArithmeticTypes[NumArithmeticTypes] = {
6405 // Start of promoted types.
6406 &ASTContext::FloatTy,
6407 &ASTContext::DoubleTy,
6408 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006409
Chandler Carruthc6586e52010-12-12 10:35:00 +00006410 // Start of integral types.
6411 &ASTContext::IntTy,
6412 &ASTContext::LongTy,
6413 &ASTContext::LongLongTy,
6414 &ASTContext::UnsignedIntTy,
6415 &ASTContext::UnsignedLongTy,
6416 &ASTContext::UnsignedLongLongTy,
6417 // End of promoted types.
6418
6419 &ASTContext::BoolTy,
6420 &ASTContext::CharTy,
6421 &ASTContext::WCharTy,
6422 &ASTContext::Char16Ty,
6423 &ASTContext::Char32Ty,
6424 &ASTContext::SignedCharTy,
6425 &ASTContext::ShortTy,
6426 &ASTContext::UnsignedCharTy,
6427 &ASTContext::UnsignedShortTy,
6428 // End of integral types.
6429 // FIXME: What about complex?
6430 };
6431 return S.Context.*ArithmeticTypes[index];
6432 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006433
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006434 /// \brief Gets the canonical type resulting from the usual arithemetic
6435 /// converions for the given arithmetic types.
6436 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6437 // Accelerator table for performing the usual arithmetic conversions.
6438 // The rules are basically:
6439 // - if either is floating-point, use the wider floating-point
6440 // - if same signedness, use the higher rank
6441 // - if same size, use unsigned of the higher rank
6442 // - use the larger type
6443 // These rules, together with the axiom that higher ranks are
6444 // never smaller, are sufficient to precompute all of these results
6445 // *except* when dealing with signed types of higher rank.
6446 // (we could precompute SLL x UI for all known platforms, but it's
6447 // better not to make any assumptions).
6448 enum PromotedType {
6449 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6450 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006451 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006452 [LastPromotedArithmeticType] = {
6453 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6454 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6455 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6456 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6457 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6458 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6459 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6460 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6461 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6462 };
6463
6464 assert(L < LastPromotedArithmeticType);
6465 assert(R < LastPromotedArithmeticType);
6466 int Idx = ConversionsTable[L][R];
6467
6468 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006469 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006470
6471 // Slow path: we need to compare widths.
6472 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006473 CanQualType LT = getArithmeticType(L),
6474 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006475 unsigned LW = S.Context.getIntWidth(LT),
6476 RW = S.Context.getIntWidth(RT);
6477
6478 // If they're different widths, use the signed type.
6479 if (LW > RW) return LT;
6480 else if (LW < RW) return RT;
6481
6482 // Otherwise, use the unsigned type of the signed type's rank.
6483 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6484 assert(L == SLL || R == SLL);
6485 return S.Context.UnsignedLongLongTy;
6486 }
6487
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006488 /// \brief Helper method to factor out the common pattern of adding overloads
6489 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006490 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6491 bool HasVolatile) {
6492 QualType ParamTypes[2] = {
6493 S.Context.getLValueReferenceType(CandidateTy),
6494 S.Context.IntTy
6495 };
6496
6497 // Non-volatile version.
6498 if (NumArgs == 1)
6499 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6500 else
6501 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6502
6503 // Use a heuristic to reduce number of builtin candidates in the set:
6504 // add volatile version only if there are conversions to a volatile type.
6505 if (HasVolatile) {
6506 ParamTypes[0] =
6507 S.Context.getLValueReferenceType(
6508 S.Context.getVolatileType(CandidateTy));
6509 if (NumArgs == 1)
6510 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6511 else
6512 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6513 }
6514 }
6515
6516public:
6517 BuiltinOperatorOverloadBuilder(
6518 Sema &S, Expr **Args, unsigned NumArgs,
6519 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006520 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006521 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006522 OverloadCandidateSet &CandidateSet)
6523 : S(S), Args(Args), NumArgs(NumArgs),
6524 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006525 HasArithmeticOrEnumeralCandidateType(
6526 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006527 CandidateTypes(CandidateTypes),
6528 CandidateSet(CandidateSet) {
6529 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006530 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006531 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006532 assert(getArithmeticType(LastPromotedIntegralType - 1)
6533 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006534 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006535 assert(getArithmeticType(FirstPromotedArithmeticType)
6536 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006537 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006538 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6539 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006540 "Invalid last promoted arithmetic type");
6541 }
6542
6543 // C++ [over.built]p3:
6544 //
6545 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6546 // is either volatile or empty, there exist candidate operator
6547 // functions of the form
6548 //
6549 // VQ T& operator++(VQ T&);
6550 // T operator++(VQ T&, int);
6551 //
6552 // C++ [over.built]p4:
6553 //
6554 // For every pair (T, VQ), where T is an arithmetic type other
6555 // than bool, and VQ is either volatile or empty, there exist
6556 // candidate operator functions of the form
6557 //
6558 // VQ T& operator--(VQ T&);
6559 // T operator--(VQ T&, int);
6560 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006561 if (!HasArithmeticOrEnumeralCandidateType)
6562 return;
6563
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006564 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6565 Arith < NumArithmeticTypes; ++Arith) {
6566 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006567 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006568 VisibleTypeConversionsQuals.hasVolatile());
6569 }
6570 }
6571
6572 // C++ [over.built]p5:
6573 //
6574 // For every pair (T, VQ), where T is a cv-qualified or
6575 // cv-unqualified object type, and VQ is either volatile or
6576 // empty, there exist candidate operator functions of the form
6577 //
6578 // T*VQ& operator++(T*VQ&);
6579 // T*VQ& operator--(T*VQ&);
6580 // T* operator++(T*VQ&, int);
6581 // T* operator--(T*VQ&, int);
6582 void addPlusPlusMinusMinusPointerOverloads() {
6583 for (BuiltinCandidateTypeSet::iterator
6584 Ptr = CandidateTypes[0].pointer_begin(),
6585 PtrEnd = CandidateTypes[0].pointer_end();
6586 Ptr != PtrEnd; ++Ptr) {
6587 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006588 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006589 continue;
6590
6591 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6592 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6593 VisibleTypeConversionsQuals.hasVolatile()));
6594 }
6595 }
6596
6597 // C++ [over.built]p6:
6598 // For every cv-qualified or cv-unqualified object type T, there
6599 // exist candidate operator functions of the form
6600 //
6601 // T& operator*(T*);
6602 //
6603 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006605 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006606 // T& operator*(T*);
6607 void addUnaryStarPointerOverloads() {
6608 for (BuiltinCandidateTypeSet::iterator
6609 Ptr = CandidateTypes[0].pointer_begin(),
6610 PtrEnd = CandidateTypes[0].pointer_end();
6611 Ptr != PtrEnd; ++Ptr) {
6612 QualType ParamTy = *Ptr;
6613 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006614 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6615 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006616
Douglas Gregor02824322011-01-26 19:30:28 +00006617 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6618 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6619 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006620
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006621 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6622 &ParamTy, Args, 1, CandidateSet);
6623 }
6624 }
6625
6626 // C++ [over.built]p9:
6627 // For every promoted arithmetic type T, there exist candidate
6628 // operator functions of the form
6629 //
6630 // T operator+(T);
6631 // T operator-(T);
6632 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006633 if (!HasArithmeticOrEnumeralCandidateType)
6634 return;
6635
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006636 for (unsigned Arith = FirstPromotedArithmeticType;
6637 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006638 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006639 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6640 }
6641
6642 // Extension: We also add these operators for vector types.
6643 for (BuiltinCandidateTypeSet::iterator
6644 Vec = CandidateTypes[0].vector_begin(),
6645 VecEnd = CandidateTypes[0].vector_end();
6646 Vec != VecEnd; ++Vec) {
6647 QualType VecTy = *Vec;
6648 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6649 }
6650 }
6651
6652 // C++ [over.built]p8:
6653 // For every type T, there exist candidate operator functions of
6654 // the form
6655 //
6656 // T* operator+(T*);
6657 void addUnaryPlusPointerOverloads() {
6658 for (BuiltinCandidateTypeSet::iterator
6659 Ptr = CandidateTypes[0].pointer_begin(),
6660 PtrEnd = CandidateTypes[0].pointer_end();
6661 Ptr != PtrEnd; ++Ptr) {
6662 QualType ParamTy = *Ptr;
6663 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6664 }
6665 }
6666
6667 // C++ [over.built]p10:
6668 // For every promoted integral type T, there exist candidate
6669 // operator functions of the form
6670 //
6671 // T operator~(T);
6672 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006673 if (!HasArithmeticOrEnumeralCandidateType)
6674 return;
6675
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006676 for (unsigned Int = FirstPromotedIntegralType;
6677 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006678 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006679 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6680 }
6681
6682 // Extension: We also add this operator for vector types.
6683 for (BuiltinCandidateTypeSet::iterator
6684 Vec = CandidateTypes[0].vector_begin(),
6685 VecEnd = CandidateTypes[0].vector_end();
6686 Vec != VecEnd; ++Vec) {
6687 QualType VecTy = *Vec;
6688 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6689 }
6690 }
6691
6692 // C++ [over.match.oper]p16:
6693 // For every pointer to member type T, there exist candidate operator
6694 // functions of the form
6695 //
6696 // bool operator==(T,T);
6697 // bool operator!=(T,T);
6698 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6699 /// Set of (canonical) types that we've already handled.
6700 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6701
6702 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6703 for (BuiltinCandidateTypeSet::iterator
6704 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6705 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6706 MemPtr != MemPtrEnd;
6707 ++MemPtr) {
6708 // Don't add the same builtin candidate twice.
6709 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6710 continue;
6711
6712 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6713 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6714 CandidateSet);
6715 }
6716 }
6717 }
6718
6719 // C++ [over.built]p15:
6720 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006721 // For every T, where T is an enumeration type, a pointer type, or
6722 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006723 //
6724 // bool operator<(T, T);
6725 // bool operator>(T, T);
6726 // bool operator<=(T, T);
6727 // bool operator>=(T, T);
6728 // bool operator==(T, T);
6729 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006730 void addRelationalPointerOrEnumeralOverloads() {
6731 // C++ [over.built]p1:
6732 // If there is a user-written candidate with the same name and parameter
6733 // types as a built-in candidate operator function, the built-in operator
6734 // function is hidden and is not included in the set of candidate
6735 // functions.
6736 //
6737 // The text is actually in a note, but if we don't implement it then we end
6738 // up with ambiguities when the user provides an overloaded operator for
6739 // an enumeration type. Note that only enumeration types have this problem,
6740 // so we track which enumeration types we've seen operators for. Also, the
6741 // only other overloaded operator with enumeration argumenst, operator=,
6742 // cannot be overloaded for enumeration types, so this is the only place
6743 // where we must suppress candidates like this.
6744 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6745 UserDefinedBinaryOperators;
6746
6747 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6748 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6749 CandidateTypes[ArgIdx].enumeration_end()) {
6750 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6751 CEnd = CandidateSet.end();
6752 C != CEnd; ++C) {
6753 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6754 continue;
6755
6756 QualType FirstParamType =
6757 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6758 QualType SecondParamType =
6759 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6760
6761 // Skip if either parameter isn't of enumeral type.
6762 if (!FirstParamType->isEnumeralType() ||
6763 !SecondParamType->isEnumeralType())
6764 continue;
6765
6766 // Add this operator to the set of known user-defined operators.
6767 UserDefinedBinaryOperators.insert(
6768 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6769 S.Context.getCanonicalType(SecondParamType)));
6770 }
6771 }
6772 }
6773
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006774 /// Set of (canonical) types that we've already handled.
6775 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6776
6777 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6778 for (BuiltinCandidateTypeSet::iterator
6779 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6780 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6781 Ptr != PtrEnd; ++Ptr) {
6782 // Don't add the same builtin candidate twice.
6783 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6784 continue;
6785
6786 QualType ParamTypes[2] = { *Ptr, *Ptr };
6787 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6788 CandidateSet);
6789 }
6790 for (BuiltinCandidateTypeSet::iterator
6791 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6792 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6793 Enum != EnumEnd; ++Enum) {
6794 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6795
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006796 // Don't add the same builtin candidate twice, or if a user defined
6797 // candidate exists.
6798 if (!AddedTypes.insert(CanonType) ||
6799 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6800 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006801 continue;
6802
6803 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006804 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6805 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006806 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006807
6808 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6809 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6810 if (AddedTypes.insert(NullPtrTy) &&
6811 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6812 NullPtrTy))) {
6813 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6814 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6815 CandidateSet);
6816 }
6817 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006818 }
6819 }
6820
6821 // C++ [over.built]p13:
6822 //
6823 // For every cv-qualified or cv-unqualified object type T
6824 // there exist candidate operator functions of the form
6825 //
6826 // T* operator+(T*, ptrdiff_t);
6827 // T& operator[](T*, ptrdiff_t); [BELOW]
6828 // T* operator-(T*, ptrdiff_t);
6829 // T* operator+(ptrdiff_t, T*);
6830 // T& operator[](ptrdiff_t, T*); [BELOW]
6831 //
6832 // C++ [over.built]p14:
6833 //
6834 // For every T, where T is a pointer to object type, there
6835 // exist candidate operator functions of the form
6836 //
6837 // ptrdiff_t operator-(T, T);
6838 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6839 /// Set of (canonical) types that we've already handled.
6840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6841
6842 for (int Arg = 0; Arg < 2; ++Arg) {
6843 QualType AsymetricParamTypes[2] = {
6844 S.Context.getPointerDiffType(),
6845 S.Context.getPointerDiffType(),
6846 };
6847 for (BuiltinCandidateTypeSet::iterator
6848 Ptr = CandidateTypes[Arg].pointer_begin(),
6849 PtrEnd = CandidateTypes[Arg].pointer_end();
6850 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006851 QualType PointeeTy = (*Ptr)->getPointeeType();
6852 if (!PointeeTy->isObjectType())
6853 continue;
6854
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006855 AsymetricParamTypes[Arg] = *Ptr;
6856 if (Arg == 0 || Op == OO_Plus) {
6857 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6858 // T* operator+(ptrdiff_t, T*);
6859 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6860 CandidateSet);
6861 }
6862 if (Op == OO_Minus) {
6863 // ptrdiff_t operator-(T, T);
6864 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6865 continue;
6866
6867 QualType ParamTypes[2] = { *Ptr, *Ptr };
6868 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6869 Args, 2, CandidateSet);
6870 }
6871 }
6872 }
6873 }
6874
6875 // C++ [over.built]p12:
6876 //
6877 // For every pair of promoted arithmetic types L and R, there
6878 // exist candidate operator functions of the form
6879 //
6880 // LR operator*(L, R);
6881 // LR operator/(L, R);
6882 // LR operator+(L, R);
6883 // LR operator-(L, R);
6884 // bool operator<(L, R);
6885 // bool operator>(L, R);
6886 // bool operator<=(L, R);
6887 // bool operator>=(L, R);
6888 // bool operator==(L, R);
6889 // bool operator!=(L, R);
6890 //
6891 // where LR is the result of the usual arithmetic conversions
6892 // between types L and R.
6893 //
6894 // C++ [over.built]p24:
6895 //
6896 // For every pair of promoted arithmetic types L and R, there exist
6897 // candidate operator functions of the form
6898 //
6899 // LR operator?(bool, L, R);
6900 //
6901 // where LR is the result of the usual arithmetic conversions
6902 // between types L and R.
6903 // Our candidates ignore the first parameter.
6904 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006905 if (!HasArithmeticOrEnumeralCandidateType)
6906 return;
6907
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006908 for (unsigned Left = FirstPromotedArithmeticType;
6909 Left < LastPromotedArithmeticType; ++Left) {
6910 for (unsigned Right = FirstPromotedArithmeticType;
6911 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006912 QualType LandR[2] = { getArithmeticType(Left),
6913 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006914 QualType Result =
6915 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006916 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006917 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6918 }
6919 }
6920
6921 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6922 // conditional operator for vector types.
6923 for (BuiltinCandidateTypeSet::iterator
6924 Vec1 = CandidateTypes[0].vector_begin(),
6925 Vec1End = CandidateTypes[0].vector_end();
6926 Vec1 != Vec1End; ++Vec1) {
6927 for (BuiltinCandidateTypeSet::iterator
6928 Vec2 = CandidateTypes[1].vector_begin(),
6929 Vec2End = CandidateTypes[1].vector_end();
6930 Vec2 != Vec2End; ++Vec2) {
6931 QualType LandR[2] = { *Vec1, *Vec2 };
6932 QualType Result = S.Context.BoolTy;
6933 if (!isComparison) {
6934 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6935 Result = *Vec1;
6936 else
6937 Result = *Vec2;
6938 }
6939
6940 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6941 }
6942 }
6943 }
6944
6945 // C++ [over.built]p17:
6946 //
6947 // For every pair of promoted integral types L and R, there
6948 // exist candidate operator functions of the form
6949 //
6950 // LR operator%(L, R);
6951 // LR operator&(L, R);
6952 // LR operator^(L, R);
6953 // LR operator|(L, R);
6954 // L operator<<(L, R);
6955 // L operator>>(L, R);
6956 //
6957 // where LR is the result of the usual arithmetic conversions
6958 // between types L and R.
6959 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006960 if (!HasArithmeticOrEnumeralCandidateType)
6961 return;
6962
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006963 for (unsigned Left = FirstPromotedIntegralType;
6964 Left < LastPromotedIntegralType; ++Left) {
6965 for (unsigned Right = FirstPromotedIntegralType;
6966 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006967 QualType LandR[2] = { getArithmeticType(Left),
6968 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006969 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6970 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006971 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006972 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6973 }
6974 }
6975 }
6976
6977 // C++ [over.built]p20:
6978 //
6979 // For every pair (T, VQ), where T is an enumeration or
6980 // pointer to member type and VQ is either volatile or
6981 // empty, there exist candidate operator functions of the form
6982 //
6983 // VQ T& operator=(VQ T&, T);
6984 void addAssignmentMemberPointerOrEnumeralOverloads() {
6985 /// Set of (canonical) types that we've already handled.
6986 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6987
6988 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6989 for (BuiltinCandidateTypeSet::iterator
6990 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6991 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6992 Enum != EnumEnd; ++Enum) {
6993 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6994 continue;
6995
6996 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6997 CandidateSet);
6998 }
6999
7000 for (BuiltinCandidateTypeSet::iterator
7001 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7002 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7003 MemPtr != MemPtrEnd; ++MemPtr) {
7004 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7005 continue;
7006
7007 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7008 CandidateSet);
7009 }
7010 }
7011 }
7012
7013 // C++ [over.built]p19:
7014 //
7015 // For every pair (T, VQ), where T is any type and VQ is either
7016 // volatile or empty, there exist candidate operator functions
7017 // of the form
7018 //
7019 // T*VQ& operator=(T*VQ&, T*);
7020 //
7021 // C++ [over.built]p21:
7022 //
7023 // For every pair (T, VQ), where T is a cv-qualified or
7024 // cv-unqualified object type and VQ is either volatile or
7025 // empty, there exist candidate operator functions of the form
7026 //
7027 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7028 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7029 void addAssignmentPointerOverloads(bool isEqualOp) {
7030 /// Set of (canonical) types that we've already handled.
7031 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7032
7033 for (BuiltinCandidateTypeSet::iterator
7034 Ptr = CandidateTypes[0].pointer_begin(),
7035 PtrEnd = CandidateTypes[0].pointer_end();
7036 Ptr != PtrEnd; ++Ptr) {
7037 // If this is operator=, keep track of the builtin candidates we added.
7038 if (isEqualOp)
7039 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007040 else if (!(*Ptr)->getPointeeType()->isObjectType())
7041 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007042
7043 // non-volatile version
7044 QualType ParamTypes[2] = {
7045 S.Context.getLValueReferenceType(*Ptr),
7046 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7047 };
7048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7049 /*IsAssigmentOperator=*/ isEqualOp);
7050
7051 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7052 VisibleTypeConversionsQuals.hasVolatile()) {
7053 // volatile version
7054 ParamTypes[0] =
7055 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7057 /*IsAssigmentOperator=*/isEqualOp);
7058 }
7059 }
7060
7061 if (isEqualOp) {
7062 for (BuiltinCandidateTypeSet::iterator
7063 Ptr = CandidateTypes[1].pointer_begin(),
7064 PtrEnd = CandidateTypes[1].pointer_end();
7065 Ptr != PtrEnd; ++Ptr) {
7066 // Make sure we don't add the same candidate twice.
7067 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7068 continue;
7069
Chandler Carruth8e543b32010-12-12 08:17:55 +00007070 QualType ParamTypes[2] = {
7071 S.Context.getLValueReferenceType(*Ptr),
7072 *Ptr,
7073 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007074
7075 // non-volatile version
7076 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7077 /*IsAssigmentOperator=*/true);
7078
7079 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7080 VisibleTypeConversionsQuals.hasVolatile()) {
7081 // volatile version
7082 ParamTypes[0] =
7083 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007084 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7085 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007086 }
7087 }
7088 }
7089 }
7090
7091 // C++ [over.built]p18:
7092 //
7093 // For every triple (L, VQ, R), where L is an arithmetic type,
7094 // VQ is either volatile or empty, and R is a promoted
7095 // arithmetic type, there exist candidate operator functions of
7096 // the form
7097 //
7098 // VQ L& operator=(VQ L&, R);
7099 // VQ L& operator*=(VQ L&, R);
7100 // VQ L& operator/=(VQ L&, R);
7101 // VQ L& operator+=(VQ L&, R);
7102 // VQ L& operator-=(VQ L&, R);
7103 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007104 if (!HasArithmeticOrEnumeralCandidateType)
7105 return;
7106
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007107 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7108 for (unsigned Right = FirstPromotedArithmeticType;
7109 Right < LastPromotedArithmeticType; ++Right) {
7110 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007111 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007112
7113 // Add this built-in operator as a candidate (VQ is empty).
7114 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007115 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007116 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7117 /*IsAssigmentOperator=*/isEqualOp);
7118
7119 // Add this built-in operator as a candidate (VQ is 'volatile').
7120 if (VisibleTypeConversionsQuals.hasVolatile()) {
7121 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007122 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007123 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007124 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7125 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007126 /*IsAssigmentOperator=*/isEqualOp);
7127 }
7128 }
7129 }
7130
7131 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7132 for (BuiltinCandidateTypeSet::iterator
7133 Vec1 = CandidateTypes[0].vector_begin(),
7134 Vec1End = CandidateTypes[0].vector_end();
7135 Vec1 != Vec1End; ++Vec1) {
7136 for (BuiltinCandidateTypeSet::iterator
7137 Vec2 = CandidateTypes[1].vector_begin(),
7138 Vec2End = CandidateTypes[1].vector_end();
7139 Vec2 != Vec2End; ++Vec2) {
7140 QualType ParamTypes[2];
7141 ParamTypes[1] = *Vec2;
7142 // Add this built-in operator as a candidate (VQ is empty).
7143 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7145 /*IsAssigmentOperator=*/isEqualOp);
7146
7147 // Add this built-in operator as a candidate (VQ is 'volatile').
7148 if (VisibleTypeConversionsQuals.hasVolatile()) {
7149 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7150 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007151 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7152 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007153 /*IsAssigmentOperator=*/isEqualOp);
7154 }
7155 }
7156 }
7157 }
7158
7159 // C++ [over.built]p22:
7160 //
7161 // For every triple (L, VQ, R), where L is an integral type, VQ
7162 // is either volatile or empty, and R is a promoted integral
7163 // type, there exist candidate operator functions of the form
7164 //
7165 // VQ L& operator%=(VQ L&, R);
7166 // VQ L& operator<<=(VQ L&, R);
7167 // VQ L& operator>>=(VQ L&, R);
7168 // VQ L& operator&=(VQ L&, R);
7169 // VQ L& operator^=(VQ L&, R);
7170 // VQ L& operator|=(VQ L&, R);
7171 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007172 if (!HasArithmeticOrEnumeralCandidateType)
7173 return;
7174
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007175 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7176 for (unsigned Right = FirstPromotedIntegralType;
7177 Right < LastPromotedIntegralType; ++Right) {
7178 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007179 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007180
7181 // Add this built-in operator as a candidate (VQ is empty).
7182 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007183 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007184 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7185 if (VisibleTypeConversionsQuals.hasVolatile()) {
7186 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007187 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007188 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7189 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7191 CandidateSet);
7192 }
7193 }
7194 }
7195 }
7196
7197 // C++ [over.operator]p23:
7198 //
7199 // There also exist candidate operator functions of the form
7200 //
7201 // bool operator!(bool);
7202 // bool operator&&(bool, bool);
7203 // bool operator||(bool, bool);
7204 void addExclaimOverload() {
7205 QualType ParamTy = S.Context.BoolTy;
7206 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7207 /*IsAssignmentOperator=*/false,
7208 /*NumContextualBoolArguments=*/1);
7209 }
7210 void addAmpAmpOrPipePipeOverload() {
7211 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7212 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7213 /*IsAssignmentOperator=*/false,
7214 /*NumContextualBoolArguments=*/2);
7215 }
7216
7217 // C++ [over.built]p13:
7218 //
7219 // For every cv-qualified or cv-unqualified object type T there
7220 // exist candidate operator functions of the form
7221 //
7222 // T* operator+(T*, ptrdiff_t); [ABOVE]
7223 // T& operator[](T*, ptrdiff_t);
7224 // T* operator-(T*, ptrdiff_t); [ABOVE]
7225 // T* operator+(ptrdiff_t, T*); [ABOVE]
7226 // T& operator[](ptrdiff_t, T*);
7227 void addSubscriptOverloads() {
7228 for (BuiltinCandidateTypeSet::iterator
7229 Ptr = CandidateTypes[0].pointer_begin(),
7230 PtrEnd = CandidateTypes[0].pointer_end();
7231 Ptr != PtrEnd; ++Ptr) {
7232 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7233 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007234 if (!PointeeType->isObjectType())
7235 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007236
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7238
7239 // T& operator[](T*, ptrdiff_t)
7240 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7241 }
7242
7243 for (BuiltinCandidateTypeSet::iterator
7244 Ptr = CandidateTypes[1].pointer_begin(),
7245 PtrEnd = CandidateTypes[1].pointer_end();
7246 Ptr != PtrEnd; ++Ptr) {
7247 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7248 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007249 if (!PointeeType->isObjectType())
7250 continue;
7251
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007252 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7253
7254 // T& operator[](ptrdiff_t, T*)
7255 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7256 }
7257 }
7258
7259 // C++ [over.built]p11:
7260 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7261 // C1 is the same type as C2 or is a derived class of C2, T is an object
7262 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7263 // there exist candidate operator functions of the form
7264 //
7265 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7266 //
7267 // where CV12 is the union of CV1 and CV2.
7268 void addArrowStarOverloads() {
7269 for (BuiltinCandidateTypeSet::iterator
7270 Ptr = CandidateTypes[0].pointer_begin(),
7271 PtrEnd = CandidateTypes[0].pointer_end();
7272 Ptr != PtrEnd; ++Ptr) {
7273 QualType C1Ty = (*Ptr);
7274 QualType C1;
7275 QualifierCollector Q1;
7276 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7277 if (!isa<RecordType>(C1))
7278 continue;
7279 // heuristic to reduce number of builtin candidates in the set.
7280 // Add volatile/restrict version only if there are conversions to a
7281 // volatile/restrict type.
7282 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7283 continue;
7284 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7285 continue;
7286 for (BuiltinCandidateTypeSet::iterator
7287 MemPtr = CandidateTypes[1].member_pointer_begin(),
7288 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7289 MemPtr != MemPtrEnd; ++MemPtr) {
7290 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7291 QualType C2 = QualType(mptr->getClass(), 0);
7292 C2 = C2.getUnqualifiedType();
7293 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7294 break;
7295 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7296 // build CV12 T&
7297 QualType T = mptr->getPointeeType();
7298 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7299 T.isVolatileQualified())
7300 continue;
7301 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7302 T.isRestrictQualified())
7303 continue;
7304 T = Q1.apply(S.Context, T);
7305 QualType ResultTy = S.Context.getLValueReferenceType(T);
7306 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7307 }
7308 }
7309 }
7310
7311 // Note that we don't consider the first argument, since it has been
7312 // contextually converted to bool long ago. The candidates below are
7313 // therefore added as binary.
7314 //
7315 // C++ [over.built]p25:
7316 // For every type T, where T is a pointer, pointer-to-member, or scoped
7317 // enumeration type, there exist candidate operator functions of the form
7318 //
7319 // T operator?(bool, T, T);
7320 //
7321 void addConditionalOperatorOverloads() {
7322 /// Set of (canonical) types that we've already handled.
7323 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7324
7325 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7326 for (BuiltinCandidateTypeSet::iterator
7327 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7328 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7329 Ptr != PtrEnd; ++Ptr) {
7330 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7331 continue;
7332
7333 QualType ParamTypes[2] = { *Ptr, *Ptr };
7334 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7335 }
7336
7337 for (BuiltinCandidateTypeSet::iterator
7338 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7339 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7340 MemPtr != MemPtrEnd; ++MemPtr) {
7341 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7342 continue;
7343
7344 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7345 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7346 }
7347
David Blaikiebbafb8a2012-03-11 07:00:24 +00007348 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007349 for (BuiltinCandidateTypeSet::iterator
7350 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7351 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7352 Enum != EnumEnd; ++Enum) {
7353 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7354 continue;
7355
7356 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7357 continue;
7358
7359 QualType ParamTypes[2] = { *Enum, *Enum };
7360 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7361 }
7362 }
7363 }
7364 }
7365};
7366
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007367} // end anonymous namespace
7368
7369/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7370/// operator overloads to the candidate set (C++ [over.built]), based
7371/// on the operator @p Op and the arguments given. For example, if the
7372/// operator is a binary '+', this routine might add "int
7373/// operator+(int, int)" to cover integer addition.
7374void
7375Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7376 SourceLocation OpLoc,
7377 Expr **Args, unsigned NumArgs,
7378 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007379 // Find all of the types that the arguments can convert to, but only
7380 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007381 // that make use of these types. Also record whether we encounter non-record
7382 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007383 Qualifiers VisibleTypeConversionsQuals;
7384 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007385 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7386 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007387
7388 bool HasNonRecordCandidateType = false;
7389 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007390 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007391 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7392 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7393 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7394 OpLoc,
7395 true,
7396 (Op == OO_Exclaim ||
7397 Op == OO_AmpAmp ||
7398 Op == OO_PipePipe),
7399 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007400 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7401 CandidateTypes[ArgIdx].hasNonRecordTypes();
7402 HasArithmeticOrEnumeralCandidateType =
7403 HasArithmeticOrEnumeralCandidateType ||
7404 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007405 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007406
Chandler Carruth00a38332010-12-13 01:44:01 +00007407 // Exit early when no non-record types have been added to the candidate set
7408 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007409 //
7410 // We can't exit early for !, ||, or &&, since there we have always have
7411 // 'bool' overloads.
7412 if (!HasNonRecordCandidateType &&
7413 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007414 return;
7415
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416 // Setup an object to manage the common state for building overloads.
7417 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7418 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007419 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007420 CandidateTypes, CandidateSet);
7421
7422 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007423 switch (Op) {
7424 case OO_None:
7425 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007426 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007427
Chandler Carruth5184de02010-12-12 08:51:33 +00007428 case OO_New:
7429 case OO_Delete:
7430 case OO_Array_New:
7431 case OO_Array_Delete:
7432 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007433 llvm_unreachable(
7434 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007435
7436 case OO_Comma:
7437 case OO_Arrow:
7438 // C++ [over.match.oper]p3:
7439 // -- For the operator ',', the unary operator '&', or the
7440 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007441 break;
7442
7443 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007444 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007445 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007446 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007447
7448 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007449 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007450 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007451 } else {
7452 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7453 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7454 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007455 break;
7456
Chandler Carruth5184de02010-12-12 08:51:33 +00007457 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007458 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007459 OpBuilder.addUnaryStarPointerOverloads();
7460 else
7461 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7462 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463
Chandler Carruth5184de02010-12-12 08:51:33 +00007464 case OO_Slash:
7465 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007466 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007467
7468 case OO_PlusPlus:
7469 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7471 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007472 break;
7473
Douglas Gregor84605ae2009-08-24 13:43:27 +00007474 case OO_EqualEqual:
7475 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007477 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007478
Douglas Gregora11693b2008-11-12 17:17:38 +00007479 case OO_Less:
7480 case OO_Greater:
7481 case OO_LessEqual:
7482 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007483 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007484 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7485 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007486
Douglas Gregora11693b2008-11-12 17:17:38 +00007487 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007488 case OO_Caret:
7489 case OO_Pipe:
7490 case OO_LessLess:
7491 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007492 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007493 break;
7494
Chandler Carruth5184de02010-12-12 08:51:33 +00007495 case OO_Amp: // '&' is either unary or binary
7496 if (NumArgs == 1)
7497 // C++ [over.match.oper]p3:
7498 // -- For the operator ',', the unary operator '&', or the
7499 // operator '->', the built-in candidates set is empty.
7500 break;
7501
7502 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7503 break;
7504
7505 case OO_Tilde:
7506 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7507 break;
7508
Douglas Gregora11693b2008-11-12 17:17:38 +00007509 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007511 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007512
7513 case OO_PlusEqual:
7514 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007515 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007516 // Fall through.
7517
7518 case OO_StarEqual:
7519 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007521 break;
7522
7523 case OO_PercentEqual:
7524 case OO_LessLessEqual:
7525 case OO_GreaterGreaterEqual:
7526 case OO_AmpEqual:
7527 case OO_CaretEqual:
7528 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007529 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007530 break;
7531
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007532 case OO_Exclaim:
7533 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007534 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007535
Douglas Gregora11693b2008-11-12 17:17:38 +00007536 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 case OO_PipePipe:
7538 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007539 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007540
7541 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007543 break;
7544
7545 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007546 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007547 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007548
7549 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007550 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7552 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007553 }
7554}
7555
Douglas Gregore254f902009-02-04 00:32:51 +00007556/// \brief Add function candidates found via argument-dependent lookup
7557/// to the set of overloading candidates.
7558///
7559/// This routine performs argument-dependent name lookup based on the
7560/// given function name (which may also be an operator name) and adds
7561/// all of the overload candidates found by ADL to the overload
7562/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007563void
Douglas Gregore254f902009-02-04 00:32:51 +00007564Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007565 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007566 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007567 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007568 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007569 bool PartialOverloading,
7570 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007571 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007572
John McCall91f61fc2010-01-26 06:04:06 +00007573 // FIXME: This approach for uniquing ADL results (and removing
7574 // redundant candidates from the set) relies on pointer-equality,
7575 // which means we need to key off the canonical decl. However,
7576 // always going back to the canonical decl might not get us the
7577 // right set of default arguments. What default arguments are
7578 // we supposed to consider on ADL candidates, anyway?
7579
Douglas Gregorcabea402009-09-22 15:41:20 +00007580 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007581 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007582 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007583
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007584 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007585 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7586 CandEnd = CandidateSet.end();
7587 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007588 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007589 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007590 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007591 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007592 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007593
7594 // For each of the ADL candidates we found, add it to the overload
7595 // set.
John McCall8fe68082010-01-26 07:16:45 +00007596 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007597 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007598 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007599 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007600 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007602 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7603 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007604 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007605 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007606 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007607 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007608 }
Douglas Gregore254f902009-02-04 00:32:51 +00007609}
7610
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007611/// isBetterOverloadCandidate - Determines whether the first overload
7612/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007613bool
John McCall5c32be02010-08-24 20:38:10 +00007614isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007615 const OverloadCandidate &Cand1,
7616 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007617 SourceLocation Loc,
7618 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007619 // Define viable functions to be better candidates than non-viable
7620 // functions.
7621 if (!Cand2.Viable)
7622 return Cand1.Viable;
7623 else if (!Cand1.Viable)
7624 return false;
7625
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007626 // C++ [over.match.best]p1:
7627 //
7628 // -- if F is a static member function, ICS1(F) is defined such
7629 // that ICS1(F) is neither better nor worse than ICS1(G) for
7630 // any function G, and, symmetrically, ICS1(G) is neither
7631 // better nor worse than ICS1(F).
7632 unsigned StartArg = 0;
7633 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7634 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007635
Douglas Gregord3cb3562009-07-07 23:38:56 +00007636 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007637 // A viable function F1 is defined to be a better function than another
7638 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007639 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007640 unsigned NumArgs = Cand1.NumConversions;
7641 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007642 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007643 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007644 switch (CompareImplicitConversionSequences(S,
7645 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007646 Cand2.Conversions[ArgIdx])) {
7647 case ImplicitConversionSequence::Better:
7648 // Cand1 has a better conversion sequence.
7649 HasBetterConversion = true;
7650 break;
7651
7652 case ImplicitConversionSequence::Worse:
7653 // Cand1 can't be better than Cand2.
7654 return false;
7655
7656 case ImplicitConversionSequence::Indistinguishable:
7657 // Do nothing.
7658 break;
7659 }
7660 }
7661
Mike Stump11289f42009-09-09 15:08:12 +00007662 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007663 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007664 if (HasBetterConversion)
7665 return true;
7666
Mike Stump11289f42009-09-09 15:08:12 +00007667 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007668 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007669 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007670 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7671 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007672
7673 // -- F1 and F2 are function template specializations, and the function
7674 // template for F1 is more specialized than the template for F2
7675 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007676 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007677 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007678 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007679 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007680 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7681 Cand2.Function->getPrimaryTemplate(),
7682 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007683 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007684 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007685 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007686 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007688
Douglas Gregora1f013e2008-11-07 22:36:19 +00007689 // -- the context is an initialization by user-defined conversion
7690 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7691 // from the return type of F1 to the destination type (i.e.,
7692 // the type of the entity being initialized) is a better
7693 // conversion sequence than the standard conversion sequence
7694 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007695 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007696 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007697 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007698 // First check whether we prefer one of the conversion functions over the
7699 // other. This only distinguishes the results in non-standard, extension
7700 // cases such as the conversion from a lambda closure type to a function
7701 // pointer or block.
7702 ImplicitConversionSequence::CompareKind FuncResult
7703 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7704 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7705 return FuncResult;
7706
John McCall5c32be02010-08-24 20:38:10 +00007707 switch (CompareStandardConversionSequences(S,
7708 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007709 Cand2.FinalConversion)) {
7710 case ImplicitConversionSequence::Better:
7711 // Cand1 has a better conversion sequence.
7712 return true;
7713
7714 case ImplicitConversionSequence::Worse:
7715 // Cand1 can't be better than Cand2.
7716 return false;
7717
7718 case ImplicitConversionSequence::Indistinguishable:
7719 // Do nothing
7720 break;
7721 }
7722 }
7723
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007724 return false;
7725}
7726
Mike Stump11289f42009-09-09 15:08:12 +00007727/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007728/// within an overload candidate set.
7729///
7730/// \param CandidateSet the set of candidate functions.
7731///
7732/// \param Loc the location of the function name (or operator symbol) for
7733/// which overload resolution occurs.
7734///
Mike Stump11289f42009-09-09 15:08:12 +00007735/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007736/// function, Best points to the candidate function found.
7737///
7738/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007739OverloadingResult
7740OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007741 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007742 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007743 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007744 Best = end();
7745 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7746 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007747 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007748 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007749 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007750 }
7751
7752 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007753 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007754 return OR_No_Viable_Function;
7755
7756 // Make sure that this function is better than every other viable
7757 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007758 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007759 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007760 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007761 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007762 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007763 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007764 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007765 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007766 }
Mike Stump11289f42009-09-09 15:08:12 +00007767
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007768 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007769 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007770 (Best->Function->isDeleted() ||
7771 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007772 return OR_Deleted;
7773
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007774 return OR_Success;
7775}
7776
John McCall53262c92010-01-12 02:15:36 +00007777namespace {
7778
7779enum OverloadCandidateKind {
7780 oc_function,
7781 oc_method,
7782 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007783 oc_function_template,
7784 oc_method_template,
7785 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007786 oc_implicit_default_constructor,
7787 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007788 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007789 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007790 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007791 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007792};
7793
John McCalle1ac8d12010-01-13 00:25:19 +00007794OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7795 FunctionDecl *Fn,
7796 std::string &Description) {
7797 bool isTemplate = false;
7798
7799 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7800 isTemplate = true;
7801 Description = S.getTemplateArgumentBindingsText(
7802 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7803 }
John McCallfd0b2f82010-01-06 09:43:14 +00007804
7805 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007806 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007807 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007808
Sebastian Redl08905022011-02-05 19:23:19 +00007809 if (Ctor->getInheritedConstructor())
7810 return oc_implicit_inherited_constructor;
7811
Alexis Hunt119c10e2011-05-25 23:16:36 +00007812 if (Ctor->isDefaultConstructor())
7813 return oc_implicit_default_constructor;
7814
7815 if (Ctor->isMoveConstructor())
7816 return oc_implicit_move_constructor;
7817
7818 assert(Ctor->isCopyConstructor() &&
7819 "unexpected sort of implicit constructor");
7820 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007821 }
7822
7823 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7824 // This actually gets spelled 'candidate function' for now, but
7825 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007826 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007827 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007828
Alexis Hunt119c10e2011-05-25 23:16:36 +00007829 if (Meth->isMoveAssignmentOperator())
7830 return oc_implicit_move_assignment;
7831
Douglas Gregor12695102012-02-10 08:36:38 +00007832 if (Meth->isCopyAssignmentOperator())
7833 return oc_implicit_copy_assignment;
7834
7835 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7836 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007837 }
7838
John McCalle1ac8d12010-01-13 00:25:19 +00007839 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007840}
7841
Sebastian Redl08905022011-02-05 19:23:19 +00007842void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7843 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7844 if (!Ctor) return;
7845
7846 Ctor = Ctor->getInheritedConstructor();
7847 if (!Ctor) return;
7848
7849 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7850}
7851
John McCall53262c92010-01-12 02:15:36 +00007852} // end anonymous namespace
7853
7854// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007855void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007856 std::string FnDesc;
7857 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007858 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7859 << (unsigned) K << FnDesc;
7860 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7861 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007862 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007863}
7864
Douglas Gregorb491ed32011-02-19 21:32:49 +00007865//Notes the location of all overload candidates designated through
7866// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007867void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007868 assert(OverloadedExpr->getType() == Context.OverloadTy);
7869
7870 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7871 OverloadExpr *OvlExpr = Ovl.Expression;
7872
7873 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7874 IEnd = OvlExpr->decls_end();
7875 I != IEnd; ++I) {
7876 if (FunctionTemplateDecl *FunTmpl =
7877 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007878 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007879 } else if (FunctionDecl *Fun
7880 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007881 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007882 }
7883 }
7884}
7885
John McCall0d1da222010-01-12 00:44:57 +00007886/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7887/// "lead" diagnostic; it will be given two arguments, the source and
7888/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007889void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7890 Sema &S,
7891 SourceLocation CaretLoc,
7892 const PartialDiagnostic &PDiag) const {
7893 S.Diag(CaretLoc, PDiag)
7894 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007895 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007896 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7897 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007898 }
John McCall12f97bc2010-01-08 04:41:39 +00007899}
7900
John McCall0d1da222010-01-12 00:44:57 +00007901namespace {
7902
John McCall6a61b522010-01-13 09:16:55 +00007903void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7904 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7905 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007906 assert(Cand->Function && "for now, candidate must be a function");
7907 FunctionDecl *Fn = Cand->Function;
7908
7909 // There's a conversion slot for the object argument if this is a
7910 // non-constructor method. Note that 'I' corresponds the
7911 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007912 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007913 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007914 if (I == 0)
7915 isObjectArgument = true;
7916 else
7917 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007918 }
7919
John McCalle1ac8d12010-01-13 00:25:19 +00007920 std::string FnDesc;
7921 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7922
John McCall6a61b522010-01-13 09:16:55 +00007923 Expr *FromExpr = Conv.Bad.FromExpr;
7924 QualType FromTy = Conv.Bad.getFromType();
7925 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007926
John McCallfb7ad0f2010-02-02 02:42:52 +00007927 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007928 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007929 Expr *E = FromExpr->IgnoreParens();
7930 if (isa<UnaryOperator>(E))
7931 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007932 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007933
7934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7935 << (unsigned) FnKind << FnDesc
7936 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7937 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007938 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007939 return;
7940 }
7941
John McCall6d174642010-01-23 08:10:49 +00007942 // Do some hand-waving analysis to see if the non-viability is due
7943 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007944 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7945 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7946 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7947 CToTy = RT->getPointeeType();
7948 else {
7949 // TODO: detect and diagnose the full richness of const mismatches.
7950 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7951 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7952 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7953 }
7954
7955 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7956 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00007957 Qualifiers FromQs = CFromTy.getQualifiers();
7958 Qualifiers ToQs = CToTy.getQualifiers();
7959
7960 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7962 << (unsigned) FnKind << FnDesc
7963 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7964 << FromTy
7965 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7966 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007967 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007968 return;
7969 }
7970
John McCall31168b02011-06-15 23:02:42 +00007971 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007972 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007973 << (unsigned) FnKind << FnDesc
7974 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7975 << FromTy
7976 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7977 << (unsigned) isObjectArgument << I+1;
7978 MaybeEmitInheritedConstructorNote(S, Fn);
7979 return;
7980 }
7981
Douglas Gregoraec25842011-04-26 23:16:46 +00007982 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7983 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7984 << (unsigned) FnKind << FnDesc
7985 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7986 << FromTy
7987 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7988 << (unsigned) isObjectArgument << I+1;
7989 MaybeEmitInheritedConstructorNote(S, Fn);
7990 return;
7991 }
7992
John McCall47000992010-01-14 03:28:57 +00007993 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7994 assert(CVR && "unexpected qualifiers mismatch");
7995
7996 if (isObjectArgument) {
7997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7998 << (unsigned) FnKind << FnDesc
7999 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8000 << FromTy << (CVR - 1);
8001 } else {
8002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8003 << (unsigned) FnKind << FnDesc
8004 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8005 << FromTy << (CVR - 1) << I+1;
8006 }
Sebastian Redl08905022011-02-05 19:23:19 +00008007 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008008 return;
8009 }
8010
Sebastian Redla72462c2011-09-24 17:48:32 +00008011 // Special diagnostic for failure to convert an initializer list, since
8012 // telling the user that it has type void is not useful.
8013 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8015 << (unsigned) FnKind << FnDesc
8016 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8017 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8018 MaybeEmitInheritedConstructorNote(S, Fn);
8019 return;
8020 }
8021
John McCall6d174642010-01-23 08:10:49 +00008022 // Diagnose references or pointers to incomplete types differently,
8023 // since it's far from impossible that the incompleteness triggered
8024 // the failure.
8025 QualType TempFromTy = FromTy.getNonReferenceType();
8026 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8027 TempFromTy = PTy->getPointeeType();
8028 if (TempFromTy->isIncompleteType()) {
8029 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8030 << (unsigned) FnKind << FnDesc
8031 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8032 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008033 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008034 return;
8035 }
8036
Douglas Gregor56f2e342010-06-30 23:01:39 +00008037 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008038 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008039 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8040 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8041 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8042 FromPtrTy->getPointeeType()) &&
8043 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8044 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008046 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008047 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008048 }
8049 } else if (const ObjCObjectPointerType *FromPtrTy
8050 = FromTy->getAs<ObjCObjectPointerType>()) {
8051 if (const ObjCObjectPointerType *ToPtrTy
8052 = ToTy->getAs<ObjCObjectPointerType>())
8053 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8054 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8055 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8056 FromPtrTy->getPointeeType()) &&
8057 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008058 BaseToDerivedConversion = 2;
8059 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8060 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8061 !FromTy->isIncompleteType() &&
8062 !ToRefTy->getPointeeType()->isIncompleteType() &&
8063 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8064 BaseToDerivedConversion = 3;
8065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008067 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008069 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008070 << (unsigned) FnKind << FnDesc
8071 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008072 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008073 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008074 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008075 return;
8076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008078 if (isa<ObjCObjectPointerType>(CFromTy) &&
8079 isa<PointerType>(CToTy)) {
8080 Qualifiers FromQs = CFromTy.getQualifiers();
8081 Qualifiers ToQs = CToTy.getQualifiers();
8082 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8084 << (unsigned) FnKind << FnDesc
8085 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8086 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8087 MaybeEmitInheritedConstructorNote(S, Fn);
8088 return;
8089 }
8090 }
8091
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008092 // Emit the generic diagnostic and, optionally, add the hints to it.
8093 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8094 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008096 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8097 << (unsigned) (Cand->Fix.Kind);
8098
8099 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008100 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8101 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008102 FDiag << *HI;
8103 S.Diag(Fn->getLocation(), FDiag);
8104
Sebastian Redl08905022011-02-05 19:23:19 +00008105 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008106}
8107
8108void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8109 unsigned NumFormalArgs) {
8110 // TODO: treat calls to a missing default constructor as a special case
8111
8112 FunctionDecl *Fn = Cand->Function;
8113 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8114
8115 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008116
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008117 // With invalid overloaded operators, it's possible that we think we
8118 // have an arity mismatch when it fact it looks like we have the
8119 // right number of arguments, because only overloaded operators have
8120 // the weird behavior of overloading member and non-member functions.
8121 // Just don't report anything.
8122 if (Fn->isInvalidDecl() &&
8123 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8124 return;
8125
John McCall6a61b522010-01-13 09:16:55 +00008126 // at least / at most / exactly
8127 unsigned mode, modeCount;
8128 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008129 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8130 (Cand->FailureKind == ovl_fail_bad_deduction &&
8131 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008133 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008134 mode = 0; // "at least"
8135 else
8136 mode = 2; // "exactly"
8137 modeCount = MinParams;
8138 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008139 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8140 (Cand->FailureKind == ovl_fail_bad_deduction &&
8141 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008142 if (MinParams != FnTy->getNumArgs())
8143 mode = 1; // "at most"
8144 else
8145 mode = 2; // "exactly"
8146 modeCount = FnTy->getNumArgs();
8147 }
8148
8149 std::string Description;
8150 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8151
8152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00008154 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008155 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008156}
8157
John McCall8b9ed552010-02-01 18:53:26 +00008158/// Diagnose a failed template-argument deduction.
8159void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008160 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008161 FunctionDecl *Fn = Cand->Function; // pattern
8162
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008163 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008164 NamedDecl *ParamD;
8165 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8166 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8167 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008168 switch (Cand->DeductionFailure.Result) {
8169 case Sema::TDK_Success:
8170 llvm_unreachable("TDK_success while diagnosing bad deduction");
8171
8172 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008173 assert(ParamD && "no parameter found for incomplete deduction result");
8174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8175 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008176 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008177 return;
8178 }
8179
John McCall42d7d192010-08-05 09:05:08 +00008180 case Sema::TDK_Underqualified: {
8181 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8182 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8183
8184 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8185
8186 // Param will have been canonicalized, but it should just be a
8187 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008188 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008189 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008190 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008191 assert(S.Context.hasSameType(Param, NonCanonParam));
8192
8193 // Arg has also been canonicalized, but there's nothing we can do
8194 // about that. It also doesn't matter as much, because it won't
8195 // have any template parameters in it (because deduction isn't
8196 // done on dependent types).
8197 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8198
8199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8200 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008201 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008202 return;
8203 }
8204
8205 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008206 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008207 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008208 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008209 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008210 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008211 which = 1;
8212 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008213 which = 2;
8214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008215
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008216 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008217 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008218 << *Cand->DeductionFailure.getFirstArg()
8219 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008220 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008221 return;
8222 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008223
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008224 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008225 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008226 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008227 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008228 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8229 << ParamD->getDeclName();
8230 else {
8231 int index = 0;
8232 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8233 index = TTP->getIndex();
8234 else if (NonTypeTemplateParmDecl *NTTP
8235 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8236 index = NTTP->getIndex();
8237 else
8238 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008239 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008240 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8241 << (index + 1);
8242 }
Sebastian Redl08905022011-02-05 19:23:19 +00008243 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008244 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008245
Douglas Gregor02eb4832010-05-08 18:13:28 +00008246 case Sema::TDK_TooManyArguments:
8247 case Sema::TDK_TooFewArguments:
8248 DiagnoseArityMismatch(S, Cand, NumArgs);
8249 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008250
8251 case Sema::TDK_InstantiationDepth:
8252 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008253 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008254 return;
8255
8256 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008257 // Format the template argument list into the argument string.
8258 llvm::SmallString<128> TemplateArgString;
8259 if (TemplateArgumentList *Args =
8260 Cand->DeductionFailure.getTemplateArgumentList()) {
8261 TemplateArgString = " ";
8262 TemplateArgString += S.getTemplateArgumentBindingsText(
8263 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8264 }
8265
Richard Smith6f8d2c62012-05-09 05:17:00 +00008266 // If this candidate was disabled by enable_if, say so.
8267 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8268 if (PDiag && PDiag->second.getDiagID() ==
8269 diag::err_typename_nested_not_found_enable_if) {
8270 // FIXME: Use the source range of the condition, and the fully-qualified
8271 // name of the enable_if template. These are both present in PDiag.
8272 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8273 << "'enable_if'" << TemplateArgString;
8274 return;
8275 }
8276
Richard Smith9ca64612012-05-07 09:03:25 +00008277 // Format the SFINAE diagnostic into the argument string.
8278 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8279 // formatted message in another diagnostic.
8280 llvm::SmallString<128> SFINAEArgString;
8281 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008282 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008283 SFINAEArgString = ": ";
8284 R = SourceRange(PDiag->first, PDiag->first);
8285 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8286 }
8287
Douglas Gregord09efd42010-05-08 20:07:26 +00008288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008289 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008290 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008291 return;
8292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008293
John McCall8b9ed552010-02-01 18:53:26 +00008294 // TODO: diagnose these individually, then kill off
8295 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008296 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008297 case Sema::TDK_FailedOverloadResolution:
8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008299 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008300 return;
8301 }
8302}
8303
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008304/// CUDA: diagnose an invalid call across targets.
8305void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8306 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8307 FunctionDecl *Callee = Cand->Function;
8308
8309 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8310 CalleeTarget = S.IdentifyCUDATarget(Callee);
8311
8312 std::string FnDesc;
8313 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8314
8315 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8316 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8317}
8318
John McCall8b9ed552010-02-01 18:53:26 +00008319/// Generates a 'note' diagnostic for an overload candidate. We've
8320/// already generated a primary error at the call site.
8321///
8322/// It really does need to be a single diagnostic with its caret
8323/// pointed at the candidate declaration. Yes, this creates some
8324/// major challenges of technical writing. Yes, this makes pointing
8325/// out problems with specific arguments quite awkward. It's still
8326/// better than generating twenty screens of text for every failed
8327/// overload.
8328///
8329/// It would be great to be able to express per-candidate problems
8330/// more richly for those diagnostic clients that cared, but we'd
8331/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008332void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008333 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008334 FunctionDecl *Fn = Cand->Function;
8335
John McCall12f97bc2010-01-08 04:41:39 +00008336 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008337 if (Cand->Viable && (Fn->isDeleted() ||
8338 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008339 std::string FnDesc;
8340 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008341
8342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008343 << FnKind << FnDesc
8344 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008345 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008346 return;
John McCall12f97bc2010-01-08 04:41:39 +00008347 }
8348
John McCalle1ac8d12010-01-13 00:25:19 +00008349 // We don't really have anything else to say about viable candidates.
8350 if (Cand->Viable) {
8351 S.NoteOverloadCandidate(Fn);
8352 return;
8353 }
John McCall0d1da222010-01-12 00:44:57 +00008354
John McCall6a61b522010-01-13 09:16:55 +00008355 switch (Cand->FailureKind) {
8356 case ovl_fail_too_many_arguments:
8357 case ovl_fail_too_few_arguments:
8358 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008359
John McCall6a61b522010-01-13 09:16:55 +00008360 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008361 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008362
John McCallfe796dd2010-01-23 05:17:32 +00008363 case ovl_fail_trivial_conversion:
8364 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008365 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008366 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008367
John McCall65eb8792010-02-25 01:37:24 +00008368 case ovl_fail_bad_conversion: {
8369 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008370 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008371 if (Cand->Conversions[I].isBad())
8372 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008373
John McCall6a61b522010-01-13 09:16:55 +00008374 // FIXME: this currently happens when we're called from SemaInit
8375 // when user-conversion overload fails. Figure out how to handle
8376 // those conditions and diagnose them well.
8377 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008378 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008379
8380 case ovl_fail_bad_target:
8381 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008382 }
John McCalld3224162010-01-08 00:58:21 +00008383}
8384
8385void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8386 // Desugar the type of the surrogate down to a function type,
8387 // retaining as many typedefs as possible while still showing
8388 // the function type (and, therefore, its parameter types).
8389 QualType FnType = Cand->Surrogate->getConversionType();
8390 bool isLValueReference = false;
8391 bool isRValueReference = false;
8392 bool isPointer = false;
8393 if (const LValueReferenceType *FnTypeRef =
8394 FnType->getAs<LValueReferenceType>()) {
8395 FnType = FnTypeRef->getPointeeType();
8396 isLValueReference = true;
8397 } else if (const RValueReferenceType *FnTypeRef =
8398 FnType->getAs<RValueReferenceType>()) {
8399 FnType = FnTypeRef->getPointeeType();
8400 isRValueReference = true;
8401 }
8402 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8403 FnType = FnTypePtr->getPointeeType();
8404 isPointer = true;
8405 }
8406 // Desugar down to a function type.
8407 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8408 // Reconstruct the pointer/reference as appropriate.
8409 if (isPointer) FnType = S.Context.getPointerType(FnType);
8410 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8411 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8412
8413 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8414 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008415 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008416}
8417
8418void NoteBuiltinOperatorCandidate(Sema &S,
8419 const char *Opc,
8420 SourceLocation OpLoc,
8421 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008422 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008423 std::string TypeStr("operator");
8424 TypeStr += Opc;
8425 TypeStr += "(";
8426 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008427 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008428 TypeStr += ")";
8429 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8430 } else {
8431 TypeStr += ", ";
8432 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8433 TypeStr += ")";
8434 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8435 }
8436}
8437
8438void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8439 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008440 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008441 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8442 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008443 if (ICS.isBad()) break; // all meaningless after first invalid
8444 if (!ICS.isAmbiguous()) continue;
8445
John McCall5c32be02010-08-24 20:38:10 +00008446 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008447 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008448 }
8449}
8450
John McCall3712d9e2010-01-15 23:32:50 +00008451SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8452 if (Cand->Function)
8453 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008454 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008455 return Cand->Surrogate->getLocation();
8456 return SourceLocation();
8457}
8458
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008459static unsigned
8460RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008461 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008462 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008463 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008464
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008465 case Sema::TDK_Incomplete:
8466 return 1;
8467
8468 case Sema::TDK_Underqualified:
8469 case Sema::TDK_Inconsistent:
8470 return 2;
8471
8472 case Sema::TDK_SubstitutionFailure:
8473 case Sema::TDK_NonDeducedMismatch:
8474 return 3;
8475
8476 case Sema::TDK_InstantiationDepth:
8477 case Sema::TDK_FailedOverloadResolution:
8478 return 4;
8479
8480 case Sema::TDK_InvalidExplicitArguments:
8481 return 5;
8482
8483 case Sema::TDK_TooManyArguments:
8484 case Sema::TDK_TooFewArguments:
8485 return 6;
8486 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008487 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008488}
8489
John McCallad2587a2010-01-12 00:48:53 +00008490struct CompareOverloadCandidatesForDisplay {
8491 Sema &S;
8492 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008493
8494 bool operator()(const OverloadCandidate *L,
8495 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008496 // Fast-path this check.
8497 if (L == R) return false;
8498
John McCall12f97bc2010-01-08 04:41:39 +00008499 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008500 if (L->Viable) {
8501 if (!R->Viable) return true;
8502
8503 // TODO: introduce a tri-valued comparison for overload
8504 // candidates. Would be more worthwhile if we had a sort
8505 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008506 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8507 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008508 } else if (R->Viable)
8509 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008510
John McCall3712d9e2010-01-15 23:32:50 +00008511 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008512
John McCall3712d9e2010-01-15 23:32:50 +00008513 // Criteria by which we can sort non-viable candidates:
8514 if (!L->Viable) {
8515 // 1. Arity mismatches come after other candidates.
8516 if (L->FailureKind == ovl_fail_too_many_arguments ||
8517 L->FailureKind == ovl_fail_too_few_arguments)
8518 return false;
8519 if (R->FailureKind == ovl_fail_too_many_arguments ||
8520 R->FailureKind == ovl_fail_too_few_arguments)
8521 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008522
John McCallfe796dd2010-01-23 05:17:32 +00008523 // 2. Bad conversions come first and are ordered by the number
8524 // of bad conversions and quality of good conversions.
8525 if (L->FailureKind == ovl_fail_bad_conversion) {
8526 if (R->FailureKind != ovl_fail_bad_conversion)
8527 return true;
8528
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008529 // The conversion that can be fixed with a smaller number of changes,
8530 // comes first.
8531 unsigned numLFixes = L->Fix.NumConversionsFixed;
8532 unsigned numRFixes = R->Fix.NumConversionsFixed;
8533 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8534 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008535 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008536 if (numLFixes < numRFixes)
8537 return true;
8538 else
8539 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008540 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008541
John McCallfe796dd2010-01-23 05:17:32 +00008542 // If there's any ordering between the defined conversions...
8543 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008544 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008545
8546 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008547 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008548 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008549 switch (CompareImplicitConversionSequences(S,
8550 L->Conversions[I],
8551 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008552 case ImplicitConversionSequence::Better:
8553 leftBetter++;
8554 break;
8555
8556 case ImplicitConversionSequence::Worse:
8557 leftBetter--;
8558 break;
8559
8560 case ImplicitConversionSequence::Indistinguishable:
8561 break;
8562 }
8563 }
8564 if (leftBetter > 0) return true;
8565 if (leftBetter < 0) return false;
8566
8567 } else if (R->FailureKind == ovl_fail_bad_conversion)
8568 return false;
8569
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008570 if (L->FailureKind == ovl_fail_bad_deduction) {
8571 if (R->FailureKind != ovl_fail_bad_deduction)
8572 return true;
8573
8574 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8575 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008576 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008577 } else if (R->FailureKind == ovl_fail_bad_deduction)
8578 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008579
John McCall3712d9e2010-01-15 23:32:50 +00008580 // TODO: others?
8581 }
8582
8583 // Sort everything else by location.
8584 SourceLocation LLoc = GetLocationForCandidate(L);
8585 SourceLocation RLoc = GetLocationForCandidate(R);
8586
8587 // Put candidates without locations (e.g. builtins) at the end.
8588 if (LLoc.isInvalid()) return false;
8589 if (RLoc.isInvalid()) return true;
8590
8591 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008592 }
8593};
8594
John McCallfe796dd2010-01-23 05:17:32 +00008595/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008596/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008597void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008598 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008599 assert(!Cand->Viable);
8600
8601 // Don't do anything on failures other than bad conversion.
8602 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8603
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008604 // We only want the FixIts if all the arguments can be corrected.
8605 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008606 // Use a implicit copy initialization to check conversion fixes.
8607 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008608
John McCallfe796dd2010-01-23 05:17:32 +00008609 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008610 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008611 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008612 while (true) {
8613 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8614 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008615 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008616 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008617 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008618 }
John McCallfe796dd2010-01-23 05:17:32 +00008619 }
8620
8621 if (ConvIdx == ConvCount)
8622 return;
8623
John McCall65eb8792010-02-25 01:37:24 +00008624 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8625 "remaining conversion is initialized?");
8626
Douglas Gregoradc7a702010-04-16 17:45:54 +00008627 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008628 // operation somehow.
8629 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008630
8631 const FunctionProtoType* Proto;
8632 unsigned ArgIdx = ConvIdx;
8633
8634 if (Cand->IsSurrogate) {
8635 QualType ConvType
8636 = Cand->Surrogate->getConversionType().getNonReferenceType();
8637 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8638 ConvType = ConvPtrType->getPointeeType();
8639 Proto = ConvType->getAs<FunctionProtoType>();
8640 ArgIdx--;
8641 } else if (Cand->Function) {
8642 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8643 if (isa<CXXMethodDecl>(Cand->Function) &&
8644 !isa<CXXConstructorDecl>(Cand->Function))
8645 ArgIdx--;
8646 } else {
8647 // Builtin binary operator with a bad first conversion.
8648 assert(ConvCount <= 3);
8649 for (; ConvIdx != ConvCount; ++ConvIdx)
8650 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008651 = TryCopyInitialization(S, Args[ConvIdx],
8652 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008653 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008654 /*InOverloadResolution*/ true,
8655 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008656 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008657 return;
8658 }
8659
8660 // Fill in the rest of the conversions.
8661 unsigned NumArgsInProto = Proto->getNumArgs();
8662 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008663 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008664 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008665 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008666 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008667 /*InOverloadResolution=*/true,
8668 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008669 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008670 // Store the FixIt in the candidate if it exists.
8671 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008672 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008673 }
John McCallfe796dd2010-01-23 05:17:32 +00008674 else
8675 Cand->Conversions[ConvIdx].setEllipsis();
8676 }
8677}
8678
John McCalld3224162010-01-08 00:58:21 +00008679} // end anonymous namespace
8680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008681/// PrintOverloadCandidates - When overload resolution fails, prints
8682/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008683/// set.
John McCall5c32be02010-08-24 20:38:10 +00008684void OverloadCandidateSet::NoteCandidates(Sema &S,
8685 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008686 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008687 const char *Opc,
8688 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008689 // Sort the candidates by viability and position. Sorting directly would
8690 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008691 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008692 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8693 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008694 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008695 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008696 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008697 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008698 if (Cand->Function || Cand->IsSurrogate)
8699 Cands.push_back(Cand);
8700 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8701 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008702 }
8703 }
8704
John McCallad2587a2010-01-12 00:48:53 +00008705 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008706 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008707
John McCall0d1da222010-01-12 00:44:57 +00008708 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008709
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008710 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008711 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8712 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008713 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008714 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8715 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008716
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008717 // Set an arbitrary limit on the number of candidate functions we'll spam
8718 // the user with. FIXME: This limit should depend on details of the
8719 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008720 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008721 break;
8722 }
8723 ++CandsShown;
8724
John McCalld3224162010-01-08 00:58:21 +00008725 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008726 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008727 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008728 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008729 else {
8730 assert(Cand->Viable &&
8731 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008732 // Generally we only see ambiguities including viable builtin
8733 // operators if overload resolution got screwed up by an
8734 // ambiguous user-defined conversion.
8735 //
8736 // FIXME: It's quite possible for different conversions to see
8737 // different ambiguities, though.
8738 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008739 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008740 ReportedAmbiguousConversions = true;
8741 }
John McCalld3224162010-01-08 00:58:21 +00008742
John McCall0d1da222010-01-12 00:44:57 +00008743 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008744 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008745 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008746 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008747
8748 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008749 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008750}
8751
Douglas Gregorb491ed32011-02-19 21:32:49 +00008752// [PossiblyAFunctionType] --> [Return]
8753// NonFunctionType --> NonFunctionType
8754// R (A) --> R(A)
8755// R (*)(A) --> R (A)
8756// R (&)(A) --> R (A)
8757// R (S::*)(A) --> R (A)
8758QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8759 QualType Ret = PossiblyAFunctionType;
8760 if (const PointerType *ToTypePtr =
8761 PossiblyAFunctionType->getAs<PointerType>())
8762 Ret = ToTypePtr->getPointeeType();
8763 else if (const ReferenceType *ToTypeRef =
8764 PossiblyAFunctionType->getAs<ReferenceType>())
8765 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008766 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008767 PossiblyAFunctionType->getAs<MemberPointerType>())
8768 Ret = MemTypePtr->getPointeeType();
8769 Ret =
8770 Context.getCanonicalType(Ret).getUnqualifiedType();
8771 return Ret;
8772}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008773
Douglas Gregorb491ed32011-02-19 21:32:49 +00008774// A helper class to help with address of function resolution
8775// - allows us to avoid passing around all those ugly parameters
8776class AddressOfFunctionResolver
8777{
8778 Sema& S;
8779 Expr* SourceExpr;
8780 const QualType& TargetType;
8781 QualType TargetFunctionType; // Extracted function type from target type
8782
8783 bool Complain;
8784 //DeclAccessPair& ResultFunctionAccessPair;
8785 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008786
Douglas Gregorb491ed32011-02-19 21:32:49 +00008787 bool TargetTypeIsNonStaticMemberFunction;
8788 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008789
Douglas Gregorb491ed32011-02-19 21:32:49 +00008790 OverloadExpr::FindResult OvlExprInfo;
8791 OverloadExpr *OvlExpr;
8792 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008793 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008794
Douglas Gregorb491ed32011-02-19 21:32:49 +00008795public:
8796 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8797 const QualType& TargetType, bool Complain)
8798 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8799 Complain(Complain), Context(S.getASTContext()),
8800 TargetTypeIsNonStaticMemberFunction(
8801 !!TargetType->getAs<MemberPointerType>()),
8802 FoundNonTemplateFunction(false),
8803 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8804 OvlExpr(OvlExprInfo.Expression)
8805 {
8806 ExtractUnqualifiedFunctionTypeFromTargetType();
8807
8808 if (!TargetFunctionType->isFunctionType()) {
8809 if (OvlExpr->hasExplicitTemplateArgs()) {
8810 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008811 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008812 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008813
8814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8815 if (!Method->isStatic()) {
8816 // If the target type is a non-function type and the function
8817 // found is a non-static member function, pretend as if that was
8818 // the target, it's the only possible type to end up with.
8819 TargetTypeIsNonStaticMemberFunction = true;
8820
8821 // And skip adding the function if its not in the proper form.
8822 // We'll diagnose this due to an empty set of functions.
8823 if (!OvlExprInfo.HasFormOfMemberPointer)
8824 return;
8825 }
8826 }
8827
Douglas Gregorb491ed32011-02-19 21:32:49 +00008828 Matches.push_back(std::make_pair(dap,Fn));
8829 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008830 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008831 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008832 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008833
8834 if (OvlExpr->hasExplicitTemplateArgs())
8835 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008836
Douglas Gregorb491ed32011-02-19 21:32:49 +00008837 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8838 // C++ [over.over]p4:
8839 // If more than one function is selected, [...]
8840 if (Matches.size() > 1) {
8841 if (FoundNonTemplateFunction)
8842 EliminateAllTemplateMatches();
8843 else
8844 EliminateAllExceptMostSpecializedTemplate();
8845 }
8846 }
8847 }
8848
8849private:
8850 bool isTargetTypeAFunction() const {
8851 return TargetFunctionType->isFunctionType();
8852 }
8853
8854 // [ToType] [Return]
8855
8856 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8857 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8858 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8859 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8860 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8861 }
8862
8863 // return true if any matching specializations were found
8864 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8865 const DeclAccessPair& CurAccessFunPair) {
8866 if (CXXMethodDecl *Method
8867 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8868 // Skip non-static function templates when converting to pointer, and
8869 // static when converting to member pointer.
8870 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8871 return false;
8872 }
8873 else if (TargetTypeIsNonStaticMemberFunction)
8874 return false;
8875
8876 // C++ [over.over]p2:
8877 // If the name is a function template, template argument deduction is
8878 // done (14.8.2.2), and if the argument deduction succeeds, the
8879 // resulting template argument list is used to generate a single
8880 // function template specialization, which is added to the set of
8881 // overloaded functions considered.
8882 FunctionDecl *Specialization = 0;
8883 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8884 if (Sema::TemplateDeductionResult Result
8885 = S.DeduceTemplateArguments(FunctionTemplate,
8886 &OvlExplicitTemplateArgs,
8887 TargetFunctionType, Specialization,
8888 Info)) {
8889 // FIXME: make a note of the failed deduction for diagnostics.
8890 (void)Result;
8891 return false;
8892 }
8893
8894 // Template argument deduction ensures that we have an exact match.
8895 // This function template specicalization works.
8896 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8897 assert(TargetFunctionType
8898 == Context.getCanonicalType(Specialization->getType()));
8899 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8900 return true;
8901 }
8902
8903 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8904 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008906 // Skip non-static functions when converting to pointer, and static
8907 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008908 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8909 return false;
8910 }
8911 else if (TargetTypeIsNonStaticMemberFunction)
8912 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008913
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008914 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008915 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008916 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8917 if (S.CheckCUDATarget(Caller, FunDecl))
8918 return false;
8919
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008920 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008921 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8922 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008923 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8924 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008925 Matches.push_back(std::make_pair(CurAccessFunPair,
8926 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008927 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008928 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008929 }
Mike Stump11289f42009-09-09 15:08:12 +00008930 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008931
8932 return false;
8933 }
8934
8935 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8936 bool Ret = false;
8937
8938 // If the overload expression doesn't have the form of a pointer to
8939 // member, don't try to convert it to a pointer-to-member type.
8940 if (IsInvalidFormOfPointerToMemberFunction())
8941 return false;
8942
8943 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8944 E = OvlExpr->decls_end();
8945 I != E; ++I) {
8946 // Look through any using declarations to find the underlying function.
8947 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8948
8949 // C++ [over.over]p3:
8950 // Non-member functions and static member functions match
8951 // targets of type "pointer-to-function" or "reference-to-function."
8952 // Nonstatic member functions match targets of
8953 // type "pointer-to-member-function."
8954 // Note that according to DR 247, the containing class does not matter.
8955 if (FunctionTemplateDecl *FunctionTemplate
8956 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8957 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8958 Ret = true;
8959 }
8960 // If we have explicit template arguments supplied, skip non-templates.
8961 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8962 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8963 Ret = true;
8964 }
8965 assert(Ret || Matches.empty());
8966 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008967 }
8968
Douglas Gregorb491ed32011-02-19 21:32:49 +00008969 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008970 // [...] and any given function template specialization F1 is
8971 // eliminated if the set contains a second function template
8972 // specialization whose function template is more specialized
8973 // than the function template of F1 according to the partial
8974 // ordering rules of 14.5.5.2.
8975
8976 // The algorithm specified above is quadratic. We instead use a
8977 // two-pass algorithm (similar to the one used to identify the
8978 // best viable function in an overload set) that identifies the
8979 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008980
8981 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8982 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8983 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008984
John McCall58cc69d2010-01-27 01:50:18 +00008985 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008986 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8987 TPOC_Other, 0, SourceExpr->getLocStart(),
8988 S.PDiag(),
8989 S.PDiag(diag::err_addr_ovl_ambiguous)
8990 << Matches[0].second->getDeclName(),
8991 S.PDiag(diag::note_ovl_candidate)
8992 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008993 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008994
Douglas Gregorb491ed32011-02-19 21:32:49 +00008995 if (Result != MatchesCopy.end()) {
8996 // Make it the first and only element
8997 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8998 Matches[0].second = cast<FunctionDecl>(*Result);
8999 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009000 }
9001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009002
Douglas Gregorb491ed32011-02-19 21:32:49 +00009003 void EliminateAllTemplateMatches() {
9004 // [...] any function template specializations in the set are
9005 // eliminated if the set also contains a non-template function, [...]
9006 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9007 if (Matches[I].second->getPrimaryTemplate() == 0)
9008 ++I;
9009 else {
9010 Matches[I] = Matches[--N];
9011 Matches.set_size(N);
9012 }
9013 }
9014 }
9015
9016public:
9017 void ComplainNoMatchesFound() const {
9018 assert(Matches.empty());
9019 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9020 << OvlExpr->getName() << TargetFunctionType
9021 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009022 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009023 }
9024
9025 bool IsInvalidFormOfPointerToMemberFunction() const {
9026 return TargetTypeIsNonStaticMemberFunction &&
9027 !OvlExprInfo.HasFormOfMemberPointer;
9028 }
9029
9030 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9031 // TODO: Should we condition this on whether any functions might
9032 // have matched, or is it more appropriate to do that in callers?
9033 // TODO: a fixit wouldn't hurt.
9034 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9035 << TargetType << OvlExpr->getSourceRange();
9036 }
9037
9038 void ComplainOfInvalidConversion() const {
9039 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9040 << OvlExpr->getName() << TargetType;
9041 }
9042
9043 void ComplainMultipleMatchesFound() const {
9044 assert(Matches.size() > 1);
9045 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9046 << OvlExpr->getName()
9047 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009048 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009049 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009050
9051 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9052
Douglas Gregorb491ed32011-02-19 21:32:49 +00009053 int getNumMatches() const { return Matches.size(); }
9054
9055 FunctionDecl* getMatchingFunctionDecl() const {
9056 if (Matches.size() != 1) return 0;
9057 return Matches[0].second;
9058 }
9059
9060 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9061 if (Matches.size() != 1) return 0;
9062 return &Matches[0].first;
9063 }
9064};
9065
9066/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9067/// an overloaded function (C++ [over.over]), where @p From is an
9068/// expression with overloaded function type and @p ToType is the type
9069/// we're trying to resolve to. For example:
9070///
9071/// @code
9072/// int f(double);
9073/// int f(int);
9074///
9075/// int (*pfd)(double) = f; // selects f(double)
9076/// @endcode
9077///
9078/// This routine returns the resulting FunctionDecl if it could be
9079/// resolved, and NULL otherwise. When @p Complain is true, this
9080/// routine will emit diagnostics if there is an error.
9081FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009082Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9083 QualType TargetType,
9084 bool Complain,
9085 DeclAccessPair &FoundResult,
9086 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009087 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009088
9089 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9090 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009091 int NumMatches = Resolver.getNumMatches();
9092 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009093 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009094 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9095 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9096 else
9097 Resolver.ComplainNoMatchesFound();
9098 }
9099 else if (NumMatches > 1 && Complain)
9100 Resolver.ComplainMultipleMatchesFound();
9101 else if (NumMatches == 1) {
9102 Fn = Resolver.getMatchingFunctionDecl();
9103 assert(Fn);
9104 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009105 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009106 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009107 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009108 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009109
9110 if (pHadMultipleCandidates)
9111 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009112 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009113}
9114
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009115/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009116/// resolve that overloaded function expression down to a single function.
9117///
9118/// This routine can only resolve template-ids that refer to a single function
9119/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009121/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009122FunctionDecl *
9123Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9124 bool Complain,
9125 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009126 // C++ [over.over]p1:
9127 // [...] [Note: any redundant set of parentheses surrounding the
9128 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009129 // C++ [over.over]p1:
9130 // [...] The overloaded function name can be preceded by the &
9131 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009132
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009133 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009134 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009135 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009136
9137 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009138 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009139
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009140 // Look through all of the overloaded functions, searching for one
9141 // whose type matches exactly.
9142 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009143 for (UnresolvedSetIterator I = ovl->decls_begin(),
9144 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009145 // C++0x [temp.arg.explicit]p3:
9146 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009147 // where deduction is not done, if a template argument list is
9148 // specified and it, along with any default template arguments,
9149 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009150 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009151 FunctionTemplateDecl *FunctionTemplate
9152 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009153
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009154 // C++ [over.over]p2:
9155 // If the name is a function template, template argument deduction is
9156 // done (14.8.2.2), and if the argument deduction succeeds, the
9157 // resulting template argument list is used to generate a single
9158 // function template specialization, which is added to the set of
9159 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009160 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009161 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009162 if (TemplateDeductionResult Result
9163 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9164 Specialization, Info)) {
9165 // FIXME: make a note of the failed deduction for diagnostics.
9166 (void)Result;
9167 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009168 }
9169
John McCall0009fcc2011-04-26 20:42:42 +00009170 assert(Specialization && "no specialization and no error?");
9171
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009172 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009173 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009174 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009175 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9176 << ovl->getName();
9177 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009178 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009179 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009180 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009181
John McCall0009fcc2011-04-26 20:42:42 +00009182 Matched = Specialization;
9183 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009185
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009186 return Matched;
9187}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009188
Douglas Gregor1beec452011-03-12 01:48:56 +00009189
9190
9191
John McCall50a2c2c2011-10-11 23:14:30 +00009192// Resolve and fix an overloaded expression that can be resolved
9193// because it identifies a single function template specialization.
9194//
Douglas Gregor1beec452011-03-12 01:48:56 +00009195// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009196//
9197// Return true if it was logically possible to so resolve the
9198// expression, regardless of whether or not it succeeded. Always
9199// returns true if 'complain' is set.
9200bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9201 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9202 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009203 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009204 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009205 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009206
John McCall50a2c2c2011-10-11 23:14:30 +00009207 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009208
John McCall0009fcc2011-04-26 20:42:42 +00009209 DeclAccessPair found;
9210 ExprResult SingleFunctionExpression;
9211 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9212 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009213 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009214 SrcExpr = ExprError();
9215 return true;
9216 }
John McCall0009fcc2011-04-26 20:42:42 +00009217
9218 // It is only correct to resolve to an instance method if we're
9219 // resolving a form that's permitted to be a pointer to member.
9220 // Otherwise we'll end up making a bound member expression, which
9221 // is illegal in all the contexts we resolve like this.
9222 if (!ovl.HasFormOfMemberPointer &&
9223 isa<CXXMethodDecl>(fn) &&
9224 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009225 if (!complain) return false;
9226
9227 Diag(ovl.Expression->getExprLoc(),
9228 diag::err_bound_member_function)
9229 << 0 << ovl.Expression->getSourceRange();
9230
9231 // TODO: I believe we only end up here if there's a mix of
9232 // static and non-static candidates (otherwise the expression
9233 // would have 'bound member' type, not 'overload' type).
9234 // Ideally we would note which candidate was chosen and why
9235 // the static candidates were rejected.
9236 SrcExpr = ExprError();
9237 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009238 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009239
John McCall0009fcc2011-04-26 20:42:42 +00009240 // Fix the expresion to refer to 'fn'.
9241 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009242 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009243
9244 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009245 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009246 SingleFunctionExpression =
9247 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009248 if (SingleFunctionExpression.isInvalid()) {
9249 SrcExpr = ExprError();
9250 return true;
9251 }
9252 }
John McCall0009fcc2011-04-26 20:42:42 +00009253 }
9254
9255 if (!SingleFunctionExpression.isUsable()) {
9256 if (complain) {
9257 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9258 << ovl.Expression->getName()
9259 << DestTypeForComplaining
9260 << OpRangeForComplaining
9261 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009262 NoteAllOverloadCandidates(SrcExpr.get());
9263
9264 SrcExpr = ExprError();
9265 return true;
9266 }
9267
9268 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009269 }
9270
John McCall50a2c2c2011-10-11 23:14:30 +00009271 SrcExpr = SingleFunctionExpression;
9272 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009273}
9274
Douglas Gregorcabea402009-09-22 15:41:20 +00009275/// \brief Add a single candidate to the overload set.
9276static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009277 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009278 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009279 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009280 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009281 bool PartialOverloading,
9282 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009283 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009284 if (isa<UsingShadowDecl>(Callee))
9285 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9286
Douglas Gregorcabea402009-09-22 15:41:20 +00009287 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009288 if (ExplicitTemplateArgs) {
9289 assert(!KnownValid && "Explicit template arguments?");
9290 return;
9291 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009292 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9293 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009294 return;
John McCalld14a8642009-11-21 08:51:07 +00009295 }
9296
9297 if (FunctionTemplateDecl *FuncTemplate
9298 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009299 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009300 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009301 return;
9302 }
9303
Richard Smith95ce4f62011-06-26 22:19:54 +00009304 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009305}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009306
Douglas Gregorcabea402009-09-22 15:41:20 +00009307/// \brief Add the overload candidates named by callee and/or found by argument
9308/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009309void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009310 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009311 OverloadCandidateSet &CandidateSet,
9312 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009313
9314#ifndef NDEBUG
9315 // Verify that ArgumentDependentLookup is consistent with the rules
9316 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009317 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009318 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9319 // and let Y be the lookup set produced by argument dependent
9320 // lookup (defined as follows). If X contains
9321 //
9322 // -- a declaration of a class member, or
9323 //
9324 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009325 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009326 //
9327 // -- a declaration that is neither a function or a function
9328 // template
9329 //
9330 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009331
John McCall57500772009-12-16 12:17:52 +00009332 if (ULE->requiresADL()) {
9333 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9334 E = ULE->decls_end(); I != E; ++I) {
9335 assert(!(*I)->getDeclContext()->isRecord());
9336 assert(isa<UsingShadowDecl>(*I) ||
9337 !(*I)->getDeclContext()->isFunctionOrMethod());
9338 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009339 }
9340 }
9341#endif
9342
John McCall57500772009-12-16 12:17:52 +00009343 // It would be nice to avoid this copy.
9344 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009345 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009346 if (ULE->hasExplicitTemplateArgs()) {
9347 ULE->copyTemplateArgumentsInto(TABuffer);
9348 ExplicitTemplateArgs = &TABuffer;
9349 }
9350
9351 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9352 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009353 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9354 CandidateSet, PartialOverloading,
9355 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009356
John McCall57500772009-12-16 12:17:52 +00009357 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009358 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009359 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009360 Args, ExplicitTemplateArgs,
9361 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009362 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009363}
John McCalld681c392009-12-16 08:11:27 +00009364
Richard Smith998a5912011-06-05 22:42:48 +00009365/// Attempt to recover from an ill-formed use of a non-dependent name in a
9366/// template, where the non-dependent name was declared after the template
9367/// was defined. This is common in code written for a compilers which do not
9368/// correctly implement two-stage name lookup.
9369///
9370/// Returns true if a viable candidate was found and a diagnostic was issued.
9371static bool
9372DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9373 const CXXScopeSpec &SS, LookupResult &R,
9374 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009375 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009376 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9377 return false;
9378
9379 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009380 if (DC->isTransparentContext())
9381 continue;
9382
Richard Smith998a5912011-06-05 22:42:48 +00009383 SemaRef.LookupQualifiedName(R, DC);
9384
9385 if (!R.empty()) {
9386 R.suppressDiagnostics();
9387
9388 if (isa<CXXRecordDecl>(DC)) {
9389 // Don't diagnose names we find in classes; we get much better
9390 // diagnostics for these from DiagnoseEmptyLookup.
9391 R.clear();
9392 return false;
9393 }
9394
9395 OverloadCandidateSet Candidates(FnLoc);
9396 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9397 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009398 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009399 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009400
9401 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009402 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009403 // No viable functions. Don't bother the user with notes for functions
9404 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009405 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009406 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009407 }
Richard Smith998a5912011-06-05 22:42:48 +00009408
9409 // Find the namespaces where ADL would have looked, and suggest
9410 // declaring the function there instead.
9411 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9412 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009413 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smith998a5912011-06-05 22:42:48 +00009414 AssociatedNamespaces,
9415 AssociatedClasses);
9416 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009417 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009418 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009419 for (Sema::AssociatedNamespaceSet::iterator
9420 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009421 end = AssociatedNamespaces.end(); it != end; ++it) {
9422 if (!Std->Encloses(*it))
9423 SuggestedNamespaces.insert(*it);
9424 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009425 } else {
9426 // Lacking the 'std::' namespace, use all of the associated namespaces.
9427 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009428 }
9429
9430 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9431 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009432 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009433 SemaRef.Diag(Best->Function->getLocation(),
9434 diag::note_not_found_by_two_phase_lookup)
9435 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009436 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009437 SemaRef.Diag(Best->Function->getLocation(),
9438 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009439 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009440 } else {
9441 // FIXME: It would be useful to list the associated namespaces here,
9442 // but the diagnostics infrastructure doesn't provide a way to produce
9443 // a localized representation of a list of items.
9444 SemaRef.Diag(Best->Function->getLocation(),
9445 diag::note_not_found_by_two_phase_lookup)
9446 << R.getLookupName() << 2;
9447 }
9448
9449 // Try to recover by calling this function.
9450 return true;
9451 }
9452
9453 R.clear();
9454 }
9455
9456 return false;
9457}
9458
9459/// Attempt to recover from ill-formed use of a non-dependent operator in a
9460/// template, where the non-dependent operator was declared after the template
9461/// was defined.
9462///
9463/// Returns true if a viable candidate was found and a diagnostic was issued.
9464static bool
9465DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9466 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009467 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009468 DeclarationName OpName =
9469 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9470 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9471 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009472 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009473}
9474
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009475namespace {
9476// Callback to limit the allowed keywords and to only accept typo corrections
9477// that are keywords or whose decls refer to functions (or template functions)
9478// that accept the given number of arguments.
9479class RecoveryCallCCC : public CorrectionCandidateCallback {
9480 public:
9481 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9482 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009483 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009484 WantRemainingKeywords = false;
9485 }
9486
9487 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9488 if (!candidate.getCorrectionDecl())
9489 return candidate.isKeyword();
9490
9491 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9492 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9493 FunctionDecl *FD = 0;
9494 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9495 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9496 FD = FTD->getTemplatedDecl();
9497 if (!HasExplicitTemplateArgs && !FD) {
9498 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9499 // If the Decl is neither a function nor a template function,
9500 // determine if it is a pointer or reference to a function. If so,
9501 // check against the number of arguments expected for the pointee.
9502 QualType ValType = cast<ValueDecl>(ND)->getType();
9503 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9504 ValType = ValType->getPointeeType();
9505 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9506 if (FPT->getNumArgs() == NumArgs)
9507 return true;
9508 }
9509 }
9510 if (FD && FD->getNumParams() >= NumArgs &&
9511 FD->getMinRequiredArguments() <= NumArgs)
9512 return true;
9513 }
9514 return false;
9515 }
9516
9517 private:
9518 unsigned NumArgs;
9519 bool HasExplicitTemplateArgs;
9520};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009521
9522// Callback that effectively disabled typo correction
9523class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9524 public:
9525 NoTypoCorrectionCCC() {
9526 WantTypeSpecifiers = false;
9527 WantExpressionKeywords = false;
9528 WantCXXNamedCasts = false;
9529 WantRemainingKeywords = false;
9530 }
9531
9532 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9533 return false;
9534 }
9535};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009536}
9537
John McCalld681c392009-12-16 08:11:27 +00009538/// Attempts to recover from a call where no functions were found.
9539///
9540/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009541static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009542BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009543 UnresolvedLookupExpr *ULE,
9544 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009545 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009546 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009547 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009548
9549 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009550 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009551 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009552
John McCall57500772009-12-16 12:17:52 +00009553 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009554 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009555 if (ULE->hasExplicitTemplateArgs()) {
9556 ULE->copyTemplateArgumentsInto(TABuffer);
9557 ExplicitTemplateArgs = &TABuffer;
9558 }
9559
John McCalld681c392009-12-16 08:11:27 +00009560 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9561 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009562 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009563 NoTypoCorrectionCCC RejectAll;
9564 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9565 (CorrectionCandidateCallback*)&Validator :
9566 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009567 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009568 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009569 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009570 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009571 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009572 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009573
John McCall57500772009-12-16 12:17:52 +00009574 assert(!R.empty() && "lookup results empty despite recovery");
9575
9576 // Build an implicit member call if appropriate. Just drop the
9577 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009578 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009579 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009580 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9581 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009582 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009583 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009584 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009585 else
9586 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9587
9588 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009589 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009590
9591 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009592 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009593 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009594 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009595 MultiExprArg(Args.data(), Args.size()),
9596 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009597}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009598
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009599/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00009600/// (which eventually refers to the declaration Func) and the call
9601/// arguments Args/NumArgs, attempt to resolve the function call down
9602/// to a specific function. If overload resolution succeeds, returns
9603/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00009604/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009605/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00009606ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009607Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00009608 SourceLocation LParenLoc,
9609 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00009610 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009611 Expr *ExecConfig,
9612 bool AllowTypoCorrection) {
John McCall57500772009-12-16 12:17:52 +00009613#ifndef NDEBUG
9614 if (ULE->requiresADL()) {
9615 // To do ADL, we must have found an unqualified name.
9616 assert(!ULE->getQualifier() && "qualified name with ADL");
9617
9618 // We don't perform ADL for implicit declarations of builtins.
9619 // Verify that this was correctly set up.
9620 FunctionDecl *F;
9621 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9622 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9623 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009624 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009625
John McCall57500772009-12-16 12:17:52 +00009626 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009627 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009628 } else
9629 assert(!ULE->isStdAssociatedNamespace() &&
9630 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009631#endif
9632
John McCall4124c492011-10-17 18:40:02 +00009633 UnbridgedCastsSet UnbridgedCasts;
9634 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9635 return ExprError();
9636
John McCallbc077cf2010-02-08 23:07:23 +00009637 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009638
John McCall57500772009-12-16 12:17:52 +00009639 // Add the functions denoted by the callee to the set of candidate
9640 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009641 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9642 CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009643
9644 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009645 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9646 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00009647 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009648 // In Microsoft mode, if we are inside a template class member function then
9649 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009650 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009651 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009652 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009653 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009654 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9655 Context.DependentTy, VK_RValue,
9656 RParenLoc);
9657 CE->setTypeDependent(true);
9658 return Owned(CE);
9659 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009660 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9661 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009662 RParenLoc, /*EmptyLookup=*/true,
9663 AllowTypoCorrection);
Francois Pichetbcf64712011-09-07 00:14:57 +00009664 }
John McCalld681c392009-12-16 08:11:27 +00009665
John McCall4124c492011-10-17 18:40:02 +00009666 UnbridgedCasts.restore();
9667
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009668 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009669 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00009670 case OR_Success: {
9671 FunctionDecl *FDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009672 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00009673 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00009674 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00009675 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00009676 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9677 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009678 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009679
Richard Smith998a5912011-06-05 22:42:48 +00009680 case OR_No_Viable_Function: {
9681 // Try to recover by looking for viable functions which the user might
9682 // have meant to call.
9683 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009684 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9685 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009686 /*EmptyLookup=*/false,
9687 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009688 if (!Recovery.isInvalid())
9689 return Recovery;
9690
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009691 Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009692 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009693 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009694 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9695 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009696 break;
Richard Smith998a5912011-06-05 22:42:48 +00009697 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009698
9699 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009700 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009701 << ULE->getName() << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009702 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9703 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009704 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009705
9706 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009707 {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009708 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009709 << Best->Function->isDeleted()
9710 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009711 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009712 << Fn->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009713 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9714 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009715
9716 // We emitted an error for the unvailable/deleted function call but keep
9717 // the call in the AST.
9718 FunctionDecl *FDecl = Best->Function;
9719 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9720 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9721 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00009722 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009723 }
9724
Douglas Gregorb412e172010-07-25 18:17:45 +00009725 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009726 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009727}
9728
John McCall4c4c1df2010-01-26 03:27:55 +00009729static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009730 return Functions.size() > 1 ||
9731 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9732}
9733
Douglas Gregor084d8552009-03-13 23:49:33 +00009734/// \brief Create a unary operation that may resolve to an overloaded
9735/// operator.
9736///
9737/// \param OpLoc The location of the operator itself (e.g., '*').
9738///
9739/// \param OpcIn The UnaryOperator::Opcode that describes this
9740/// operator.
9741///
9742/// \param Functions The set of non-member functions that will be
9743/// considered by overload resolution. The caller needs to build this
9744/// set based on the context using, e.g.,
9745/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9746/// set should not contain any member functions; those will be added
9747/// by CreateOverloadedUnaryOp().
9748///
9749/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009750ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009751Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9752 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009753 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009754 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009755
9756 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9757 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009759 // TODO: provide better source location info.
9760 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009761
John McCall4124c492011-10-17 18:40:02 +00009762 if (checkPlaceholderForOverload(*this, Input))
9763 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009764
Douglas Gregor084d8552009-03-13 23:49:33 +00009765 Expr *Args[2] = { Input, 0 };
9766 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009767
Douglas Gregor084d8552009-03-13 23:49:33 +00009768 // For post-increment and post-decrement, add the implicit '0' as
9769 // the second argument, so that we know this is a post-increment or
9770 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009771 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009772 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009773 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9774 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009775 NumArgs = 2;
9776 }
9777
9778 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009779 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009780 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009781 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009782 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009783 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009784 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009785
John McCall58cc69d2010-01-27 01:50:18 +00009786 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009787 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009788 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009789 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009790 /*ADL*/ true, IsOverloaded(Fns),
9791 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009792 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009793 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009794 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009795 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009796 OpLoc));
9797 }
9798
9799 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009800 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009801
9802 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009803 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9804 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009805
9806 // Add operator candidates that are member functions.
9807 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9808
John McCall4c4c1df2010-01-26 03:27:55 +00009809 // Add candidates from ADL.
9810 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009811 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009812 /*ExplicitTemplateArgs*/ 0,
9813 CandidateSet);
9814
Douglas Gregor084d8552009-03-13 23:49:33 +00009815 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009816 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009817
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009818 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9819
Douglas Gregor084d8552009-03-13 23:49:33 +00009820 // Perform overload resolution.
9821 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009822 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009823 case OR_Success: {
9824 // We found a built-in operator or an overloaded operator.
9825 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009826
Douglas Gregor084d8552009-03-13 23:49:33 +00009827 if (FnDecl) {
9828 // We matched an overloaded operator. Build a call to that
9829 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009830
Eli Friedmanfa0df832012-02-02 03:46:19 +00009831 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009832
Douglas Gregor084d8552009-03-13 23:49:33 +00009833 // Convert the arguments.
9834 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009835 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009836
John Wiegley01296292011-04-08 18:41:53 +00009837 ExprResult InputRes =
9838 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9839 Best->FoundDecl, Method);
9840 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009841 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009842 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009843 } else {
9844 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009845 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009846 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009847 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009848 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009849 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009850 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009851 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009852 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009853 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009854 }
9855
John McCall4fa0d5f2010-05-06 18:15:07 +00009856 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9857
John McCall7decc9e2010-11-18 06:31:45 +00009858 // Determine the result type.
9859 QualType ResultTy = FnDecl->getResultType();
9860 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9861 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009862
Douglas Gregor084d8552009-03-13 23:49:33 +00009863 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009864 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +00009865 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009866 if (FnExpr.isInvalid())
9867 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009868
Eli Friedman030eee42009-11-18 03:58:17 +00009869 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009870 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009871 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009872 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009873
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009874 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009875 FnDecl))
9876 return ExprError();
9877
John McCallb268a282010-08-23 23:25:46 +00009878 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009879 } else {
9880 // We matched a built-in operator. Convert the arguments, then
9881 // break out so that we will build the appropriate built-in
9882 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009883 ExprResult InputRes =
9884 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9885 Best->Conversions[0], AA_Passing);
9886 if (InputRes.isInvalid())
9887 return ExprError();
9888 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009889 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009890 }
John Wiegley01296292011-04-08 18:41:53 +00009891 }
9892
9893 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009894 // This is an erroneous use of an operator which can be overloaded by
9895 // a non-member function. Check for non-member operators which were
9896 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009897 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9898 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +00009899 // FIXME: Recover by calling the found function.
9900 return ExprError();
9901
John Wiegley01296292011-04-08 18:41:53 +00009902 // No viable function; fall through to handling this as a
9903 // built-in operator, which will produce an error message for us.
9904 break;
9905
9906 case OR_Ambiguous:
9907 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9908 << UnaryOperator::getOpcodeStr(Opc)
9909 << Input->getType()
9910 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009911 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9912 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +00009913 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9914 return ExprError();
9915
9916 case OR_Deleted:
9917 Diag(OpLoc, diag::err_ovl_deleted_oper)
9918 << Best->Function->isDeleted()
9919 << UnaryOperator::getOpcodeStr(Opc)
9920 << getDeletedOrUnavailableSuffix(Best->Function)
9921 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009922 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9923 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009924 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009925 return ExprError();
9926 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009927
9928 // Either we found no viable overloaded operator or we matched a
9929 // built-in operator. In either case, fall through to trying to
9930 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009931 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009932}
9933
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009934/// \brief Create a binary operation that may resolve to an overloaded
9935/// operator.
9936///
9937/// \param OpLoc The location of the operator itself (e.g., '+').
9938///
9939/// \param OpcIn The BinaryOperator::Opcode that describes this
9940/// operator.
9941///
9942/// \param Functions The set of non-member functions that will be
9943/// considered by overload resolution. The caller needs to build this
9944/// set based on the context using, e.g.,
9945/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9946/// set should not contain any member functions; those will be added
9947/// by CreateOverloadedBinOp().
9948///
9949/// \param LHS Left-hand argument.
9950/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009951ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009952Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009953 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009954 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009955 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009956 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009957 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009958
9959 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9960 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9961 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9962
9963 // If either side is type-dependent, create an appropriate dependent
9964 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009965 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009966 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009967 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009968 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009969 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009970 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009971 Context.DependentTy,
9972 VK_RValue, OK_Ordinary,
9973 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009974
Douglas Gregor5287f092009-11-05 00:51:44 +00009975 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9976 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009977 VK_LValue,
9978 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009979 Context.DependentTy,
9980 Context.DependentTy,
9981 OpLoc));
9982 }
John McCall4c4c1df2010-01-26 03:27:55 +00009983
9984 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009985 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009986 // TODO: provide better source location info in DNLoc component.
9987 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009988 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009989 = UnresolvedLookupExpr::Create(Context, NamingClass,
9990 NestedNameSpecifierLoc(), OpNameInfo,
9991 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009992 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009993 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009994 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009995 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009996 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009997 OpLoc));
9998 }
9999
John McCall4124c492011-10-17 18:40:02 +000010000 // Always do placeholder-like conversions on the RHS.
10001 if (checkPlaceholderForOverload(*this, Args[1]))
10002 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010003
John McCall526ab472011-10-25 17:37:35 +000010004 // Do placeholder-like conversion on the LHS; note that we should
10005 // not get here with a PseudoObject LHS.
10006 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010007 if (checkPlaceholderForOverload(*this, Args[0]))
10008 return ExprError();
10009
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010010 // If this is the assignment operator, we only perform overload resolution
10011 // if the left-hand side is a class or enumeration type. This is actually
10012 // a hack. The standard requires that we do overload resolution between the
10013 // various built-in candidates, but as DR507 points out, this can lead to
10014 // problems. So we do it this way, which pretty much follows what GCC does.
10015 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010016 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010017 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010018
John McCalle26a8722010-12-04 08:14:53 +000010019 // If this is the .* operator, which is not overloadable, just
10020 // create a built-in binary operator.
10021 if (Opc == BO_PtrMemD)
10022 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10023
Douglas Gregor084d8552009-03-13 23:49:33 +000010024 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010025 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010026
10027 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010028 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010029
10030 // Add operator candidates that are member functions.
10031 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10032
John McCall4c4c1df2010-01-26 03:27:55 +000010033 // Add candidates from ADL.
10034 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010035 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010036 /*ExplicitTemplateArgs*/ 0,
10037 CandidateSet);
10038
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010039 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010040 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010041
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010042 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10043
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010044 // Perform overload resolution.
10045 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010046 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010047 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010048 // We found a built-in operator or an overloaded operator.
10049 FunctionDecl *FnDecl = Best->Function;
10050
10051 if (FnDecl) {
10052 // We matched an overloaded operator. Build a call to that
10053 // operator.
10054
Eli Friedmanfa0df832012-02-02 03:46:19 +000010055 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010056
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010057 // Convert the arguments.
10058 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010059 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010060 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010061
Chandler Carruth8e543b32010-12-12 08:17:55 +000010062 ExprResult Arg1 =
10063 PerformCopyInitialization(
10064 InitializedEntity::InitializeParameter(Context,
10065 FnDecl->getParamDecl(0)),
10066 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010067 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010068 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010069
John Wiegley01296292011-04-08 18:41:53 +000010070 ExprResult Arg0 =
10071 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10072 Best->FoundDecl, Method);
10073 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010074 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010075 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010076 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010077 } else {
10078 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010079 ExprResult Arg0 = PerformCopyInitialization(
10080 InitializedEntity::InitializeParameter(Context,
10081 FnDecl->getParamDecl(0)),
10082 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010083 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010084 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010085
Chandler Carruth8e543b32010-12-12 08:17:55 +000010086 ExprResult Arg1 =
10087 PerformCopyInitialization(
10088 InitializedEntity::InitializeParameter(Context,
10089 FnDecl->getParamDecl(1)),
10090 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010091 if (Arg1.isInvalid())
10092 return ExprError();
10093 Args[0] = LHS = Arg0.takeAs<Expr>();
10094 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010095 }
10096
John McCall4fa0d5f2010-05-06 18:15:07 +000010097 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10098
John McCall7decc9e2010-11-18 06:31:45 +000010099 // Determine the result type.
10100 QualType ResultTy = FnDecl->getResultType();
10101 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10102 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010103
10104 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010105 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10106 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010107 if (FnExpr.isInvalid())
10108 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010109
John McCallb268a282010-08-23 23:25:46 +000010110 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010111 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010112 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010113
10114 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010115 FnDecl))
10116 return ExprError();
10117
John McCallb268a282010-08-23 23:25:46 +000010118 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010119 } else {
10120 // We matched a built-in operator. Convert the arguments, then
10121 // break out so that we will build the appropriate built-in
10122 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010123 ExprResult ArgsRes0 =
10124 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10125 Best->Conversions[0], AA_Passing);
10126 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010127 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010128 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010129
John Wiegley01296292011-04-08 18:41:53 +000010130 ExprResult ArgsRes1 =
10131 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10132 Best->Conversions[1], AA_Passing);
10133 if (ArgsRes1.isInvalid())
10134 return ExprError();
10135 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010136 break;
10137 }
10138 }
10139
Douglas Gregor66950a32009-09-30 21:46:01 +000010140 case OR_No_Viable_Function: {
10141 // C++ [over.match.oper]p9:
10142 // If the operator is the operator , [...] and there are no
10143 // viable functions, then the operator is assumed to be the
10144 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010145 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010146 break;
10147
Chandler Carruth8e543b32010-12-12 08:17:55 +000010148 // For class as left operand for assignment or compound assigment
10149 // operator do not fall through to handling in built-in, but report that
10150 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010151 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010152 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010153 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010154 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10155 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010156 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010157 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010158 // This is an erroneous use of an operator which can be overloaded by
10159 // a non-member function. Check for non-member operators which were
10160 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010161 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010162 // FIXME: Recover by calling the found function.
10163 return ExprError();
10164
Douglas Gregor66950a32009-09-30 21:46:01 +000010165 // No viable function; try to create a built-in operation, which will
10166 // produce an error. Then, show the non-viable candidates.
10167 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010169 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010170 "C++ binary operator overloading is missing candidates!");
10171 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010173 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +000010174 return move(Result);
10175 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010176
10177 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010178 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010179 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010180 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010181 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010182 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010183 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010184 return ExprError();
10185
10186 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010187 if (isImplicitlyDeleted(Best->Function)) {
10188 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10189 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10190 << getSpecialMember(Method)
10191 << BinaryOperator::getOpcodeStr(Opc)
10192 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010193
10194 if (getSpecialMember(Method) != CXXInvalid) {
10195 // The user probably meant to call this special member. Just
10196 // explain why it's deleted.
10197 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010198 return ExprError();
10199 }
10200 } else {
10201 Diag(OpLoc, diag::err_ovl_deleted_oper)
10202 << Best->Function->isDeleted()
10203 << BinaryOperator::getOpcodeStr(Opc)
10204 << getDeletedOrUnavailableSuffix(Best->Function)
10205 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10206 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010207 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010208 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010209 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010210 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010211
Douglas Gregor66950a32009-09-30 21:46:01 +000010212 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010213 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010214}
10215
John McCalldadc5752010-08-24 06:29:42 +000010216ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010217Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10218 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010219 Expr *Base, Expr *Idx) {
10220 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010221 DeclarationName OpName =
10222 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10223
10224 // If either side is type-dependent, create an appropriate dependent
10225 // expression.
10226 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10227
John McCall58cc69d2010-01-27 01:50:18 +000010228 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010229 // CHECKME: no 'operator' keyword?
10230 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10231 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010232 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010233 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010234 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010235 /*ADL*/ true, /*Overloaded*/ false,
10236 UnresolvedSetIterator(),
10237 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010238 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010239
Sebastian Redladba46e2009-10-29 20:17:01 +000010240 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10241 Args, 2,
10242 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010243 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010244 RLoc));
10245 }
10246
John McCall4124c492011-10-17 18:40:02 +000010247 // Handle placeholders on both operands.
10248 if (checkPlaceholderForOverload(*this, Args[0]))
10249 return ExprError();
10250 if (checkPlaceholderForOverload(*this, Args[1]))
10251 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010252
Sebastian Redladba46e2009-10-29 20:17:01 +000010253 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010254 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010255
10256 // Subscript can only be overloaded as a member function.
10257
10258 // Add operator candidates that are member functions.
10259 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10260
10261 // Add builtin operator candidates.
10262 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10263
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010264 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10265
Sebastian Redladba46e2009-10-29 20:17:01 +000010266 // Perform overload resolution.
10267 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010268 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010269 case OR_Success: {
10270 // We found a built-in operator or an overloaded operator.
10271 FunctionDecl *FnDecl = Best->Function;
10272
10273 if (FnDecl) {
10274 // We matched an overloaded operator. Build a call to that
10275 // operator.
10276
Eli Friedmanfa0df832012-02-02 03:46:19 +000010277 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010278
John McCalla0296f72010-03-19 07:35:19 +000010279 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010280 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010281
Sebastian Redladba46e2009-10-29 20:17:01 +000010282 // Convert the arguments.
10283 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010284 ExprResult Arg0 =
10285 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10286 Best->FoundDecl, Method);
10287 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010288 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010289 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010290
Anders Carlssona68e51e2010-01-29 18:37:50 +000010291 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010292 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010293 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010294 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010295 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010296 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010297 Owned(Args[1]));
10298 if (InputInit.isInvalid())
10299 return ExprError();
10300
10301 Args[1] = InputInit.takeAs<Expr>();
10302
Sebastian Redladba46e2009-10-29 20:17:01 +000010303 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010304 QualType ResultTy = FnDecl->getResultType();
10305 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10306 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010307
10308 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010309 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10310 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010311 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10312 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010313 OpLocInfo.getLoc(),
10314 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010315 if (FnExpr.isInvalid())
10316 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010317
John McCallb268a282010-08-23 23:25:46 +000010318 CXXOperatorCallExpr *TheCall =
10319 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +000010320 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +000010321 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010322
John McCallb268a282010-08-23 23:25:46 +000010323 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010324 FnDecl))
10325 return ExprError();
10326
John McCallb268a282010-08-23 23:25:46 +000010327 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010328 } else {
10329 // We matched a built-in operator. Convert the arguments, then
10330 // break out so that we will build the appropriate built-in
10331 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010332 ExprResult ArgsRes0 =
10333 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10334 Best->Conversions[0], AA_Passing);
10335 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010336 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010337 Args[0] = ArgsRes0.take();
10338
10339 ExprResult ArgsRes1 =
10340 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10341 Best->Conversions[1], AA_Passing);
10342 if (ArgsRes1.isInvalid())
10343 return ExprError();
10344 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010345
10346 break;
10347 }
10348 }
10349
10350 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010351 if (CandidateSet.empty())
10352 Diag(LLoc, diag::err_ovl_no_oper)
10353 << Args[0]->getType() << /*subscript*/ 0
10354 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10355 else
10356 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10357 << Args[0]->getType()
10358 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010359 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010360 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010361 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010362 }
10363
10364 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010365 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010366 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010367 << Args[0]->getType() << Args[1]->getType()
10368 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010369 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010370 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010371 return ExprError();
10372
10373 case OR_Deleted:
10374 Diag(LLoc, diag::err_ovl_deleted_oper)
10375 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010376 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010377 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010378 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010379 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010380 return ExprError();
10381 }
10382
10383 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010384 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010385}
10386
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010387/// BuildCallToMemberFunction - Build a call to a member
10388/// function. MemExpr is the expression that refers to the member
10389/// function (and includes the object parameter), Args/NumArgs are the
10390/// arguments to the function call (not including the object
10391/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010392/// expression refers to a non-static member function or an overloaded
10393/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010394ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010395Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10396 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010397 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010398 assert(MemExprE->getType() == Context.BoundMemberTy ||
10399 MemExprE->getType() == Context.OverloadTy);
10400
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010401 // Dig out the member expression. This holds both the object
10402 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010403 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010404
John McCall0009fcc2011-04-26 20:42:42 +000010405 // Determine whether this is a call to a pointer-to-member function.
10406 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10407 assert(op->getType() == Context.BoundMemberTy);
10408 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10409
10410 QualType fnType =
10411 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10412
10413 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10414 QualType resultType = proto->getCallResultType(Context);
10415 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10416
10417 // Check that the object type isn't more qualified than the
10418 // member function we're calling.
10419 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10420
10421 QualType objectType = op->getLHS()->getType();
10422 if (op->getOpcode() == BO_PtrMemI)
10423 objectType = objectType->castAs<PointerType>()->getPointeeType();
10424 Qualifiers objectQuals = objectType.getQualifiers();
10425
10426 Qualifiers difference = objectQuals - funcQuals;
10427 difference.removeObjCGCAttr();
10428 difference.removeAddressSpace();
10429 if (difference) {
10430 std::string qualsString = difference.getAsString();
10431 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10432 << fnType.getUnqualifiedType()
10433 << qualsString
10434 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10435 }
10436
10437 CXXMemberCallExpr *call
10438 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10439 resultType, valueKind, RParenLoc);
10440
10441 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010442 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010443 call, 0))
10444 return ExprError();
10445
10446 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10447 return ExprError();
10448
10449 return MaybeBindToTemporary(call);
10450 }
10451
John McCall4124c492011-10-17 18:40:02 +000010452 UnbridgedCastsSet UnbridgedCasts;
10453 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10454 return ExprError();
10455
John McCall10eae182009-11-30 22:42:35 +000010456 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010457 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010458 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010459 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010460 if (isa<MemberExpr>(NakedMemExpr)) {
10461 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010462 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010463 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010464 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010465 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010466 } else {
10467 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010468 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010469
John McCall6e9f8f62009-12-03 04:06:58 +000010470 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010471 Expr::Classification ObjectClassification
10472 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10473 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010474
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010475 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010476 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010477
John McCall2d74de92009-12-01 22:10:20 +000010478 // FIXME: avoid copy.
10479 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10480 if (UnresExpr->hasExplicitTemplateArgs()) {
10481 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10482 TemplateArgs = &TemplateArgsBuffer;
10483 }
10484
John McCall10eae182009-11-30 22:42:35 +000010485 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10486 E = UnresExpr->decls_end(); I != E; ++I) {
10487
John McCall6e9f8f62009-12-03 04:06:58 +000010488 NamedDecl *Func = *I;
10489 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10490 if (isa<UsingShadowDecl>(Func))
10491 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10492
Douglas Gregor02824322011-01-26 19:30:28 +000010493
Francois Pichet64225792011-01-18 05:04:39 +000010494 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010495 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010496 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10497 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010498 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010499 // If explicit template arguments were provided, we can't call a
10500 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010501 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010502 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010503
John McCalla0296f72010-03-19 07:35:19 +000010504 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010505 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010506 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010507 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010508 } else {
John McCall10eae182009-11-30 22:42:35 +000010509 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010510 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010511 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010512 llvm::makeArrayRef(Args, NumArgs),
10513 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010514 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010515 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010516 }
Mike Stump11289f42009-09-09 15:08:12 +000010517
John McCall10eae182009-11-30 22:42:35 +000010518 DeclarationName DeclName = UnresExpr->getMemberName();
10519
John McCall4124c492011-10-17 18:40:02 +000010520 UnbridgedCasts.restore();
10521
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010522 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010523 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010524 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010525 case OR_Success:
10526 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010527 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010528 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010529 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010530 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010531 break;
10532
10533 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010534 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010535 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010536 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010537 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10538 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010539 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010540 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010541
10542 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010543 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010544 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010545 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10546 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010547 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010548 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010549
10550 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010551 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010552 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010553 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010554 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010555 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010556 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10557 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010558 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010559 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010560 }
10561
John McCall16df1e52010-03-30 21:47:33 +000010562 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010563
John McCall2d74de92009-12-01 22:10:20 +000010564 // If overload resolution picked a static member, build a
10565 // non-member call based on that function.
10566 if (Method->isStatic()) {
10567 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10568 Args, NumArgs, RParenLoc);
10569 }
10570
John McCall10eae182009-11-30 22:42:35 +000010571 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010572 }
10573
John McCall7decc9e2010-11-18 06:31:45 +000010574 QualType ResultType = Method->getResultType();
10575 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10576 ResultType = ResultType.getNonLValueExprType(Context);
10577
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010578 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010579 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +000010580 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +000010581 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010582
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010583 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010584 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010585 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010586 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010587
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010588 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010589 // We only need to do this if there was actually an overload; otherwise
10590 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010591 if (!Method->isStatic()) {
10592 ExprResult ObjectArg =
10593 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10594 FoundDecl, Method);
10595 if (ObjectArg.isInvalid())
10596 return ExprError();
10597 MemExpr->setBase(ObjectArg.take());
10598 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010599
10600 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010601 const FunctionProtoType *Proto =
10602 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010603 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010604 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010605 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010606
Eli Friedmanff4b4072012-02-18 04:48:30 +000010607 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10608
John McCallb268a282010-08-23 23:25:46 +000010609 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +000010610 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010611
Anders Carlsson47061ee2011-05-06 14:25:31 +000010612 if ((isa<CXXConstructorDecl>(CurContext) ||
10613 isa<CXXDestructorDecl>(CurContext)) &&
10614 TheCall->getMethodDecl()->isPure()) {
10615 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10616
Chandler Carruth59259262011-06-27 08:31:58 +000010617 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010618 Diag(MemExpr->getLocStart(),
10619 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10620 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10621 << MD->getParent()->getDeclName();
10622
10623 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010624 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010625 }
John McCallb268a282010-08-23 23:25:46 +000010626 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010627}
10628
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010629/// BuildCallToObjectOfClassType - Build a call to an object of class
10630/// type (C++ [over.call.object]), which can end up invoking an
10631/// overloaded function call operator (@c operator()) or performing a
10632/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010633ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010634Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010635 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010636 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010637 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010638 if (checkPlaceholderForOverload(*this, Obj))
10639 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010640 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010641
10642 UnbridgedCastsSet UnbridgedCasts;
10643 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10644 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010645
John Wiegley01296292011-04-08 18:41:53 +000010646 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10647 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010648
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010649 // C++ [over.call.object]p1:
10650 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010651 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010652 // candidate functions includes at least the function call
10653 // operators of T. The function call operators of T are obtained by
10654 // ordinary lookup of the name operator() in the context of
10655 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010656 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010658
John Wiegley01296292011-04-08 18:41:53 +000010659 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010660 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010661 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010662
John McCall27b18f82009-11-17 02:14:36 +000010663 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10664 LookupQualifiedName(R, Record->getDecl());
10665 R.suppressDiagnostics();
10666
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010667 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010668 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010669 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10670 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010671 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010673
Douglas Gregorab7897a2008-11-19 22:57:39 +000010674 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010675 // In addition, for each (non-explicit in C++0x) conversion function
10676 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010677 //
10678 // operator conversion-type-id () cv-qualifier;
10679 //
10680 // where cv-qualifier is the same cv-qualification as, or a
10681 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010682 // denotes the type "pointer to function of (P1,...,Pn) returning
10683 // R", or the type "reference to pointer to function of
10684 // (P1,...,Pn) returning R", or the type "reference to function
10685 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010686 // is also considered as a candidate function. Similarly,
10687 // surrogate call functions are added to the set of candidate
10688 // functions for each conversion function declared in an
10689 // accessible base class provided the function is not hidden
10690 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010691 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010692 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010693 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010694 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010695 NamedDecl *D = *I;
10696 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10697 if (isa<UsingShadowDecl>(D))
10698 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010699
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010700 // Skip over templated conversion functions; they aren't
10701 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010702 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010703 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010704
John McCall6e9f8f62009-12-03 04:06:58 +000010705 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010706 if (!Conv->isExplicit()) {
10707 // Strip the reference type (if any) and then the pointer type (if
10708 // any) to get down to what might be a function type.
10709 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10710 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10711 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010712
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010713 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10714 {
10715 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010716 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10717 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010718 }
10719 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010720 }
Mike Stump11289f42009-09-09 15:08:12 +000010721
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010722 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10723
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010724 // Perform overload resolution.
10725 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010726 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010727 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010728 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010729 // Overload resolution succeeded; we'll build the appropriate call
10730 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010731 break;
10732
10733 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010734 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010735 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010736 << Object.get()->getType() << /*call*/ 1
10737 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010738 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010739 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010740 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010741 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010742 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10743 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010744 break;
10745
10746 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010747 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010748 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010749 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010750 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10751 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010752 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010753
10754 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010755 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010756 diag::err_ovl_deleted_object_call)
10757 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010758 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010759 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010760 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10762 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010763 break;
Mike Stump11289f42009-09-09 15:08:12 +000010764 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010765
Douglas Gregorb412e172010-07-25 18:17:45 +000010766 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010767 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010768
John McCall4124c492011-10-17 18:40:02 +000010769 UnbridgedCasts.restore();
10770
Douglas Gregorab7897a2008-11-19 22:57:39 +000010771 if (Best->Function == 0) {
10772 // Since there is no function declaration, this is one of the
10773 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010774 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010775 = cast<CXXConversionDecl>(
10776 Best->Conversions[0].UserDefined.ConversionFunction);
10777
John Wiegley01296292011-04-08 18:41:53 +000010778 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010779 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010780
Douglas Gregorab7897a2008-11-19 22:57:39 +000010781 // We selected one of the surrogate functions that converts the
10782 // object parameter to a function pointer. Perform the conversion
10783 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010784
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010785 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010786 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010787 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10788 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010789 if (Call.isInvalid())
10790 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010791 // Record usage of conversion in an implicit cast.
10792 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10793 CK_UserDefinedConversion,
10794 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010795
Douglas Gregor668443e2011-01-20 00:18:04 +000010796 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010797 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010798 }
10799
Eli Friedmanfa0df832012-02-02 03:46:19 +000010800 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010801 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010802 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010803
Douglas Gregorab7897a2008-11-19 22:57:39 +000010804 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10805 // that calls this method, using Object for the implicit object
10806 // parameter and passing along the remaining arguments.
10807 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010808 const FunctionProtoType *Proto =
10809 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010810
10811 unsigned NumArgsInProto = Proto->getNumArgs();
10812 unsigned NumArgsToCheck = NumArgs;
10813
10814 // Build the full argument list for the method call (the
10815 // implicit object parameter is placed at the beginning of the
10816 // list).
10817 Expr **MethodArgs;
10818 if (NumArgs < NumArgsInProto) {
10819 NumArgsToCheck = NumArgsInProto;
10820 MethodArgs = new Expr*[NumArgsInProto + 1];
10821 } else {
10822 MethodArgs = new Expr*[NumArgs + 1];
10823 }
John Wiegley01296292011-04-08 18:41:53 +000010824 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10826 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010827
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010828 DeclarationNameInfo OpLocInfo(
10829 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10830 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010831 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010832 HadMultipleCandidates,
10833 OpLocInfo.getLoc(),
10834 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010835 if (NewFn.isInvalid())
10836 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010837
10838 // Once we've built TheCall, all of the expressions are properly
10839 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010840 QualType ResultTy = Method->getResultType();
10841 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10842 ResultTy = ResultTy.getNonLValueExprType(Context);
10843
John McCallb268a282010-08-23 23:25:46 +000010844 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010845 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010846 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010847 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010848 delete [] MethodArgs;
10849
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010850 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010851 Method))
10852 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010853
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010854 // We may have default arguments. If so, we need to allocate more
10855 // slots in the call for them.
10856 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010857 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010858 else if (NumArgs > NumArgsInProto)
10859 NumArgsToCheck = NumArgsInProto;
10860
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010861 bool IsError = false;
10862
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010863 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010864 ExprResult ObjRes =
10865 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10866 Best->FoundDecl, Method);
10867 if (ObjRes.isInvalid())
10868 IsError = true;
10869 else
10870 Object = move(ObjRes);
10871 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010872
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010873 // Check the argument types.
10874 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010875 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010876 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010877 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010878
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010879 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010880
John McCalldadc5752010-08-24 06:29:42 +000010881 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010882 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010883 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010884 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010885 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010886
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010887 IsError |= InputInit.isInvalid();
10888 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010889 } else {
John McCalldadc5752010-08-24 06:29:42 +000010890 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010891 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10892 if (DefArg.isInvalid()) {
10893 IsError = true;
10894 break;
10895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010896
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010897 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010898 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010899
10900 TheCall->setArg(i + 1, Arg);
10901 }
10902
10903 // If this is a variadic call, handle args passed through "...".
10904 if (Proto->isVariadic()) {
10905 // Promote the arguments (C99 6.5.2.2p7).
10906 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010907 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10908 IsError |= Arg.isInvalid();
10909 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010910 }
10911 }
10912
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010913 if (IsError) return true;
10914
Eli Friedmanff4b4072012-02-18 04:48:30 +000010915 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10916
John McCallb268a282010-08-23 23:25:46 +000010917 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010918 return true;
10919
John McCalle172be52010-08-24 06:09:16 +000010920 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010921}
10922
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010923/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010924/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010925/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010926ExprResult
John McCallb268a282010-08-23 23:25:46 +000010927Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010928 assert(Base->getType()->isRecordType() &&
10929 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010930
John McCall4124c492011-10-17 18:40:02 +000010931 if (checkPlaceholderForOverload(*this, Base))
10932 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010933
John McCallbc077cf2010-02-08 23:07:23 +000010934 SourceLocation Loc = Base->getExprLoc();
10935
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010936 // C++ [over.ref]p1:
10937 //
10938 // [...] An expression x->m is interpreted as (x.operator->())->m
10939 // for a class object x of type T if T::operator->() exists and if
10940 // the operator is selected as the best match function by the
10941 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010942 DeclarationName OpName =
10943 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010944 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010945 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010946
John McCallbc077cf2010-02-08 23:07:23 +000010947 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010948 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000010949 return ExprError();
10950
John McCall27b18f82009-11-17 02:14:36 +000010951 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10952 LookupQualifiedName(R, BaseRecord->getDecl());
10953 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010954
10955 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010956 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010957 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10958 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010959 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010960
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010961 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10962
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010963 // Perform overload resolution.
10964 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010966 case OR_Success:
10967 // Overload resolution succeeded; we'll build the call below.
10968 break;
10969
10970 case OR_No_Viable_Function:
10971 if (CandidateSet.empty())
10972 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010973 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010974 else
10975 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010976 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010978 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010979
10980 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010981 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10982 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010983 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010984 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010985
10986 case OR_Deleted:
10987 Diag(OpLoc, diag::err_ovl_deleted_oper)
10988 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010989 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010990 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010991 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000010993 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010994 }
10995
Eli Friedmanfa0df832012-02-02 03:46:19 +000010996 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010997 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010998 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010999
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011000 // Convert the object parameter.
11001 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011002 ExprResult BaseResult =
11003 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11004 Best->FoundDecl, Method);
11005 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011006 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011007 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011008
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011009 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011010 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011011 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011012 if (FnExpr.isInvalid())
11013 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011014
John McCall7decc9e2010-11-18 06:31:45 +000011015 QualType ResultTy = Method->getResultType();
11016 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11017 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011018 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011019 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000011020 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011021
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011022 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011023 Method))
11024 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011025
11026 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011027}
11028
Richard Smithbcc22fc2012-03-09 08:00:36 +000011029/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11030/// a literal operator described by the provided lookup results.
11031ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11032 DeclarationNameInfo &SuffixInfo,
11033 ArrayRef<Expr*> Args,
11034 SourceLocation LitEndLoc,
11035 TemplateArgumentListInfo *TemplateArgs) {
11036 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011037
Richard Smithbcc22fc2012-03-09 08:00:36 +000011038 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11039 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11040 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011041
Richard Smithbcc22fc2012-03-09 08:00:36 +000011042 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11043
Richard Smithbcc22fc2012-03-09 08:00:36 +000011044 // Perform overload resolution. This will usually be trivial, but might need
11045 // to perform substitutions for a literal operator template.
11046 OverloadCandidateSet::iterator Best;
11047 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11048 case OR_Success:
11049 case OR_Deleted:
11050 break;
11051
11052 case OR_No_Viable_Function:
11053 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11054 << R.getLookupName();
11055 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11056 return ExprError();
11057
11058 case OR_Ambiguous:
11059 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11060 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11061 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011062 }
11063
Richard Smithbcc22fc2012-03-09 08:00:36 +000011064 FunctionDecl *FD = Best->Function;
11065 MarkFunctionReferenced(UDSuffixLoc, FD);
11066 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011067
Richard Smithbcc22fc2012-03-09 08:00:36 +000011068 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11069 SuffixInfo.getLoc(),
11070 SuffixInfo.getInfo());
11071 if (Fn.isInvalid())
11072 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011073
11074 // Check the argument types. This should almost always be a no-op, except
11075 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011076 Expr *ConvArgs[2];
11077 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11078 ExprResult InputInit = PerformCopyInitialization(
11079 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11080 SourceLocation(), Args[ArgIdx]);
11081 if (InputInit.isInvalid())
11082 return true;
11083 ConvArgs[ArgIdx] = InputInit.take();
11084 }
11085
Richard Smithc67fdd42012-03-07 08:35:16 +000011086 QualType ResultTy = FD->getResultType();
11087 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11088 ResultTy = ResultTy.getNonLValueExprType(Context);
11089
Richard Smithc67fdd42012-03-07 08:35:16 +000011090 UserDefinedLiteral *UDL =
11091 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11092 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11093
11094 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11095 return ExprError();
11096
11097 if (CheckFunctionCall(FD, UDL))
11098 return ExprError();
11099
11100 return MaybeBindToTemporary(UDL);
11101}
11102
Douglas Gregorcd695e52008-11-10 20:40:00 +000011103/// FixOverloadedFunctionReference - E is an expression that refers to
11104/// a C++ overloaded function (possibly with some parentheses and
11105/// perhaps a '&' around it). We have resolved the overloaded function
11106/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011107/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011108Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011109 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011110 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011111 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11112 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011113 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011114 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011115
Douglas Gregor51c538b2009-11-20 19:42:02 +000011116 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011117 }
11118
Douglas Gregor51c538b2009-11-20 19:42:02 +000011119 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011120 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11121 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011122 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011123 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011124 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011125 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011126 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011127 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011128
11129 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011130 ICE->getCastKind(),
11131 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011132 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011133 }
11134
Douglas Gregor51c538b2009-11-20 19:42:02 +000011135 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011136 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011137 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011138 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11139 if (Method->isStatic()) {
11140 // Do nothing: static member functions aren't any different
11141 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011142 } else {
John McCalle66edc12009-11-24 19:00:30 +000011143 // Fix the sub expression, which really has to be an
11144 // UnresolvedLookupExpr holding an overloaded member function
11145 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011146 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11147 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011148 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011149 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011150
John McCalld14a8642009-11-21 08:51:07 +000011151 assert(isa<DeclRefExpr>(SubExpr)
11152 && "fixed to something other than a decl ref");
11153 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11154 && "fixed to a member ref with no nested name qualifier");
11155
11156 // We have taken the address of a pointer to member
11157 // function. Perform the computation here so that we get the
11158 // appropriate pointer to member type.
11159 QualType ClassType
11160 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11161 QualType MemPtrType
11162 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11163
John McCall7decc9e2010-11-18 06:31:45 +000011164 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11165 VK_RValue, OK_Ordinary,
11166 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011167 }
11168 }
John McCall16df1e52010-03-30 21:47:33 +000011169 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11170 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011171 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011172 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011173
John McCalle3027922010-08-25 11:45:40 +000011174 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011175 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011176 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011177 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011178 }
John McCalld14a8642009-11-21 08:51:07 +000011179
11180 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011181 // FIXME: avoid copy.
11182 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011183 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011184 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11185 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011186 }
11187
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011188 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11189 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011190 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011191 Fn,
John McCall113bee02012-03-10 09:33:50 +000011192 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011193 ULE->getNameLoc(),
11194 Fn->getType(),
11195 VK_LValue,
11196 Found.getDecl(),
11197 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011198 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011199 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11200 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011201 }
11202
John McCall10eae182009-11-30 22:42:35 +000011203 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011204 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011205 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11206 if (MemExpr->hasExplicitTemplateArgs()) {
11207 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11208 TemplateArgs = &TemplateArgsBuffer;
11209 }
John McCall6b51f282009-11-23 01:53:49 +000011210
John McCall2d74de92009-12-01 22:10:20 +000011211 Expr *Base;
11212
John McCall7decc9e2010-11-18 06:31:45 +000011213 // If we're filling in a static method where we used to have an
11214 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011215 if (MemExpr->isImplicitAccess()) {
11216 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011217 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11218 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011219 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011220 Fn,
John McCall113bee02012-03-10 09:33:50 +000011221 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011222 MemExpr->getMemberLoc(),
11223 Fn->getType(),
11224 VK_LValue,
11225 Found.getDecl(),
11226 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011227 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011228 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11229 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011230 } else {
11231 SourceLocation Loc = MemExpr->getMemberLoc();
11232 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011233 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011234 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011235 Base = new (Context) CXXThisExpr(Loc,
11236 MemExpr->getBaseType(),
11237 /*isImplicit=*/true);
11238 }
John McCall2d74de92009-12-01 22:10:20 +000011239 } else
John McCallc3007a22010-10-26 07:05:15 +000011240 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011241
John McCall4adb38c2011-04-27 00:36:17 +000011242 ExprValueKind valueKind;
11243 QualType type;
11244 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11245 valueKind = VK_LValue;
11246 type = Fn->getType();
11247 } else {
11248 valueKind = VK_RValue;
11249 type = Context.BoundMemberTy;
11250 }
11251
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011252 MemberExpr *ME = MemberExpr::Create(Context, Base,
11253 MemExpr->isArrow(),
11254 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011255 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011256 Fn,
11257 Found,
11258 MemExpr->getMemberNameInfo(),
11259 TemplateArgs,
11260 type, valueKind, OK_Ordinary);
11261 ME->setHadMultipleCandidates(true);
11262 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011264
John McCallc3007a22010-10-26 07:05:15 +000011265 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011266}
11267
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011268ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011269 DeclAccessPair Found,
11270 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011271 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011272}
11273
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011274} // end namespace clang