blob: a8744899d70cfd94ee4c3e577c8a7d9b3c0741be [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000037
John McCallf89e55a2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
52 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000053}
54
John McCall120d63c2010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-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 McCall120d63c2010-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 Gregor8e9bebd2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-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 Lopes2550d702009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor60d62c22008-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 Gregora9bff302010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000203}
204
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000243bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-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 Gregorf9af5242011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith4c3fc9b2012-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 Smithf6028062012-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 Smith4c3fc9b2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-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 Smithf6028062012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-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 Smithf6028062012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000365 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000392 (FromWidth == ToWidth && FromSigned != ToSigned) ||
393 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000394 // Not all values of FromType can be represented in ToType.
395 llvm::APSInt InitializerValue;
396 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398 // Such conversions on variables are always narrowing.
399 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000400 }
401 bool Narrowing = false;
402 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000403 // Negative -> unsigned is narrowing. Otherwise, more bits is never
404 // narrowing.
405 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000406 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000407 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Add a bit to the InitializerValue so we don't have to worry about
409 // signed vs. unsigned comparisons.
410 InitializerValue = InitializerValue.extend(
411 InitializerValue.getBitWidth() + 1);
412 // Convert the initializer to and from the target width and signed-ness.
413 llvm::APSInt ConvertedValue = InitializerValue;
414 ConvertedValue = ConvertedValue.trunc(ToWidth);
415 ConvertedValue.setIsSigned(ToSigned);
416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
418 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000419 if (ConvertedValue != InitializerValue)
420 Narrowing = true;
421 }
422 if (Narrowing) {
423 ConstantType = Initializer->getType();
424 ConstantValue = APValue(InitializerValue);
425 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000426 }
427 }
428 return NK_Not_Narrowing;
429 }
430
431 default:
432 // Other kinds of conversions are not narrowings.
433 return NK_Not_Narrowing;
434 }
435}
436
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 bool PrintedSomething = false;
442 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000443 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 PrintedSomething = true;
445 }
446
447 if (Second != ICK_Identity) {
448 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000451 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000452
453 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000455 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000459 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Third != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 if (Before.First || Before.Second || Before.Third) {
481 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000484 if (ConversionFunction)
485 OS << '\'' << *ConversionFunction << '\'';
486 else
487 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 After.DebugPrint();
491 }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000497 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 switch (ConversionKind) {
499 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 Standard.DebugPrint();
502 break;
503 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 UserDefined.DebugPrint();
506 break;
507 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000508 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 break;
John McCall1d318332010-01-12 00:44:57 +0000510 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000511 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000512 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 break;
516 }
517
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519}
520
John McCall1d318332010-01-12 00:44:57 +0000521void AmbiguousConversionSequence::construct() {
522 new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526 conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531 FromTypePtr = O.FromTypePtr;
532 ToTypePtr = O.ToTypePtr;
533 new (&conversions()) ConversionSet(O.conversions());
534}
535
Douglas Gregora9333192010-05-08 17:41:32 +0000536namespace {
537 // Structure used by OverloadCandidate::DeductionFailureInfo to store
538 // template parameter and template argument information.
539 struct DFIParamWithArguments {
540 TemplateParameter Param;
541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
544}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000545
Douglas Gregora9333192010-05-08 17:41:32 +0000546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000549static MakeDeductionFailureInfo(ASTContext &Context,
550 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000551 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000552 OverloadCandidate::DeductionFailureInfo Result;
553 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000554 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000555 Result.Data = 0;
556 switch (TDK) {
557 case Sema::TDK_Success:
558 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000559 case Sema::TDK_TooManyArguments:
560 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000561 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000562
Douglas Gregora9333192010-05-08 17:41:32 +0000563 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000564 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000565 Result.Data = Info.Param.getOpaqueValue();
566 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567
Douglas Gregora9333192010-05-08 17:41:32 +0000568 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000569 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000570 // FIXME: Should allocate from normal heap so that we can free this later.
571 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000572 Saved->Param = Info.Param;
573 Saved->FirstArg = Info.FirstArg;
574 Saved->SecondArg = Info.SecondArg;
575 Result.Data = Saved;
576 break;
577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578
Douglas Gregora9333192010-05-08 17:41:32 +0000579 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000580 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000581 if (Info.hasSFINAEDiagnostic()) {
582 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
583 SourceLocation(), PartialDiagnostic::NullDiagnostic());
584 Info.takeSFINAEDiagnostic(*Diag);
585 Result.HasDiagnostic = true;
586 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000587 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588
Douglas Gregora9333192010-05-08 17:41:32 +0000589 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000590 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000591 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
Douglas Gregora9333192010-05-08 17:41:32 +0000594 return Result;
595}
John McCall1d318332010-01-12 00:44:57 +0000596
Douglas Gregora9333192010-05-08 17:41:32 +0000597void OverloadCandidate::DeductionFailureInfo::Destroy() {
598 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
599 case Sema::TDK_Success:
600 case Sema::TDK_InstantiationDepth:
601 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000602 case Sema::TDK_TooManyArguments:
603 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000604 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000605 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606
Douglas Gregora9333192010-05-08 17:41:32 +0000607 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000608 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000609 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000610 Data = 0;
611 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000612
613 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000614 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000616 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
617 Diag->~PartialDiagnosticAt();
618 HasDiagnostic = false;
619 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000620 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000622 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000623 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000624 case Sema::TDK_FailedOverloadResolution:
625 break;
626 }
627}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
Richard Smithb8590f32012-05-07 09:03:25 +0000629PartialDiagnosticAt *
630OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
631 if (HasDiagnostic)
632 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
633 return 0;
634}
635
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000636TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000637OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
638 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
639 case Sema::TDK_Success:
640 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000641 case Sema::TDK_TooManyArguments:
642 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000643 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000644 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645
Douglas Gregora9333192010-05-08 17:41:32 +0000646 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000647 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000649
650 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000651 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000652 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000653
Douglas Gregora9333192010-05-08 17:41:32 +0000654 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000655 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000656 case Sema::TDK_FailedOverloadResolution:
657 break;
658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659
Douglas Gregora9333192010-05-08 17:41:32 +0000660 return TemplateParameter();
661}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Douglas Gregorec20f462010-05-08 20:07:26 +0000663TemplateArgumentList *
664OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
665 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
666 case Sema::TDK_Success:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_TooManyArguments:
669 case Sema::TDK_TooFewArguments:
670 case Sema::TDK_Incomplete:
671 case Sema::TDK_InvalidExplicitArguments:
672 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000673 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000674 return 0;
675
676 case Sema::TDK_SubstitutionFailure:
677 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000678
Douglas Gregorec20f462010-05-08 20:07:26 +0000679 // Unhandled
680 case Sema::TDK_NonDeducedMismatch:
681 case Sema::TDK_FailedOverloadResolution:
682 break;
683 }
684
685 return 0;
686}
687
Douglas Gregora9333192010-05-08 17:41:32 +0000688const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
689 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
690 case Sema::TDK_Success:
691 case Sema::TDK_InstantiationDepth:
692 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000693 case Sema::TDK_TooManyArguments:
694 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000695 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000696 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000697 return 0;
698
Douglas Gregora9333192010-05-08 17:41:32 +0000699 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000700 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000702
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000703 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000704 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000705 case Sema::TDK_FailedOverloadResolution:
706 break;
707 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000708
Douglas Gregora9333192010-05-08 17:41:32 +0000709 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000710}
Douglas Gregora9333192010-05-08 17:41:32 +0000711
712const TemplateArgument *
713OverloadCandidate::DeductionFailureInfo::getSecondArg() {
714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
715 case Sema::TDK_Success:
716 case Sema::TDK_InstantiationDepth:
717 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000718 case Sema::TDK_TooManyArguments:
719 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000720 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000721 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000722 return 0;
723
Douglas Gregora9333192010-05-08 17:41:32 +0000724 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000725 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000726 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
727
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000728 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000730 case Sema::TDK_FailedOverloadResolution:
731 break;
732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000733
Douglas Gregora9333192010-05-08 17:41:32 +0000734 return 0;
735}
736
737void OverloadCandidateSet::clear() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000738 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000739 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
740 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000741 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
742 i->DeductionFailure.Destroy();
743 }
Benjamin Kramer314f5542012-01-14 19:31:39 +0000744 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000745 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000746 Functions.clear();
747}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000748
John McCall5acb0c92011-10-17 18:40:02 +0000749namespace {
750 class UnbridgedCastsSet {
751 struct Entry {
752 Expr **Addr;
753 Expr *Saved;
754 };
755 SmallVector<Entry, 2> Entries;
756
757 public:
758 void save(Sema &S, Expr *&E) {
759 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
760 Entry entry = { &E, E };
761 Entries.push_back(entry);
762 E = S.stripARCUnbridgedCast(E);
763 }
764
765 void restore() {
766 for (SmallVectorImpl<Entry>::iterator
767 i = Entries.begin(), e = Entries.end(); i != e; ++i)
768 *i->Addr = i->Saved;
769 }
770 };
771}
772
773/// checkPlaceholderForOverload - Do any interesting placeholder-like
774/// preprocessing on the given expression.
775///
776/// \param unbridgedCasts a collection to which to add unbridged casts;
777/// without this, they will be immediately diagnosed as errors
778///
779/// Return true on unrecoverable error.
780static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
781 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000782 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
783 // We can't handle overloaded expressions here because overload
784 // resolution might reasonably tweak them.
785 if (placeholder->getKind() == BuiltinType::Overload) return false;
786
787 // If the context potentially accepts unbridged ARC casts, strip
788 // the unbridged cast and add it to the collection for later restoration.
789 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
790 unbridgedCasts) {
791 unbridgedCasts->save(S, E);
792 return false;
793 }
794
795 // Go ahead and check everything else.
796 ExprResult result = S.CheckPlaceholderExpr(E);
797 if (result.isInvalid())
798 return true;
799
800 E = result.take();
801 return false;
802 }
803
804 // Nothing to do.
805 return false;
806}
807
808/// checkArgPlaceholdersForOverload - Check a set of call operands for
809/// placeholders.
810static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
811 unsigned numArgs,
812 UnbridgedCastsSet &unbridged) {
813 for (unsigned i = 0; i != numArgs; ++i)
814 if (checkPlaceholderForOverload(S, args[i], &unbridged))
815 return true;
816
817 return false;
818}
819
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000820// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000821// overload of the declarations in Old. This routine returns false if
822// New and Old cannot be overloaded, e.g., if New has the same
823// signature as some function in Old (C++ 1.3.10) or if the Old
824// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000825// it does return false, MatchedDecl will point to the decl that New
826// cannot be overloaded with. This decl may be a UsingShadowDecl on
827// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000828//
829// Example: Given the following input:
830//
831// void f(int, float); // #1
832// void f(int, int); // #2
833// int f(int, int); // #3
834//
835// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000836// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000837//
John McCall51fa86f2009-12-02 08:47:38 +0000838// When we process #2, Old contains only the FunctionDecl for #1. By
839// comparing the parameter types, we see that #1 and #2 are overloaded
840// (since they have different signatures), so this routine returns
841// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000842//
John McCall51fa86f2009-12-02 08:47:38 +0000843// When we process #3, Old is an overload set containing #1 and #2. We
844// compare the signatures of #3 to #1 (they're overloaded, so we do
845// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
846// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847// signature), IsOverload returns false and MatchedDecl will be set to
848// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000849//
850// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
851// into a class by a using declaration. The rules for whether to hide
852// shadow declarations ignore some properties which otherwise figure
853// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000854Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000855Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
856 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000857 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000858 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000859 NamedDecl *OldD = *I;
860
861 bool OldIsUsingDecl = false;
862 if (isa<UsingShadowDecl>(OldD)) {
863 OldIsUsingDecl = true;
864
865 // We can always introduce two using declarations into the same
866 // context, even if they have identical signatures.
867 if (NewIsUsingDecl) continue;
868
869 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
870 }
871
872 // If either declaration was introduced by a using declaration,
873 // we'll need to use slightly different rules for matching.
874 // Essentially, these rules are the normal rules, except that
875 // function templates hide function templates with different
876 // return types or template parameter lists.
877 bool UseMemberUsingDeclRules =
878 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
879
John McCall51fa86f2009-12-02 08:47:38 +0000880 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000881 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
882 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
883 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
884 continue;
885 }
886
John McCall871b2e72009-12-09 03:35:25 +0000887 Match = *I;
888 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000889 }
John McCall51fa86f2009-12-02 08:47:38 +0000890 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000891 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
892 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
893 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
894 continue;
895 }
896
John McCall871b2e72009-12-09 03:35:25 +0000897 Match = *I;
898 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000899 }
John McCalld7945c62010-11-10 03:01:53 +0000900 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000901 // We can overload with these, which can show up when doing
902 // redeclaration checks for UsingDecls.
903 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000904 } else if (isa<TagDecl>(OldD)) {
905 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000906 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
907 // Optimistically assume that an unresolved using decl will
908 // overload; if it doesn't, we'll have to diagnose during
909 // template instantiation.
910 } else {
John McCall68263142009-11-18 22:49:29 +0000911 // (C++ 13p1):
912 // Only function declarations can be overloaded; object and type
913 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000914 Match = *I;
915 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000916 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000917 }
John McCall68263142009-11-18 22:49:29 +0000918
John McCall871b2e72009-12-09 03:35:25 +0000919 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000920}
921
John McCallad00b772010-06-16 08:42:20 +0000922bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
923 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000924 // If both of the functions are extern "C", then they are not
925 // overloads.
926 if (Old->isExternC() && New->isExternC())
927 return false;
928
John McCall68263142009-11-18 22:49:29 +0000929 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
930 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
931
932 // C++ [temp.fct]p2:
933 // A function template can be overloaded with other function templates
934 // and with normal (non-template) functions.
935 if ((OldTemplate == 0) != (NewTemplate == 0))
936 return true;
937
938 // Is the function New an overload of the function Old?
939 QualType OldQType = Context.getCanonicalType(Old->getType());
940 QualType NewQType = Context.getCanonicalType(New->getType());
941
942 // Compare the signatures (C++ 1.3.10) of the two functions to
943 // determine whether they are overloads. If we find any mismatch
944 // in the signature, they are overloads.
945
946 // If either of these functions is a K&R-style function (no
947 // prototype), then we consider them to have matching signatures.
948 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
949 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
950 return false;
951
John McCallf4c73712011-01-19 06:33:43 +0000952 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
953 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000954
955 // The signature of a function includes the types of its
956 // parameters (C++ 1.3.10), which includes the presence or absence
957 // of the ellipsis; see C++ DR 357).
958 if (OldQType != NewQType &&
959 (OldType->getNumArgs() != NewType->getNumArgs() ||
960 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000961 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000962 return true;
963
964 // C++ [temp.over.link]p4:
965 // The signature of a function template consists of its function
966 // signature, its return type and its template parameter list. The names
967 // of the template parameters are significant only for establishing the
968 // relationship between the template parameters and the rest of the
969 // signature.
970 //
971 // We check the return type and template parameter lists for function
972 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000973 //
974 // However, we don't consider either of these when deciding whether
975 // a member introduced by a shadow declaration is hidden.
976 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000977 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
978 OldTemplate->getTemplateParameters(),
979 false, TPL_TemplateMatch) ||
980 OldType->getResultType() != NewType->getResultType()))
981 return true;
982
983 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000984 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000985 //
986 // As part of this, also check whether one of the member functions
987 // is static, in which case they are not overloads (C++
988 // 13.1p2). While not part of the definition of the signature,
989 // this check is important to determine whether these functions
990 // can be overloaded.
991 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
992 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
993 if (OldMethod && NewMethod &&
994 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000995 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000996 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
997 if (!UseUsingDeclRules &&
998 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
999 (OldMethod->getRefQualifier() == RQ_None ||
1000 NewMethod->getRefQualifier() == RQ_None)) {
1001 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002 // - Member function declarations with the same name and the same
1003 // parameter-type-list as well as member function template
1004 // declarations with the same name, the same parameter-type-list, and
1005 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001006 // them, but not all, have a ref-qualifier (8.3.5).
1007 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1008 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1009 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1010 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
John McCall68263142009-11-18 22:49:29 +00001012 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001013 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
John McCall68263142009-11-18 22:49:29 +00001015 // The signatures match; this is not an overload.
1016 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017}
1018
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001019/// \brief Checks availability of the function depending on the current
1020/// function context. Inside an unavailable function, unavailability is ignored.
1021///
1022/// \returns true if \arg FD is unavailable and current context is inside
1023/// an available function, false otherwise.
1024bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1025 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1026}
1027
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001028/// \brief Tries a user-defined conversion from From to ToType.
1029///
1030/// Produces an implicit conversion sequence for when a standard conversion
1031/// is not an option. See TryImplicitConversion for more information.
1032static ImplicitConversionSequence
1033TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1034 bool SuppressUserConversions,
1035 bool AllowExplicit,
1036 bool InOverloadResolution,
1037 bool CStyle,
1038 bool AllowObjCWritebackConversion) {
1039 ImplicitConversionSequence ICS;
1040
1041 if (SuppressUserConversions) {
1042 // We're not in the case above, so there is no conversion that
1043 // we can perform.
1044 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1045 return ICS;
1046 }
1047
1048 // Attempt user-defined conversion.
1049 OverloadCandidateSet Conversions(From->getExprLoc());
1050 OverloadingResult UserDefResult
1051 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1052 AllowExplicit);
1053
1054 if (UserDefResult == OR_Success) {
1055 ICS.setUserDefined();
1056 // C++ [over.ics.user]p4:
1057 // A conversion of an expression of class type to the same class
1058 // type is given Exact Match rank, and a conversion of an
1059 // expression of class type to a base class of that type is
1060 // given Conversion rank, in spite of the fact that a copy
1061 // constructor (i.e., a user-defined conversion function) is
1062 // called for those cases.
1063 if (CXXConstructorDecl *Constructor
1064 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1065 QualType FromCanon
1066 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1067 QualType ToCanon
1068 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1069 if (Constructor->isCopyConstructor() &&
1070 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1071 // Turn this into a "standard" conversion sequence, so that it
1072 // gets ranked with standard conversion sequences.
1073 ICS.setStandard();
1074 ICS.Standard.setAsIdentityConversion();
1075 ICS.Standard.setFromType(From->getType());
1076 ICS.Standard.setAllToTypes(ToType);
1077 ICS.Standard.CopyConstructor = Constructor;
1078 if (ToCanon != FromCanon)
1079 ICS.Standard.Second = ICK_Derived_To_Base;
1080 }
1081 }
1082
1083 // C++ [over.best.ics]p4:
1084 // However, when considering the argument of a user-defined
1085 // conversion function that is a candidate by 13.3.1.3 when
1086 // invoked for the copying of the temporary in the second step
1087 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1088 // 13.3.1.6 in all cases, only standard conversion sequences and
1089 // ellipsis conversion sequences are allowed.
1090 if (SuppressUserConversions && ICS.isUserDefined()) {
1091 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1092 }
1093 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1094 ICS.setAmbiguous();
1095 ICS.Ambiguous.setFromType(From->getType());
1096 ICS.Ambiguous.setToType(ToType);
1097 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1098 Cand != Conversions.end(); ++Cand)
1099 if (Cand->Viable)
1100 ICS.Ambiguous.addConversion(Cand->Function);
1101 } else {
1102 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1103 }
1104
1105 return ICS;
1106}
1107
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001108/// TryImplicitConversion - Attempt to perform an implicit conversion
1109/// from the given expression (Expr) to the given type (ToType). This
1110/// function returns an implicit conversion sequence that can be used
1111/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001112///
1113/// void f(float f);
1114/// void g(int i) { f(i); }
1115///
1116/// this routine would produce an implicit conversion sequence to
1117/// describe the initialization of f from i, which will be a standard
1118/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1119/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1120//
1121/// Note that this routine only determines how the conversion can be
1122/// performed; it does not actually perform the conversion. As such,
1123/// it will not produce any diagnostics if no conversion is available,
1124/// but will instead return an implicit conversion sequence of kind
1125/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001126///
1127/// If @p SuppressUserConversions, then user-defined conversions are
1128/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001129/// If @p AllowExplicit, then explicit user-defined conversions are
1130/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001131///
1132/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1133/// writeback conversion, which allows __autoreleasing id* parameters to
1134/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001135static ImplicitConversionSequence
1136TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1137 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001139 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001140 bool CStyle,
1141 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001143 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001144 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001145 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001146 return ICS;
1147 }
1148
David Blaikie4e4d0842012-03-11 07:00:24 +00001149 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001150 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001151 return ICS;
1152 }
1153
Douglas Gregor604eb652010-08-11 02:15:33 +00001154 // C++ [over.ics.user]p4:
1155 // A conversion of an expression of class type to the same class
1156 // type is given Exact Match rank, and a conversion of an
1157 // expression of class type to a base class of that type is
1158 // given Conversion rank, in spite of the fact that a copy/move
1159 // constructor (i.e., a user-defined conversion function) is
1160 // called for those cases.
1161 QualType FromType = From->getType();
1162 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001163 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1164 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001165 ICS.setStandard();
1166 ICS.Standard.setAsIdentityConversion();
1167 ICS.Standard.setFromType(FromType);
1168 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001169
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001170 // We don't actually check at this point whether there is a valid
1171 // copy/move constructor, since overloading just assumes that it
1172 // exists. When we actually perform initialization, we'll find the
1173 // appropriate constructor to copy the returned object, if needed.
1174 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001175
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001176 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001177 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001178 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
Douglas Gregor604eb652010-08-11 02:15:33 +00001180 return ICS;
1181 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001182
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001183 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1184 AllowExplicit, InOverloadResolution, CStyle,
1185 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001186}
1187
John McCallf85e1932011-06-15 23:02:42 +00001188ImplicitConversionSequence
1189Sema::TryImplicitConversion(Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
1191 bool AllowExplicit,
1192 bool InOverloadResolution,
1193 bool CStyle,
1194 bool AllowObjCWritebackConversion) {
1195 return clang::TryImplicitConversion(*this, From, ToType,
1196 SuppressUserConversions, AllowExplicit,
1197 InOverloadResolution, CStyle,
1198 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001199}
1200
Douglas Gregor575c63a2010-04-16 22:27:05 +00001201/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001202/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001203/// converted expression. Flavor is the kind of conversion we're
1204/// performing, used in the error message. If @p AllowExplicit,
1205/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001206ExprResult
1207Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001208 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001209 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001210 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001211}
1212
John Wiegley429bb272011-04-08 18:41:53 +00001213ExprResult
1214Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001215 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001216 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001217 if (checkPlaceholderForOverload(*this, From))
1218 return ExprError();
1219
John McCallf85e1932011-06-15 23:02:42 +00001220 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1221 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001222 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001223 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001224
John McCall120d63c2010-08-24 20:38:10 +00001225 ICS = clang::TryImplicitConversion(*this, From, ToType,
1226 /*SuppressUserConversions=*/false,
1227 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001228 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001229 /*CStyle=*/false,
1230 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001231 return PerformImplicitConversion(From, ToType, ICS, Action);
1232}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001233
1234/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001235/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001236bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1237 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001238 if (Context.hasSameUnqualifiedType(FromType, ToType))
1239 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001240
John McCall00ccbef2010-12-21 00:44:39 +00001241 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1242 // where F adds one of the following at most once:
1243 // - a pointer
1244 // - a member pointer
1245 // - a block pointer
1246 CanQualType CanTo = Context.getCanonicalType(ToType);
1247 CanQualType CanFrom = Context.getCanonicalType(FromType);
1248 Type::TypeClass TyClass = CanTo->getTypeClass();
1249 if (TyClass != CanFrom->getTypeClass()) return false;
1250 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1251 if (TyClass == Type::Pointer) {
1252 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1253 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1254 } else if (TyClass == Type::BlockPointer) {
1255 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1256 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1257 } else if (TyClass == Type::MemberPointer) {
1258 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1259 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1260 } else {
1261 return false;
1262 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001263
John McCall00ccbef2010-12-21 00:44:39 +00001264 TyClass = CanTo->getTypeClass();
1265 if (TyClass != CanFrom->getTypeClass()) return false;
1266 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1267 return false;
1268 }
1269
1270 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1271 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1272 if (!EInfo.getNoReturn()) return false;
1273
1274 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1275 assert(QualType(FromFn, 0).isCanonical());
1276 if (QualType(FromFn, 0) != CanTo) return false;
1277
1278 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001279 return true;
1280}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001281
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001282/// \brief Determine whether the conversion from FromType to ToType is a valid
1283/// vector conversion.
1284///
1285/// \param ICK Will be set to the vector conversion kind, if this is a vector
1286/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001287static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1288 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001289 // We need at least one of these types to be a vector type to have a vector
1290 // conversion.
1291 if (!ToType->isVectorType() && !FromType->isVectorType())
1292 return false;
1293
1294 // Identical types require no conversions.
1295 if (Context.hasSameUnqualifiedType(FromType, ToType))
1296 return false;
1297
1298 // There are no conversions between extended vector types, only identity.
1299 if (ToType->isExtVectorType()) {
1300 // There are no conversions between extended vector types other than the
1301 // identity conversion.
1302 if (FromType->isExtVectorType())
1303 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001304
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001305 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001306 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001307 ICK = ICK_Vector_Splat;
1308 return true;
1309 }
1310 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001311
1312 // We can perform the conversion between vector types in the following cases:
1313 // 1)vector types are equivalent AltiVec and GCC vector types
1314 // 2)lax vector conversions are permitted and the vector types are of the
1315 // same size
1316 if (ToType->isVectorType() && FromType->isVectorType()) {
1317 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001318 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001319 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001320 ICK = ICK_Vector_Conversion;
1321 return true;
1322 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001323 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001324
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001325 return false;
1326}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001327
Douglas Gregor7d000652012-04-12 20:48:09 +00001328static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1329 bool InOverloadResolution,
1330 StandardConversionSequence &SCS,
1331 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001332
Douglas Gregor60d62c22008-10-31 16:23:19 +00001333/// IsStandardConversion - Determines whether there is a standard
1334/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1335/// expression From to the type ToType. Standard conversion sequences
1336/// only consider non-class types; for conversions that involve class
1337/// types, use TryImplicitConversion. If a conversion exists, SCS will
1338/// contain the standard conversion sequence required to perform this
1339/// conversion and this routine will return true. Otherwise, this
1340/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001341static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1342 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001343 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001344 bool CStyle,
1345 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001346 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347
Douglas Gregor60d62c22008-10-31 16:23:19 +00001348 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001349 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001350 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001351 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001352 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001353 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001354
Douglas Gregorf9201e02009-02-11 23:02:49 +00001355 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001356 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001357 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001358 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001359 return false;
1360
Mike Stump1eb44332009-09-09 15:08:12 +00001361 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001362 }
1363
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001364 // The first conversion can be an lvalue-to-rvalue conversion,
1365 // array-to-pointer conversion, or function-to-pointer conversion
1366 // (C++ 4p1).
1367
John McCall120d63c2010-08-24 20:38:10 +00001368 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001369 DeclAccessPair AccessPair;
1370 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001371 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001372 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001373 // We were able to resolve the address of the overloaded function,
1374 // so we can convert to the type of that function.
1375 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001376
1377 // we can sometimes resolve &foo<int> regardless of ToType, so check
1378 // if the type matches (identity) or we are converting to bool
1379 if (!S.Context.hasSameUnqualifiedType(
1380 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1381 QualType resultTy;
1382 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001383 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001384 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1385 // otherwise, only a boolean conversion is standard
1386 if (!ToType->isBooleanType())
1387 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389
Chandler Carruth90434232011-03-29 08:08:18 +00001390 // Check if the "from" expression is taking the address of an overloaded
1391 // function and recompute the FromType accordingly. Take advantage of the
1392 // fact that non-static member functions *must* have such an address-of
1393 // expression.
1394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1395 if (Method && !Method->isStatic()) {
1396 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1397 "Non-unary operator on non-static member address");
1398 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1399 == UO_AddrOf &&
1400 "Non-address-of operator on non-static member address");
1401 const Type *ClassType
1402 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1403 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001404 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1406 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001407 "Non-address-of operator for overloaded function expression");
1408 FromType = S.Context.getPointerType(FromType);
1409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001411 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001412 assert(S.Context.hasSameType(
1413 FromType,
1414 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001415 } else {
1416 return false;
1417 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001418 }
John McCall21480112011-08-30 00:57:29 +00001419 // Lvalue-to-rvalue conversion (C++11 4.1):
1420 // A glvalue (3.10) of a non-function, non-array type T can
1421 // be converted to a prvalue.
1422 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001423 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001424 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001425 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001426 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001427
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001428 // C11 6.3.2.1p2:
1429 // ... if the lvalue has atomic type, the value has the non-atomic version
1430 // of the type of the lvalue ...
1431 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1432 FromType = Atomic->getValueType();
1433
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434 // If T is a non-class type, the type of the rvalue is the
1435 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001436 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1437 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001438 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001439 } else if (FromType->isArrayType()) {
1440 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442
1443 // An lvalue or rvalue of type "array of N T" or "array of unknown
1444 // bound of T" can be converted to an rvalue of type "pointer to
1445 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001446 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001447
John McCall120d63c2010-08-24 20:38:10 +00001448 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001449 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001450 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001451
1452 // For the purpose of ranking in overload resolution
1453 // (13.3.3.1.1), this conversion is considered an
1454 // array-to-pointer conversion followed by a qualification
1455 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001456 SCS.Second = ICK_Identity;
1457 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001458 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001459 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001460 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001461 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001462 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001463 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001464 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465
1466 // An lvalue of function type T can be converted to an rvalue of
1467 // type "pointer to T." The result is a pointer to the
1468 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001469 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001470 } else {
1471 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001472 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001473 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001474 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001475
1476 // The second conversion can be an integral promotion, floating
1477 // point promotion, integral conversion, floating point conversion,
1478 // floating-integral conversion, pointer conversion,
1479 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001480 // For overloading in C, this can also be a "compatible-type"
1481 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001482 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001483 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001484 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485 // The unqualified versions of the types are the same: there's no
1486 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001487 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001488 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001489 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001490 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001491 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001492 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001493 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001494 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001495 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001496 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001497 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001498 SCS.Second = ICK_Complex_Promotion;
1499 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001500 } else if (ToType->isBooleanType() &&
1501 (FromType->isArithmeticType() ||
1502 FromType->isAnyPointerType() ||
1503 FromType->isBlockPointerType() ||
1504 FromType->isMemberPointerType() ||
1505 FromType->isNullPtrType())) {
1506 // Boolean conversions (C++ 4.12).
1507 SCS.Second = ICK_Boolean_Conversion;
1508 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001509 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001510 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001511 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001512 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001513 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001514 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001515 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001516 SCS.Second = ICK_Complex_Conversion;
1517 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001518 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1519 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001520 // Complex-real conversions (C99 6.3.1.7)
1521 SCS.Second = ICK_Complex_Real;
1522 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001523 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001524 // Floating point conversions (C++ 4.8).
1525 SCS.Second = ICK_Floating_Conversion;
1526 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001527 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001528 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001529 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001530 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001531 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001532 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001533 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001534 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001535 SCS.Second = ICK_Block_Pointer_Conversion;
1536 } else if (AllowObjCWritebackConversion &&
1537 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1538 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001539 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1540 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001541 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001543 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001544 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001545 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001546 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001547 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001548 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001549 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001550 SCS.Second = SecondICK;
1551 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001552 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001553 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001554 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001555 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001556 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001557 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001558 // Treat a conversion that strips "noreturn" as an identity conversion.
1559 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001560 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1561 InOverloadResolution,
1562 SCS, CStyle)) {
1563 SCS.Second = ICK_TransparentUnionConversion;
1564 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001565 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1566 CStyle)) {
1567 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001568 // appropriately.
1569 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001570 } else {
1571 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001572 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001574 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001576 QualType CanonFrom;
1577 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001578 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001579 bool ObjCLifetimeConversion;
1580 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1581 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001583 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001584 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001585 CanonFrom = S.Context.getCanonicalType(FromType);
1586 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587 } else {
1588 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589 SCS.Third = ICK_Identity;
1590
Mike Stump1eb44332009-09-09 15:08:12 +00001591 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 // [...] Any difference in top-level cv-qualification is
1593 // subsumed by the initialization itself and does not constitute
1594 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001595 CanonFrom = S.Context.getCanonicalType(FromType);
1596 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001598 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001599 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001600 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1601 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001602 FromType = ToType;
1603 CanonFrom = CanonTo;
1604 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001605 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001606 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001607
1608 // If we have not converted the argument type to the parameter type,
1609 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001610 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001611 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612
Douglas Gregor60d62c22008-10-31 16:23:19 +00001613 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001614}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001615
1616static bool
1617IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1618 QualType &ToType,
1619 bool InOverloadResolution,
1620 StandardConversionSequence &SCS,
1621 bool CStyle) {
1622
1623 const RecordType *UT = ToType->getAsUnionType();
1624 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1625 return false;
1626 // The field to initialize within the transparent union.
1627 RecordDecl *UD = UT->getDecl();
1628 // It's compatible if the expression matches any of the fields.
1629 for (RecordDecl::field_iterator it = UD->field_begin(),
1630 itend = UD->field_end();
1631 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001632 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1633 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001634 ToType = it->getType();
1635 return true;
1636 }
1637 }
1638 return false;
1639}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001640
1641/// IsIntegralPromotion - Determines whether the conversion from the
1642/// expression From (whose potentially-adjusted type is FromType) to
1643/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1644/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001645bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001646 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001647 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001648 if (!To) {
1649 return false;
1650 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001651
1652 // An rvalue of type char, signed char, unsigned char, short int, or
1653 // unsigned short int can be converted to an rvalue of type int if
1654 // int can represent all the values of the source type; otherwise,
1655 // the source rvalue can be converted to an rvalue of type unsigned
1656 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001657 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1658 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659 if (// We can promote any signed, promotable integer type to an int
1660 (FromType->isSignedIntegerType() ||
1661 // We can promote any unsigned integer type whose size is
1662 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001663 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001664 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001666 }
1667
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001668 return To->getKind() == BuiltinType::UInt;
1669 }
1670
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001671 // C++0x [conv.prom]p3:
1672 // A prvalue of an unscoped enumeration type whose underlying type is not
1673 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1674 // following types that can represent all the values of the enumeration
1675 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1676 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001677 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001679 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680 // with lowest integer conversion rank (4.13) greater than the rank of long
1681 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001682 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001683 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1684 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1685 // provided for a scoped enumeration.
1686 if (FromEnumType->getDecl()->isScoped())
1687 return false;
1688
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001689 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001691 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001692 return Context.hasSameUnqualifiedType(ToType,
1693 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001694 }
John McCall842aef82009-12-09 09:09:27 +00001695
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001696 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001697 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1698 // to an rvalue a prvalue of the first of the following types that can
1699 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001700 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001702 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001704 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001706 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001707 // Determine whether the type we're converting from is signed or
1708 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001709 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001711
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001712 // The types we'll try to promote to, in the appropriate
1713 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001714 QualType PromoteTypes[6] = {
1715 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001716 Context.LongTy, Context.UnsignedLongTy ,
1717 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001719 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001720 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1721 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001722 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001723 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1724 // We found the type that we can promote to. If this is the
1725 // type we wanted, we have a promotion. Otherwise, no
1726 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001727 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 }
1729 }
1730 }
1731
1732 // An rvalue for an integral bit-field (9.6) can be converted to an
1733 // rvalue of type int if int can represent all the values of the
1734 // bit-field; otherwise, it can be converted to unsigned int if
1735 // unsigned int can represent all the values of the bit-field. If
1736 // the bit-field is larger yet, no integral promotion applies to
1737 // it. If the bit-field has an enumerated type, it is treated as any
1738 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001739 // FIXME: We should delay checking of bit-fields until we actually perform the
1740 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001741 using llvm::APSInt;
1742 if (From)
1743 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001744 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001745 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001746 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1747 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1748 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Douglas Gregor86f19402008-12-20 23:49:58 +00001750 // Are we promoting to an int from a bitfield that fits in an int?
1751 if (BitWidth < ToSize ||
1752 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1753 return To->getKind() == BuiltinType::Int;
1754 }
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Douglas Gregor86f19402008-12-20 23:49:58 +00001756 // Are we promoting to an unsigned int from an unsigned bitfield
1757 // that fits into an unsigned int?
1758 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1759 return To->getKind() == BuiltinType::UInt;
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor86f19402008-12-20 23:49:58 +00001762 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001763 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001766 // An rvalue of type bool can be converted to an rvalue of type int,
1767 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001768 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001770 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771
1772 return false;
1773}
1774
1775/// IsFloatingPointPromotion - Determines whether the conversion from
1776/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1777/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001778bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001779 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1780 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001781 /// An rvalue of type float can be converted to an rvalue of type
1782 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001783 if (FromBuiltin->getKind() == BuiltinType::Float &&
1784 ToBuiltin->getKind() == BuiltinType::Double)
1785 return true;
1786
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001787 // C99 6.3.1.5p1:
1788 // When a float is promoted to double or long double, or a
1789 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001790 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001791 (FromBuiltin->getKind() == BuiltinType::Float ||
1792 FromBuiltin->getKind() == BuiltinType::Double) &&
1793 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1794 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001795
1796 // Half can be promoted to float.
1797 if (FromBuiltin->getKind() == BuiltinType::Half &&
1798 ToBuiltin->getKind() == BuiltinType::Float)
1799 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001800 }
1801
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 return false;
1803}
1804
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001805/// \brief Determine if a conversion is a complex promotion.
1806///
1807/// A complex promotion is defined as a complex -> complex conversion
1808/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001809/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001810bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001811 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001812 if (!FromComplex)
1813 return false;
1814
John McCall183700f2009-09-21 23:43:11 +00001815 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001816 if (!ToComplex)
1817 return false;
1818
1819 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001820 ToComplex->getElementType()) ||
1821 IsIntegralPromotion(0, FromComplex->getElementType(),
1822 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001823}
1824
Douglas Gregorcb7de522008-11-26 23:31:11 +00001825/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1826/// the pointer type FromPtr to a pointer to type ToPointee, with the
1827/// same type qualifiers as FromPtr has on its pointee type. ToType,
1828/// if non-empty, will be a pointer to ToType that may or may not have
1829/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001830///
Mike Stump1eb44332009-09-09 15:08:12 +00001831static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001832BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001833 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001834 ASTContext &Context,
1835 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001836 assert((FromPtr->getTypeClass() == Type::Pointer ||
1837 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1838 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001839
John McCallf85e1932011-06-15 23:02:42 +00001840 /// Conversions to 'id' subsume cv-qualifier conversions.
1841 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001842 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001843
1844 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001845 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001846 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001847 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001848
John McCallf85e1932011-06-15 23:02:42 +00001849 if (StripObjCLifetime)
1850 Quals.removeObjCLifetime();
1851
Mike Stump1eb44332009-09-09 15:08:12 +00001852 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001853 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001854 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001855 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001856 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001857
1858 // Build a pointer to ToPointee. It has the right qualifiers
1859 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001860 if (isa<ObjCObjectPointerType>(ToType))
1861 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001862 return Context.getPointerType(ToPointee);
1863 }
1864
1865 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001866 QualType QualifiedCanonToPointee
1867 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868
Douglas Gregorda80f742010-12-01 21:43:58 +00001869 if (isa<ObjCObjectPointerType>(ToType))
1870 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1871 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001872}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001873
Mike Stump1eb44332009-09-09 15:08:12 +00001874static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001875 bool InOverloadResolution,
1876 ASTContext &Context) {
1877 // Handle value-dependent integral null pointer constants correctly.
1878 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1879 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001880 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001881 return !InOverloadResolution;
1882
Douglas Gregorce940492009-09-25 04:25:58 +00001883 return Expr->isNullPointerConstant(Context,
1884 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1885 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001886}
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001888/// IsPointerConversion - Determines whether the conversion of the
1889/// expression From, which has the (possibly adjusted) type FromType,
1890/// can be converted to the type ToType via a pointer conversion (C++
1891/// 4.10). If so, returns true and places the converted type (that
1892/// might differ from ToType in its cv-qualifiers at some level) into
1893/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001894///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001895/// This routine also supports conversions to and from block pointers
1896/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1897/// pointers to interfaces. FIXME: Once we've determined the
1898/// appropriate overloading rules for Objective-C, we may want to
1899/// split the Objective-C checks into a different routine; however,
1900/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001901/// conversions, so for now they live here. IncompatibleObjC will be
1902/// set if the conversion is an allowed Objective-C conversion that
1903/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001904bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001905 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001906 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001907 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001908 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001909 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1910 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001911 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001912
Mike Stump1eb44332009-09-09 15:08:12 +00001913 // Conversion from a null pointer constant to any Objective-C pointer type.
1914 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001915 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001916 ConvertedType = ToType;
1917 return true;
1918 }
1919
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001920 // Blocks: Block pointers can be converted to void*.
1921 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001922 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001923 ConvertedType = ToType;
1924 return true;
1925 }
1926 // Blocks: A null pointer constant can be converted to a block
1927 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001928 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001929 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001930 ConvertedType = ToType;
1931 return true;
1932 }
1933
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001934 // If the left-hand-side is nullptr_t, the right side can be a null
1935 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001936 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001938 ConvertedType = ToType;
1939 return true;
1940 }
1941
Ted Kremenek6217b802009-07-29 21:53:49 +00001942 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001943 if (!ToTypePtr)
1944 return false;
1945
1946 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001947 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001948 ConvertedType = ToType;
1949 return true;
1950 }
Sebastian Redl07779722008-10-31 14:43:28 +00001951
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001952 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001953 // , including objective-c pointers.
1954 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001955 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001956 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001957 ConvertedType = BuildSimilarlyQualifiedPointerType(
1958 FromType->getAs<ObjCObjectPointerType>(),
1959 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001960 ToType, Context);
1961 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001962 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001963 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001964 if (!FromTypePtr)
1965 return false;
1966
1967 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001968
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001969 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001970 // pointer conversion, so don't do all of the work below.
1971 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1972 return false;
1973
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001974 // An rvalue of type "pointer to cv T," where T is an object type,
1975 // can be converted to an rvalue of type "pointer to cv void" (C++
1976 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001977 if (FromPointeeType->isIncompleteOrObjectType() &&
1978 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001979 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001980 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001981 ToType, Context,
1982 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001983 return true;
1984 }
1985
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001986 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001987 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001988 ToPointeeType->isVoidType()) {
1989 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1990 ToPointeeType,
1991 ToType, Context);
1992 return true;
1993 }
1994
Douglas Gregorf9201e02009-02-11 23:02:49 +00001995 // When we're overloading in C, we allow a special kind of pointer
1996 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001997 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001998 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002000 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002001 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002002 return true;
2003 }
2004
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002005 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002006 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002007 // An rvalue of type "pointer to cv D," where D is a class type,
2008 // can be converted to an rvalue of type "pointer to cv B," where
2009 // B is a base class (clause 10) of D. If B is an inaccessible
2010 // (clause 11) or ambiguous (10.2) base class of D, a program that
2011 // necessitates this conversion is ill-formed. The result of the
2012 // conversion is a pointer to the base class sub-object of the
2013 // derived class object. The null pointer value is converted to
2014 // the null pointer value of the destination type.
2015 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002016 // Note that we do not check for ambiguity or inaccessibility
2017 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002018 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002019 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002021 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002022 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002024 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002025 ToType, Context);
2026 return true;
2027 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002028
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002029 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2030 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2031 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2032 ToPointeeType,
2033 ToType, Context);
2034 return true;
2035 }
2036
Douglas Gregorc7887512008-12-19 19:13:09 +00002037 return false;
2038}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002039
2040/// \brief Adopt the given qualifiers for the given type.
2041static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2042 Qualifiers TQs = T.getQualifiers();
2043
2044 // Check whether qualifiers already match.
2045 if (TQs == Qs)
2046 return T;
2047
2048 if (Qs.compatiblyIncludes(TQs))
2049 return Context.getQualifiedType(T, Qs);
2050
2051 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2052}
Douglas Gregorc7887512008-12-19 19:13:09 +00002053
2054/// isObjCPointerConversion - Determines whether this is an
2055/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2056/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002057bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002058 QualType& ConvertedType,
2059 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002060 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002061 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002063 // The set of qualifiers on the type we're converting from.
2064 Qualifiers FromQualifiers = FromType.getQualifiers();
2065
Steve Naroff14108da2009-07-10 23:34:53 +00002066 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002067 const ObjCObjectPointerType* ToObjCPtr =
2068 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002069 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002070 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002071
Steve Naroff14108da2009-07-10 23:34:53 +00002072 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002073 // If the pointee types are the same (ignoring qualifications),
2074 // then this is not a pointer conversion.
2075 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2076 FromObjCPtr->getPointeeType()))
2077 return false;
2078
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002079 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002080 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002081 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002082 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002083 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002084 return true;
2085 }
2086 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002087 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002088 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002089 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002090 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002091 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002092 return true;
2093 }
2094 // Objective C++: We're able to convert from a pointer to an
2095 // interface to a pointer to a different interface.
2096 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002097 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2098 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002099 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002100 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2101 FromObjCPtr->getPointeeType()))
2102 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002104 ToObjCPtr->getPointeeType(),
2105 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002107 return true;
2108 }
2109
2110 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2111 // Okay: this is some kind of implicit downcast of Objective-C
2112 // interfaces, which is permitted. However, we're going to
2113 // complain about it.
2114 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002116 ToObjCPtr->getPointeeType(),
2117 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002118 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002119 return true;
2120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121 }
Steve Naroff14108da2009-07-10 23:34:53 +00002122 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002123 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002124 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002125 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002126 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002127 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002128 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002129 // to a block pointer type.
2130 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002131 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002132 return true;
2133 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002134 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002137 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002139 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002140 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002141 return true;
2142 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002143 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002144 return false;
2145
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002146 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002147 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002148 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002149 else if (const BlockPointerType *FromBlockPtr =
2150 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002151 FromPointeeType = FromBlockPtr->getPointeeType();
2152 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002153 return false;
2154
Douglas Gregorc7887512008-12-19 19:13:09 +00002155 // If we have pointers to pointers, recursively check whether this
2156 // is an Objective-C conversion.
2157 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2159 IncompatibleObjC)) {
2160 // We always complain about this conversion.
2161 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002162 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002163 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002164 return true;
2165 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002166 // Allow conversion of pointee being objective-c pointer to another one;
2167 // as in I* to id.
2168 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2169 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2170 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2171 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002172
Douglas Gregorda80f742010-12-01 21:43:58 +00002173 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002174 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002175 return true;
2176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002178 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002179 // differences in the argument and result types are in Objective-C
2180 // pointer conversions. If so, we permit the conversion (but
2181 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002182 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002183 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002184 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002185 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002186 if (FromFunctionType && ToFunctionType) {
2187 // If the function types are exactly the same, this isn't an
2188 // Objective-C pointer conversion.
2189 if (Context.getCanonicalType(FromPointeeType)
2190 == Context.getCanonicalType(ToPointeeType))
2191 return false;
2192
2193 // Perform the quick checks that will tell us whether these
2194 // function types are obviously different.
2195 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2196 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2197 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2198 return false;
2199
2200 bool HasObjCConversion = false;
2201 if (Context.getCanonicalType(FromFunctionType->getResultType())
2202 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2203 // Okay, the types match exactly. Nothing to do.
2204 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2205 ToFunctionType->getResultType(),
2206 ConvertedType, IncompatibleObjC)) {
2207 // Okay, we have an Objective-C pointer conversion.
2208 HasObjCConversion = true;
2209 } else {
2210 // Function types are too different. Abort.
2211 return false;
2212 }
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Douglas Gregorc7887512008-12-19 19:13:09 +00002214 // Check argument types.
2215 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2216 ArgIdx != NumArgs; ++ArgIdx) {
2217 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2218 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2219 if (Context.getCanonicalType(FromArgType)
2220 == Context.getCanonicalType(ToArgType)) {
2221 // Okay, the types match exactly. Nothing to do.
2222 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2223 ConvertedType, IncompatibleObjC)) {
2224 // Okay, we have an Objective-C pointer conversion.
2225 HasObjCConversion = true;
2226 } else {
2227 // Argument types are too different. Abort.
2228 return false;
2229 }
2230 }
2231
2232 if (HasObjCConversion) {
2233 // We had an Objective-C conversion. Allow this pointer
2234 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002236 IncompatibleObjC = true;
2237 return true;
2238 }
2239 }
2240
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002241 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002242}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002243
John McCallf85e1932011-06-15 23:02:42 +00002244/// \brief Determine whether this is an Objective-C writeback conversion,
2245/// used for parameter passing when performing automatic reference counting.
2246///
2247/// \param FromType The type we're converting form.
2248///
2249/// \param ToType The type we're converting to.
2250///
2251/// \param ConvertedType The type that will be produced after applying
2252/// this conversion.
2253bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2254 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002255 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002256 Context.hasSameUnqualifiedType(FromType, ToType))
2257 return false;
2258
2259 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2260 QualType ToPointee;
2261 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2262 ToPointee = ToPointer->getPointeeType();
2263 else
2264 return false;
2265
2266 Qualifiers ToQuals = ToPointee.getQualifiers();
2267 if (!ToPointee->isObjCLifetimeType() ||
2268 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002269 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002270 return false;
2271
2272 // Argument must be a pointer to __strong to __weak.
2273 QualType FromPointee;
2274 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2275 FromPointee = FromPointer->getPointeeType();
2276 else
2277 return false;
2278
2279 Qualifiers FromQuals = FromPointee.getQualifiers();
2280 if (!FromPointee->isObjCLifetimeType() ||
2281 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2282 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2283 return false;
2284
2285 // Make sure that we have compatible qualifiers.
2286 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2287 if (!ToQuals.compatiblyIncludes(FromQuals))
2288 return false;
2289
2290 // Remove qualifiers from the pointee type we're converting from; they
2291 // aren't used in the compatibility check belong, and we'll be adding back
2292 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2293 FromPointee = FromPointee.getUnqualifiedType();
2294
2295 // The unqualified form of the pointee types must be compatible.
2296 ToPointee = ToPointee.getUnqualifiedType();
2297 bool IncompatibleObjC;
2298 if (Context.typesAreCompatible(FromPointee, ToPointee))
2299 FromPointee = ToPointee;
2300 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2301 IncompatibleObjC))
2302 return false;
2303
2304 /// \brief Construct the type we're converting to, which is a pointer to
2305 /// __autoreleasing pointee.
2306 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2307 ConvertedType = Context.getPointerType(FromPointee);
2308 return true;
2309}
2310
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002311bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2312 QualType& ConvertedType) {
2313 QualType ToPointeeType;
2314 if (const BlockPointerType *ToBlockPtr =
2315 ToType->getAs<BlockPointerType>())
2316 ToPointeeType = ToBlockPtr->getPointeeType();
2317 else
2318 return false;
2319
2320 QualType FromPointeeType;
2321 if (const BlockPointerType *FromBlockPtr =
2322 FromType->getAs<BlockPointerType>())
2323 FromPointeeType = FromBlockPtr->getPointeeType();
2324 else
2325 return false;
2326 // We have pointer to blocks, check whether the only
2327 // differences in the argument and result types are in Objective-C
2328 // pointer conversions. If so, we permit the conversion.
2329
2330 const FunctionProtoType *FromFunctionType
2331 = FromPointeeType->getAs<FunctionProtoType>();
2332 const FunctionProtoType *ToFunctionType
2333 = ToPointeeType->getAs<FunctionProtoType>();
2334
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002335 if (!FromFunctionType || !ToFunctionType)
2336 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002337
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002338 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002339 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002340
2341 // Perform the quick checks that will tell us whether these
2342 // function types are obviously different.
2343 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2344 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2345 return false;
2346
2347 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2348 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2349 if (FromEInfo != ToEInfo)
2350 return false;
2351
2352 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002353 if (Context.hasSameType(FromFunctionType->getResultType(),
2354 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002355 // Okay, the types match exactly. Nothing to do.
2356 } else {
2357 QualType RHS = FromFunctionType->getResultType();
2358 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002359 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002360 !RHS.hasQualifiers() && LHS.hasQualifiers())
2361 LHS = LHS.getUnqualifiedType();
2362
2363 if (Context.hasSameType(RHS,LHS)) {
2364 // OK exact match.
2365 } else if (isObjCPointerConversion(RHS, LHS,
2366 ConvertedType, IncompatibleObjC)) {
2367 if (IncompatibleObjC)
2368 return false;
2369 // Okay, we have an Objective-C pointer conversion.
2370 }
2371 else
2372 return false;
2373 }
2374
2375 // Check argument types.
2376 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2377 ArgIdx != NumArgs; ++ArgIdx) {
2378 IncompatibleObjC = false;
2379 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2380 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2381 if (Context.hasSameType(FromArgType, ToArgType)) {
2382 // Okay, the types match exactly. Nothing to do.
2383 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2384 ConvertedType, IncompatibleObjC)) {
2385 if (IncompatibleObjC)
2386 return false;
2387 // Okay, we have an Objective-C pointer conversion.
2388 } else
2389 // Argument types are too different. Abort.
2390 return false;
2391 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002392 if (LangOpts.ObjCAutoRefCount &&
2393 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2394 ToFunctionType))
2395 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002396
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002397 ConvertedType = ToType;
2398 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002399}
2400
Richard Trieu6efd4c52011-11-23 22:32:32 +00002401enum {
2402 ft_default,
2403 ft_different_class,
2404 ft_parameter_arity,
2405 ft_parameter_mismatch,
2406 ft_return_type,
2407 ft_qualifer_mismatch
2408};
2409
2410/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2411/// function types. Catches different number of parameter, mismatch in
2412/// parameter types, and different return types.
2413void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2414 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002415 // If either type is not valid, include no extra info.
2416 if (FromType.isNull() || ToType.isNull()) {
2417 PDiag << ft_default;
2418 return;
2419 }
2420
Richard Trieu6efd4c52011-11-23 22:32:32 +00002421 // Get the function type from the pointers.
2422 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2423 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2424 *ToMember = ToType->getAs<MemberPointerType>();
2425 if (FromMember->getClass() != ToMember->getClass()) {
2426 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2427 << QualType(FromMember->getClass(), 0);
2428 return;
2429 }
2430 FromType = FromMember->getPointeeType();
2431 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002432 }
2433
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002434 if (FromType->isPointerType())
2435 FromType = FromType->getPointeeType();
2436 if (ToType->isPointerType())
2437 ToType = ToType->getPointeeType();
2438
2439 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002440 FromType = FromType.getNonReferenceType();
2441 ToType = ToType.getNonReferenceType();
2442
Richard Trieu6efd4c52011-11-23 22:32:32 +00002443 // Don't print extra info for non-specialized template functions.
2444 if (FromType->isInstantiationDependentType() &&
2445 !FromType->getAs<TemplateSpecializationType>()) {
2446 PDiag << ft_default;
2447 return;
2448 }
2449
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002450 // No extra info for same types.
2451 if (Context.hasSameType(FromType, ToType)) {
2452 PDiag << ft_default;
2453 return;
2454 }
2455
Richard Trieu6efd4c52011-11-23 22:32:32 +00002456 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2457 *ToFunction = ToType->getAs<FunctionProtoType>();
2458
2459 // Both types need to be function types.
2460 if (!FromFunction || !ToFunction) {
2461 PDiag << ft_default;
2462 return;
2463 }
2464
2465 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2466 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2467 << FromFunction->getNumArgs();
2468 return;
2469 }
2470
2471 // Handle different parameter types.
2472 unsigned ArgPos;
2473 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2474 PDiag << ft_parameter_mismatch << ArgPos + 1
2475 << ToFunction->getArgType(ArgPos)
2476 << FromFunction->getArgType(ArgPos);
2477 return;
2478 }
2479
2480 // Handle different return type.
2481 if (!Context.hasSameType(FromFunction->getResultType(),
2482 ToFunction->getResultType())) {
2483 PDiag << ft_return_type << ToFunction->getResultType()
2484 << FromFunction->getResultType();
2485 return;
2486 }
2487
2488 unsigned FromQuals = FromFunction->getTypeQuals(),
2489 ToQuals = ToFunction->getTypeQuals();
2490 if (FromQuals != ToQuals) {
2491 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2492 return;
2493 }
2494
2495 // Unable to find a difference, so add no extra info.
2496 PDiag << ft_default;
2497}
2498
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002499/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002500/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002501/// they have same number of arguments. This routine assumes that Objective-C
2502/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002503/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002504/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002506 const FunctionProtoType *NewType,
2507 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002508 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002509 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2510 N = NewType->arg_type_begin(),
2511 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2512 if (!Context.hasSameType(*O, *N)) {
2513 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2514 return false;
2515 }
2516 }
2517 return true;
2518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002519
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002520 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2521 N = NewType->arg_type_begin(),
2522 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2523 QualType ToType = (*O);
2524 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002525 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002526 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2527 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002528 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2529 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2530 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2531 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002532 continue;
2533 }
John McCallc12c5bb2010-05-15 11:32:37 +00002534 else if (const ObjCObjectPointerType *PTTo =
2535 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002536 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002537 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002538 if (Context.hasSameUnqualifiedType(
2539 PTTo->getObjectType()->getBaseType(),
2540 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002541 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002542 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002543 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002544 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002545 }
2546 }
2547 return true;
2548}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002549
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550/// CheckPointerConversion - Check the pointer conversion from the
2551/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002552/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002553/// conversions for which IsPointerConversion has already returned
2554/// true. It returns true and produces a diagnostic if there was an
2555/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002556bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002557 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002558 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002559 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002560 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002561 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562
John McCalldaa8e4e2010-11-15 09:13:47 +00002563 Kind = CK_BitCast;
2564
David Blaikie50800fc2012-08-08 17:33:31 +00002565 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2566 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2567 Expr::NPCK_ZeroExpression) {
2568 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2569 DiagRuntimeBehavior(From->getExprLoc(), From,
2570 PDiag(diag::warn_impcast_bool_to_null_pointer)
2571 << ToType << From->getSourceRange());
2572 else if (!isUnevaluatedContext())
2573 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2574 << ToType << From->getSourceRange();
2575 }
John McCall1d9b3b22011-09-09 05:25:32 +00002576 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2577 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002578 QualType FromPointeeType = FromPtrType->getPointeeType(),
2579 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002580
Douglas Gregor5fccd362010-03-03 23:55:11 +00002581 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2582 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002583 // We must have a derived-to-base conversion. Check an
2584 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002585 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2586 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002587 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002588 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002589 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002590
Anders Carlsson61faec12009-09-12 04:46:44 +00002591 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002592 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002593 }
2594 }
John McCall1d9b3b22011-09-09 05:25:32 +00002595 } else if (const ObjCObjectPointerType *ToPtrType =
2596 ToType->getAs<ObjCObjectPointerType>()) {
2597 if (const ObjCObjectPointerType *FromPtrType =
2598 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002599 // Objective-C++ conversions are always okay.
2600 // FIXME: We should have a different class of conversions for the
2601 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002602 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002603 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002604 } else if (FromType->isBlockPointerType()) {
2605 Kind = CK_BlockPointerToObjCPointerCast;
2606 } else {
2607 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002608 }
John McCall1d9b3b22011-09-09 05:25:32 +00002609 } else if (ToType->isBlockPointerType()) {
2610 if (!FromType->isBlockPointerType())
2611 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002612 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002613
2614 // We shouldn't fall into this case unless it's valid for other
2615 // reasons.
2616 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2617 Kind = CK_NullToPointer;
2618
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002619 return false;
2620}
2621
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002622/// IsMemberPointerConversion - Determines whether the conversion of the
2623/// expression From, which has the (possibly adjusted) type FromType, can be
2624/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2625/// If so, returns true and places the converted type (that might differ from
2626/// ToType in its cv-qualifiers at some level) into ConvertedType.
2627bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002628 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002629 bool InOverloadResolution,
2630 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002631 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002632 if (!ToTypePtr)
2633 return false;
2634
2635 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002636 if (From->isNullPointerConstant(Context,
2637 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2638 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002639 ConvertedType = ToType;
2640 return true;
2641 }
2642
2643 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002644 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002645 if (!FromTypePtr)
2646 return false;
2647
2648 // A pointer to member of B can be converted to a pointer to member of D,
2649 // where D is derived from B (C++ 4.11p2).
2650 QualType FromClass(FromTypePtr->getClass(), 0);
2651 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002652
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002653 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002654 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002655 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002656 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2657 ToClass.getTypePtr());
2658 return true;
2659 }
2660
2661 return false;
2662}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002664/// CheckMemberPointerConversion - Check the member pointer conversion from the
2665/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002666/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002667/// for which IsMemberPointerConversion has already returned true. It returns
2668/// true and produces a diagnostic if there was an error, or returns false
2669/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002670bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002671 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002672 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002673 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002674 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002675 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002676 if (!FromPtrType) {
2677 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002679 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002680 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002681 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002682 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002683 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002684
Ted Kremenek6217b802009-07-29 21:53:49 +00002685 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002686 assert(ToPtrType && "No member pointer cast has a target type "
2687 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002688
Sebastian Redl21593ac2009-01-28 18:33:18 +00002689 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2690 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002691
Sebastian Redl21593ac2009-01-28 18:33:18 +00002692 // FIXME: What about dependent types?
2693 assert(FromClass->isRecordType() && "Pointer into non-class.");
2694 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002695
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002696 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002697 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002698 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2699 assert(DerivationOkay &&
2700 "Should not have been called if derivation isn't OK.");
2701 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002702
Sebastian Redl21593ac2009-01-28 18:33:18 +00002703 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2704 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002705 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2706 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2707 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2708 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002710
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002711 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002712 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2713 << FromClass << ToClass << QualType(VBase, 0)
2714 << From->getSourceRange();
2715 return true;
2716 }
2717
John McCall6b2accb2010-02-10 09:31:12 +00002718 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002719 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2720 Paths.front(),
2721 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002722
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002723 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002724 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002725 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002726 return false;
2727}
2728
Douglas Gregor98cd5992008-10-21 23:43:52 +00002729/// IsQualificationConversion - Determines whether the conversion from
2730/// an rvalue of type FromType to ToType is a qualification conversion
2731/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002732///
2733/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2734/// when the qualification conversion involves a change in the Objective-C
2735/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002736bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002737Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002738 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 FromType = Context.getCanonicalType(FromType);
2740 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002741 ObjCLifetimeConversion = false;
2742
Douglas Gregor98cd5992008-10-21 23:43:52 +00002743 // If FromType and ToType are the same type, this is not a
2744 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002745 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002746 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002747
Douglas Gregor98cd5992008-10-21 23:43:52 +00002748 // (C++ 4.4p4):
2749 // A conversion can add cv-qualifiers at levels other than the first
2750 // in multi-level pointers, subject to the following rules: [...]
2751 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002752 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002753 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002754 // Within each iteration of the loop, we check the qualifiers to
2755 // determine if this still looks like a qualification
2756 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002757 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002758 // until there are no more pointers or pointers-to-members left to
2759 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002760 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002761
Douglas Gregor621c92a2011-04-25 18:40:17 +00002762 Qualifiers FromQuals = FromType.getQualifiers();
2763 Qualifiers ToQuals = ToType.getQualifiers();
2764
John McCallf85e1932011-06-15 23:02:42 +00002765 // Objective-C ARC:
2766 // Check Objective-C lifetime conversions.
2767 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2768 UnwrappedAnyPointer) {
2769 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2770 ObjCLifetimeConversion = true;
2771 FromQuals.removeObjCLifetime();
2772 ToQuals.removeObjCLifetime();
2773 } else {
2774 // Qualification conversions cannot cast between different
2775 // Objective-C lifetime qualifiers.
2776 return false;
2777 }
2778 }
2779
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002780 // Allow addition/removal of GC attributes but not changing GC attributes.
2781 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2782 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2783 FromQuals.removeObjCGCAttr();
2784 ToQuals.removeObjCGCAttr();
2785 }
2786
Douglas Gregor98cd5992008-10-21 23:43:52 +00002787 // -- for every j > 0, if const is in cv 1,j then const is in cv
2788 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002789 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002790 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Douglas Gregor98cd5992008-10-21 23:43:52 +00002792 // -- if the cv 1,j and cv 2,j are different, then const is in
2793 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002794 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002795 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002796 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Douglas Gregor98cd5992008-10-21 23:43:52 +00002798 // Keep track of whether all prior cv-qualifiers in the "to" type
2799 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002800 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002801 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002802 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002803
2804 // We are left with FromType and ToType being the pointee types
2805 // after unwrapping the original FromType and ToType the same number
2806 // of types. If we unwrapped any pointers, and if FromType and
2807 // ToType have the same unqualified type (since we checked
2808 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002809 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002810}
2811
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002812/// \brief - Determine whether this is a conversion from a scalar type to an
2813/// atomic type.
2814///
2815/// If successful, updates \c SCS's second and third steps in the conversion
2816/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002817static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2818 bool InOverloadResolution,
2819 StandardConversionSequence &SCS,
2820 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002821 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2822 if (!ToAtomic)
2823 return false;
2824
2825 StandardConversionSequence InnerSCS;
2826 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2827 InOverloadResolution, InnerSCS,
2828 CStyle, /*AllowObjCWritebackConversion=*/false))
2829 return false;
2830
2831 SCS.Second = InnerSCS.Second;
2832 SCS.setToType(1, InnerSCS.getToType(1));
2833 SCS.Third = InnerSCS.Third;
2834 SCS.QualificationIncludesObjCLifetime
2835 = InnerSCS.QualificationIncludesObjCLifetime;
2836 SCS.setToType(2, InnerSCS.getToType(2));
2837 return true;
2838}
2839
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002840static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2841 CXXConstructorDecl *Constructor,
2842 QualType Type) {
2843 const FunctionProtoType *CtorType =
2844 Constructor->getType()->getAs<FunctionProtoType>();
2845 if (CtorType->getNumArgs() > 0) {
2846 QualType FirstArg = CtorType->getArgType(0);
2847 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2848 return true;
2849 }
2850 return false;
2851}
2852
Sebastian Redl56a04282012-02-11 23:51:08 +00002853static OverloadingResult
2854IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2855 CXXRecordDecl *To,
2856 UserDefinedConversionSequence &User,
2857 OverloadCandidateSet &CandidateSet,
2858 bool AllowExplicit) {
2859 DeclContext::lookup_iterator Con, ConEnd;
2860 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2861 Con != ConEnd; ++Con) {
2862 NamedDecl *D = *Con;
2863 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2864
2865 // Find the constructor (which may be a template).
2866 CXXConstructorDecl *Constructor = 0;
2867 FunctionTemplateDecl *ConstructorTmpl
2868 = dyn_cast<FunctionTemplateDecl>(D);
2869 if (ConstructorTmpl)
2870 Constructor
2871 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2872 else
2873 Constructor = cast<CXXConstructorDecl>(D);
2874
2875 bool Usable = !Constructor->isInvalidDecl() &&
2876 S.isInitListConstructor(Constructor) &&
2877 (AllowExplicit || !Constructor->isExplicit());
2878 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002879 // If the first argument is (a reference to) the target type,
2880 // suppress conversions.
2881 bool SuppressUserConversions =
2882 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002883 if (ConstructorTmpl)
2884 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2885 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002886 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002887 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002888 else
2889 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002890 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002891 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002892 }
2893 }
2894
2895 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2896
2897 OverloadCandidateSet::iterator Best;
2898 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2899 case OR_Success: {
2900 // Record the standard conversion we used and the conversion function.
2901 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2902 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2903
2904 QualType ThisType = Constructor->getThisType(S.Context);
2905 // Initializer lists don't have conversions as such.
2906 User.Before.setAsIdentityConversion();
2907 User.HadMultipleCandidates = HadMultipleCandidates;
2908 User.ConversionFunction = Constructor;
2909 User.FoundConversionFunction = Best->FoundDecl;
2910 User.After.setAsIdentityConversion();
2911 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2912 User.After.setAllToTypes(ToType);
2913 return OR_Success;
2914 }
2915
2916 case OR_No_Viable_Function:
2917 return OR_No_Viable_Function;
2918 case OR_Deleted:
2919 return OR_Deleted;
2920 case OR_Ambiguous:
2921 return OR_Ambiguous;
2922 }
2923
2924 llvm_unreachable("Invalid OverloadResult!");
2925}
2926
Douglas Gregor734d9862009-01-30 23:27:23 +00002927/// Determines whether there is a user-defined conversion sequence
2928/// (C++ [over.ics.user]) that converts expression From to the type
2929/// ToType. If such a conversion exists, User will contain the
2930/// user-defined conversion sequence that performs such a conversion
2931/// and this routine will return true. Otherwise, this routine returns
2932/// false and User is unspecified.
2933///
Douglas Gregor734d9862009-01-30 23:27:23 +00002934/// \param AllowExplicit true if the conversion should consider C++0x
2935/// "explicit" conversion functions as well as non-explicit conversion
2936/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002937static OverloadingResult
2938IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002939 UserDefinedConversionSequence &User,
2940 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002941 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002942 // Whether we will only visit constructors.
2943 bool ConstructorsOnly = false;
2944
2945 // If the type we are conversion to is a class type, enumerate its
2946 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002947 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002948 // C++ [over.match.ctor]p1:
2949 // When objects of class type are direct-initialized (8.5), or
2950 // copy-initialized from an expression of the same or a
2951 // derived class type (8.5), overload resolution selects the
2952 // constructor. [...] For copy-initialization, the candidate
2953 // functions are all the converting constructors (12.3.1) of
2954 // that class. The argument list is the expression-list within
2955 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002956 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002957 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002958 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002959 ConstructorsOnly = true;
2960
Douglas Gregord10099e2012-05-04 16:32:21 +00002961 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002962 // RequireCompleteType may have returned true due to some invalid decl
2963 // during template instantiation, but ToType may be complete enough now
2964 // to try to recover.
2965 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002966 // We're not going to find any constructors.
2967 } else if (CXXRecordDecl *ToRecordDecl
2968 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002969
2970 Expr **Args = &From;
2971 unsigned NumArgs = 1;
2972 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002973 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002974 // But first, see if there is an init-list-contructor that will work.
2975 OverloadingResult Result = IsInitializerListConstructorConversion(
2976 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2977 if (Result != OR_No_Viable_Function)
2978 return Result;
2979 // Never mind.
2980 CandidateSet.clear();
2981
2982 // If we're list-initializing, we pass the individual elements as
2983 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002984 Args = InitList->getInits();
2985 NumArgs = InitList->getNumInits();
2986 ListInitializing = true;
2987 }
2988
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002989 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002990 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002991 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002992 NamedDecl *D = *Con;
2993 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2994
Douglas Gregordec06662009-08-21 18:42:58 +00002995 // Find the constructor (which may be a template).
2996 CXXConstructorDecl *Constructor = 0;
2997 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002998 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002999 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003000 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003001 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3002 else
John McCall9aa472c2010-03-19 07:35:19 +00003003 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003005 bool Usable = !Constructor->isInvalidDecl();
3006 if (ListInitializing)
3007 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3008 else
3009 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3010 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003011 bool SuppressUserConversions = !ConstructorsOnly;
3012 if (SuppressUserConversions && ListInitializing) {
3013 SuppressUserConversions = false;
3014 if (NumArgs == 1) {
3015 // If the first argument is (a reference to) the target type,
3016 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003017 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3018 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003019 }
3020 }
Douglas Gregordec06662009-08-21 18:42:58 +00003021 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003022 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3023 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003024 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003025 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003026 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003027 // Allow one user-defined conversion when user specifies a
3028 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003029 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003030 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003031 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003032 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003033 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003034 }
3035 }
3036
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003037 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003038 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003039 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003040 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003041 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003042 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003043 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003044 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3045 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003046 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003047 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003048 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003049 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003050 DeclAccessPair FoundDecl = I.getPair();
3051 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003052 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3053 if (isa<UsingShadowDecl>(D))
3054 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3055
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003056 CXXConversionDecl *Conv;
3057 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003058 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3059 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003060 else
John McCall32daa422010-03-31 01:36:47 +00003061 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003062
3063 if (AllowExplicit || !Conv->isExplicit()) {
3064 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003065 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3066 ActingContext, From, ToType,
3067 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003068 else
John McCall120d63c2010-08-24 20:38:10 +00003069 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3070 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003071 }
3072 }
3073 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003074 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003075
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003076 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3077
Douglas Gregor60d62c22008-10-31 16:23:19 +00003078 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003079 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003080 case OR_Success:
3081 // Record the standard conversion we used and the conversion function.
3082 if (CXXConstructorDecl *Constructor
3083 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003084 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003085
John McCall120d63c2010-08-24 20:38:10 +00003086 // C++ [over.ics.user]p1:
3087 // If the user-defined conversion is specified by a
3088 // constructor (12.3.1), the initial standard conversion
3089 // sequence converts the source type to the type required by
3090 // the argument of the constructor.
3091 //
3092 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003093 if (isa<InitListExpr>(From)) {
3094 // Initializer lists don't have conversions as such.
3095 User.Before.setAsIdentityConversion();
3096 } else {
3097 if (Best->Conversions[0].isEllipsis())
3098 User.EllipsisConversion = true;
3099 else {
3100 User.Before = Best->Conversions[0].Standard;
3101 User.EllipsisConversion = false;
3102 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003103 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003104 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003105 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003106 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003107 User.After.setAsIdentityConversion();
3108 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3109 User.After.setAllToTypes(ToType);
3110 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003111 }
3112 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003113 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003114 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003115
John McCall120d63c2010-08-24 20:38:10 +00003116 // C++ [over.ics.user]p1:
3117 //
3118 // [...] If the user-defined conversion is specified by a
3119 // conversion function (12.3.2), the initial standard
3120 // conversion sequence converts the source type to the
3121 // implicit object parameter of the conversion function.
3122 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003123 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003124 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003125 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003126 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003127
John McCall120d63c2010-08-24 20:38:10 +00003128 // C++ [over.ics.user]p2:
3129 // The second standard conversion sequence converts the
3130 // result of the user-defined conversion to the target type
3131 // for the sequence. Since an implicit conversion sequence
3132 // is an initialization, the special rules for
3133 // initialization by user-defined conversion apply when
3134 // selecting the best user-defined conversion for a
3135 // user-defined conversion sequence (see 13.3.3 and
3136 // 13.3.3.1).
3137 User.After = Best->FinalConversion;
3138 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003139 }
David Blaikie7530c032012-01-17 06:56:22 +00003140 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003141
John McCall120d63c2010-08-24 20:38:10 +00003142 case OR_No_Viable_Function:
3143 return OR_No_Viable_Function;
3144 case OR_Deleted:
3145 // No conversion here! We're done.
3146 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147
John McCall120d63c2010-08-24 20:38:10 +00003148 case OR_Ambiguous:
3149 return OR_Ambiguous;
3150 }
3151
David Blaikie7530c032012-01-17 06:56:22 +00003152 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003153}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003154
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003155bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003156Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003157 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003158 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003160 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003161 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003162 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003163 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003164 diag::err_typecheck_ambiguous_condition)
3165 << From->getType() << ToType << From->getSourceRange();
3166 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003167 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003168 diag::err_typecheck_nonviable_condition)
3169 << From->getType() << ToType << From->getSourceRange();
3170 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003171 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003174}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003175
Douglas Gregorb734e242012-02-22 17:32:19 +00003176/// \brief Compare the user-defined conversion functions or constructors
3177/// of two user-defined conversion sequences to determine whether any ordering
3178/// is possible.
3179static ImplicitConversionSequence::CompareKind
3180compareConversionFunctions(Sema &S,
3181 FunctionDecl *Function1,
3182 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003183 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003184 return ImplicitConversionSequence::Indistinguishable;
3185
3186 // Objective-C++:
3187 // If both conversion functions are implicitly-declared conversions from
3188 // a lambda closure type to a function pointer and a block pointer,
3189 // respectively, always prefer the conversion to a function pointer,
3190 // because the function pointer is more lightweight and is more likely
3191 // to keep code working.
3192 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3193 if (!Conv1)
3194 return ImplicitConversionSequence::Indistinguishable;
3195
3196 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3197 if (!Conv2)
3198 return ImplicitConversionSequence::Indistinguishable;
3199
3200 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3201 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3202 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3203 if (Block1 != Block2)
3204 return Block1? ImplicitConversionSequence::Worse
3205 : ImplicitConversionSequence::Better;
3206 }
3207
3208 return ImplicitConversionSequence::Indistinguishable;
3209}
3210
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003211/// CompareImplicitConversionSequences - Compare two implicit
3212/// conversion sequences to determine whether one is better than the
3213/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003214static ImplicitConversionSequence::CompareKind
3215CompareImplicitConversionSequences(Sema &S,
3216 const ImplicitConversionSequence& ICS1,
3217 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003218{
3219 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3220 // conversion sequences (as defined in 13.3.3.1)
3221 // -- a standard conversion sequence (13.3.3.1.1) is a better
3222 // conversion sequence than a user-defined conversion sequence or
3223 // an ellipsis conversion sequence, and
3224 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3225 // conversion sequence than an ellipsis conversion sequence
3226 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003227 //
John McCall1d318332010-01-12 00:44:57 +00003228 // C++0x [over.best.ics]p10:
3229 // For the purpose of ranking implicit conversion sequences as
3230 // described in 13.3.3.2, the ambiguous conversion sequence is
3231 // treated as a user-defined sequence that is indistinguishable
3232 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003233 if (ICS1.getKindRank() < ICS2.getKindRank())
3234 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003235 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003236 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003237
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003238 // The following checks require both conversion sequences to be of
3239 // the same kind.
3240 if (ICS1.getKind() != ICS2.getKind())
3241 return ImplicitConversionSequence::Indistinguishable;
3242
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003243 ImplicitConversionSequence::CompareKind Result =
3244 ImplicitConversionSequence::Indistinguishable;
3245
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003246 // Two implicit conversion sequences of the same form are
3247 // indistinguishable conversion sequences unless one of the
3248 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003249 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003250 Result = CompareStandardConversionSequences(S,
3251 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003252 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003253 // User-defined conversion sequence U1 is a better conversion
3254 // sequence than another user-defined conversion sequence U2 if
3255 // they contain the same user-defined conversion function or
3256 // constructor and if the second standard conversion sequence of
3257 // U1 is better than the second standard conversion sequence of
3258 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003259 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003260 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003261 Result = CompareStandardConversionSequences(S,
3262 ICS1.UserDefined.After,
3263 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003264 else
3265 Result = compareConversionFunctions(S,
3266 ICS1.UserDefined.ConversionFunction,
3267 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003268 }
3269
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003270 // List-initialization sequence L1 is a better conversion sequence than
3271 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3272 // for some X and L2 does not.
3273 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003274 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003275 ICS1.isListInitializationSequence() &&
3276 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003277 if (ICS1.isStdInitializerListElement() &&
3278 !ICS2.isStdInitializerListElement())
3279 return ImplicitConversionSequence::Better;
3280 if (!ICS1.isStdInitializerListElement() &&
3281 ICS2.isStdInitializerListElement())
3282 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003283 }
3284
3285 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003286}
3287
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003288static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3289 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3290 Qualifiers Quals;
3291 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003292 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003295 return Context.hasSameUnqualifiedType(T1, T2);
3296}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297
Douglas Gregorad323a82010-01-27 03:51:04 +00003298// Per 13.3.3.2p3, compare the given standard conversion sequences to
3299// determine if one is a proper subset of the other.
3300static ImplicitConversionSequence::CompareKind
3301compareStandardConversionSubsets(ASTContext &Context,
3302 const StandardConversionSequence& SCS1,
3303 const StandardConversionSequence& SCS2) {
3304 ImplicitConversionSequence::CompareKind Result
3305 = ImplicitConversionSequence::Indistinguishable;
3306
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003307 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003308 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003309 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3310 return ImplicitConversionSequence::Better;
3311 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3312 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313
Douglas Gregorad323a82010-01-27 03:51:04 +00003314 if (SCS1.Second != SCS2.Second) {
3315 if (SCS1.Second == ICK_Identity)
3316 Result = ImplicitConversionSequence::Better;
3317 else if (SCS2.Second == ICK_Identity)
3318 Result = ImplicitConversionSequence::Worse;
3319 else
3320 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003321 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003322 return ImplicitConversionSequence::Indistinguishable;
3323
3324 if (SCS1.Third == SCS2.Third) {
3325 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3326 : ImplicitConversionSequence::Indistinguishable;
3327 }
3328
3329 if (SCS1.Third == ICK_Identity)
3330 return Result == ImplicitConversionSequence::Worse
3331 ? ImplicitConversionSequence::Indistinguishable
3332 : ImplicitConversionSequence::Better;
3333
3334 if (SCS2.Third == ICK_Identity)
3335 return Result == ImplicitConversionSequence::Better
3336 ? ImplicitConversionSequence::Indistinguishable
3337 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338
Douglas Gregorad323a82010-01-27 03:51:04 +00003339 return ImplicitConversionSequence::Indistinguishable;
3340}
3341
Douglas Gregor440a4832011-01-26 14:52:12 +00003342/// \brief Determine whether one of the given reference bindings is better
3343/// than the other based on what kind of bindings they are.
3344static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3345 const StandardConversionSequence &SCS2) {
3346 // C++0x [over.ics.rank]p3b4:
3347 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3348 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003350 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003352 // reference*.
3353 //
3354 // FIXME: Rvalue references. We're going rogue with the above edits,
3355 // because the semantics in the current C++0x working paper (N3225 at the
3356 // time of this writing) break the standard definition of std::forward
3357 // and std::reference_wrapper when dealing with references to functions.
3358 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003359 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3360 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3361 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362
Douglas Gregor440a4832011-01-26 14:52:12 +00003363 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3364 SCS2.IsLvalueReference) ||
3365 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3366 !SCS2.IsLvalueReference);
3367}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003368
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003369/// CompareStandardConversionSequences - Compare two standard
3370/// conversion sequences to determine whether one is better than the
3371/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003372static ImplicitConversionSequence::CompareKind
3373CompareStandardConversionSequences(Sema &S,
3374 const StandardConversionSequence& SCS1,
3375 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003376{
3377 // Standard conversion sequence S1 is a better conversion sequence
3378 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3379
3380 // -- S1 is a proper subsequence of S2 (comparing the conversion
3381 // sequences in the canonical form defined by 13.3.3.1.1,
3382 // excluding any Lvalue Transformation; the identity conversion
3383 // sequence is considered to be a subsequence of any
3384 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003385 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003386 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003387 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003388
3389 // -- the rank of S1 is better than the rank of S2 (by the rules
3390 // defined below), or, if not that,
3391 ImplicitConversionRank Rank1 = SCS1.getRank();
3392 ImplicitConversionRank Rank2 = SCS2.getRank();
3393 if (Rank1 < Rank2)
3394 return ImplicitConversionSequence::Better;
3395 else if (Rank2 < Rank1)
3396 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003397
Douglas Gregor57373262008-10-22 14:17:15 +00003398 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3399 // are indistinguishable unless one of the following rules
3400 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003401
Douglas Gregor57373262008-10-22 14:17:15 +00003402 // A conversion that is not a conversion of a pointer, or
3403 // pointer to member, to bool is better than another conversion
3404 // that is such a conversion.
3405 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3406 return SCS2.isPointerConversionToBool()
3407 ? ImplicitConversionSequence::Better
3408 : ImplicitConversionSequence::Worse;
3409
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003410 // C++ [over.ics.rank]p4b2:
3411 //
3412 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003413 // conversion of B* to A* is better than conversion of B* to
3414 // void*, and conversion of A* to void* is better than conversion
3415 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003416 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003417 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003418 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003419 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003420 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3421 // Exactly one of the conversion sequences is a conversion to
3422 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003423 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3424 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003425 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3426 // Neither conversion sequence converts to a void pointer; compare
3427 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003428 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003429 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003430 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003431 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3432 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003433 // Both conversion sequences are conversions to void
3434 // pointers. Compare the source types to determine if there's an
3435 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003436 QualType FromType1 = SCS1.getFromType();
3437 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003438
3439 // Adjust the types we're converting from via the array-to-pointer
3440 // conversion, if we need to.
3441 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003442 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003443 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003444 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003445
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003446 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3447 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003448
John McCall120d63c2010-08-24 20:38:10 +00003449 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003450 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003451 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003452 return ImplicitConversionSequence::Worse;
3453
3454 // Objective-C++: If one interface is more specific than the
3455 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003456 const ObjCObjectPointerType* FromObjCPtr1
3457 = FromType1->getAs<ObjCObjectPointerType>();
3458 const ObjCObjectPointerType* FromObjCPtr2
3459 = FromType2->getAs<ObjCObjectPointerType>();
3460 if (FromObjCPtr1 && FromObjCPtr2) {
3461 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3462 FromObjCPtr2);
3463 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3464 FromObjCPtr1);
3465 if (AssignLeft != AssignRight) {
3466 return AssignLeft? ImplicitConversionSequence::Better
3467 : ImplicitConversionSequence::Worse;
3468 }
Douglas Gregor01919692009-12-13 21:37:05 +00003469 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003470 }
Douglas Gregor57373262008-10-22 14:17:15 +00003471
3472 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3473 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003474 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003475 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003476 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003477
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003478 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003479 // Check for a better reference binding based on the kind of bindings.
3480 if (isBetterReferenceBindingKind(SCS1, SCS2))
3481 return ImplicitConversionSequence::Better;
3482 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3483 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003485 // C++ [over.ics.rank]p3b4:
3486 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3487 // which the references refer are the same type except for
3488 // top-level cv-qualifiers, and the type to which the reference
3489 // initialized by S2 refers is more cv-qualified than the type
3490 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003491 QualType T1 = SCS1.getToType(2);
3492 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003493 T1 = S.Context.getCanonicalType(T1);
3494 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003495 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003496 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3497 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003498 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003499 // Objective-C++ ARC: If the references refer to objects with different
3500 // lifetimes, prefer bindings that don't change lifetime.
3501 if (SCS1.ObjCLifetimeConversionBinding !=
3502 SCS2.ObjCLifetimeConversionBinding) {
3503 return SCS1.ObjCLifetimeConversionBinding
3504 ? ImplicitConversionSequence::Worse
3505 : ImplicitConversionSequence::Better;
3506 }
3507
Chandler Carruth6df868e2010-12-12 08:17:55 +00003508 // If the type is an array type, promote the element qualifiers to the
3509 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003510 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003511 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003512 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003513 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003514 if (T2.isMoreQualifiedThan(T1))
3515 return ImplicitConversionSequence::Better;
3516 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003517 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003518 }
3519 }
Douglas Gregor57373262008-10-22 14:17:15 +00003520
Francois Pichet1c98d622011-09-18 21:37:37 +00003521 // In Microsoft mode, prefer an integral conversion to a
3522 // floating-to-integral conversion if the integral conversion
3523 // is between types of the same size.
3524 // For example:
3525 // void f(float);
3526 // void f(int);
3527 // int main {
3528 // long a;
3529 // f(a);
3530 // }
3531 // Here, MSVC will call f(int) instead of generating a compile error
3532 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003533 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003534 SCS1.Second == ICK_Integral_Conversion &&
3535 SCS2.Second == ICK_Floating_Integral &&
3536 S.Context.getTypeSize(SCS1.getFromType()) ==
3537 S.Context.getTypeSize(SCS1.getToType(2)))
3538 return ImplicitConversionSequence::Better;
3539
Douglas Gregor57373262008-10-22 14:17:15 +00003540 return ImplicitConversionSequence::Indistinguishable;
3541}
3542
3543/// CompareQualificationConversions - Compares two standard conversion
3544/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003545/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3546ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003547CompareQualificationConversions(Sema &S,
3548 const StandardConversionSequence& SCS1,
3549 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003550 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003551 // -- S1 and S2 differ only in their qualification conversion and
3552 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3553 // cv-qualification signature of type T1 is a proper subset of
3554 // the cv-qualification signature of type T2, and S1 is not the
3555 // deprecated string literal array-to-pointer conversion (4.2).
3556 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3557 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3558 return ImplicitConversionSequence::Indistinguishable;
3559
3560 // FIXME: the example in the standard doesn't use a qualification
3561 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003562 QualType T1 = SCS1.getToType(2);
3563 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003564 T1 = S.Context.getCanonicalType(T1);
3565 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003566 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003567 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3568 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003569
3570 // If the types are the same, we won't learn anything by unwrapped
3571 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003572 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003573 return ImplicitConversionSequence::Indistinguishable;
3574
Chandler Carruth28e318c2009-12-29 07:16:59 +00003575 // If the type is an array type, promote the element qualifiers to the type
3576 // for comparison.
3577 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003578 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003579 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003580 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003581
Mike Stump1eb44332009-09-09 15:08:12 +00003582 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003583 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003584
3585 // Objective-C++ ARC:
3586 // Prefer qualification conversions not involving a change in lifetime
3587 // to qualification conversions that do not change lifetime.
3588 if (SCS1.QualificationIncludesObjCLifetime !=
3589 SCS2.QualificationIncludesObjCLifetime) {
3590 Result = SCS1.QualificationIncludesObjCLifetime
3591 ? ImplicitConversionSequence::Worse
3592 : ImplicitConversionSequence::Better;
3593 }
3594
John McCall120d63c2010-08-24 20:38:10 +00003595 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003596 // Within each iteration of the loop, we check the qualifiers to
3597 // determine if this still looks like a qualification
3598 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003599 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003600 // until there are no more pointers or pointers-to-members left
3601 // to unwrap. This essentially mimics what
3602 // IsQualificationConversion does, but here we're checking for a
3603 // strict subset of qualifiers.
3604 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3605 // The qualifiers are the same, so this doesn't tell us anything
3606 // about how the sequences rank.
3607 ;
3608 else if (T2.isMoreQualifiedThan(T1)) {
3609 // T1 has fewer qualifiers, so it could be the better sequence.
3610 if (Result == ImplicitConversionSequence::Worse)
3611 // Neither has qualifiers that are a subset of the other's
3612 // qualifiers.
3613 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Douglas Gregor57373262008-10-22 14:17:15 +00003615 Result = ImplicitConversionSequence::Better;
3616 } else if (T1.isMoreQualifiedThan(T2)) {
3617 // T2 has fewer qualifiers, so it could be the better sequence.
3618 if (Result == ImplicitConversionSequence::Better)
3619 // Neither has qualifiers that are a subset of the other's
3620 // qualifiers.
3621 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor57373262008-10-22 14:17:15 +00003623 Result = ImplicitConversionSequence::Worse;
3624 } else {
3625 // Qualifiers are disjoint.
3626 return ImplicitConversionSequence::Indistinguishable;
3627 }
3628
3629 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003630 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003631 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003632 }
3633
Douglas Gregor57373262008-10-22 14:17:15 +00003634 // Check that the winning standard conversion sequence isn't using
3635 // the deprecated string literal array to pointer conversion.
3636 switch (Result) {
3637 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003638 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003639 Result = ImplicitConversionSequence::Indistinguishable;
3640 break;
3641
3642 case ImplicitConversionSequence::Indistinguishable:
3643 break;
3644
3645 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003646 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003647 Result = ImplicitConversionSequence::Indistinguishable;
3648 break;
3649 }
3650
3651 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003652}
3653
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003654/// CompareDerivedToBaseConversions - Compares two standard conversion
3655/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003656/// various kinds of derived-to-base conversions (C++
3657/// [over.ics.rank]p4b3). As part of these checks, we also look at
3658/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003659ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003660CompareDerivedToBaseConversions(Sema &S,
3661 const StandardConversionSequence& SCS1,
3662 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003663 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003664 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003665 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003666 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003667
3668 // Adjust the types we're converting from via the array-to-pointer
3669 // conversion, if we need to.
3670 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003671 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003672 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003673 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003674
3675 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003676 FromType1 = S.Context.getCanonicalType(FromType1);
3677 ToType1 = S.Context.getCanonicalType(ToType1);
3678 FromType2 = S.Context.getCanonicalType(FromType2);
3679 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003680
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003681 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003682 //
3683 // If class B is derived directly or indirectly from class A and
3684 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003685 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003686 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003687 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003688 SCS2.Second == ICK_Pointer_Conversion &&
3689 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3690 FromType1->isPointerType() && FromType2->isPointerType() &&
3691 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003692 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003693 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003694 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003695 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003696 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003697 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003698 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003699 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003700
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003701 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003702 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003703 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003704 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003705 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003706 return ImplicitConversionSequence::Worse;
3707 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003708
3709 // -- conversion of B* to A* is better than conversion of C* to A*,
3710 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003711 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003712 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003713 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003714 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003715 }
3716 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3717 SCS2.Second == ICK_Pointer_Conversion) {
3718 const ObjCObjectPointerType *FromPtr1
3719 = FromType1->getAs<ObjCObjectPointerType>();
3720 const ObjCObjectPointerType *FromPtr2
3721 = FromType2->getAs<ObjCObjectPointerType>();
3722 const ObjCObjectPointerType *ToPtr1
3723 = ToType1->getAs<ObjCObjectPointerType>();
3724 const ObjCObjectPointerType *ToPtr2
3725 = ToType2->getAs<ObjCObjectPointerType>();
3726
3727 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3728 // Apply the same conversion ranking rules for Objective-C pointer types
3729 // that we do for C++ pointers to class types. However, we employ the
3730 // Objective-C pseudo-subtyping relationship used for assignment of
3731 // Objective-C pointer types.
3732 bool FromAssignLeft
3733 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3734 bool FromAssignRight
3735 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3736 bool ToAssignLeft
3737 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3738 bool ToAssignRight
3739 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3740
3741 // A conversion to an a non-id object pointer type or qualified 'id'
3742 // type is better than a conversion to 'id'.
3743 if (ToPtr1->isObjCIdType() &&
3744 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3745 return ImplicitConversionSequence::Worse;
3746 if (ToPtr2->isObjCIdType() &&
3747 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3748 return ImplicitConversionSequence::Better;
3749
3750 // A conversion to a non-id object pointer type is better than a
3751 // conversion to a qualified 'id' type
3752 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3753 return ImplicitConversionSequence::Worse;
3754 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3755 return ImplicitConversionSequence::Better;
3756
3757 // A conversion to an a non-Class object pointer type or qualified 'Class'
3758 // type is better than a conversion to 'Class'.
3759 if (ToPtr1->isObjCClassType() &&
3760 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3761 return ImplicitConversionSequence::Worse;
3762 if (ToPtr2->isObjCClassType() &&
3763 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3764 return ImplicitConversionSequence::Better;
3765
3766 // A conversion to a non-Class object pointer type is better than a
3767 // conversion to a qualified 'Class' type.
3768 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3769 return ImplicitConversionSequence::Worse;
3770 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3771 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Douglas Gregor395cc372011-01-31 18:51:41 +00003773 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3774 if (S.Context.hasSameType(FromType1, FromType2) &&
3775 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3776 (ToAssignLeft != ToAssignRight))
3777 return ToAssignLeft? ImplicitConversionSequence::Worse
3778 : ImplicitConversionSequence::Better;
3779
3780 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3781 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3782 (FromAssignLeft != FromAssignRight))
3783 return FromAssignLeft? ImplicitConversionSequence::Better
3784 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003785 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003786 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003787
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003788 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003789 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3790 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3791 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003793 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003794 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003795 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003797 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003799 ToType2->getAs<MemberPointerType>();
3800 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3801 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3802 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3803 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3804 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3805 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3806 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3807 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003808 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003809 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003810 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003811 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003812 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003813 return ImplicitConversionSequence::Better;
3814 }
3815 // conversion of B::* to C::* is better than conversion of A::* to C::*
3816 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003817 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003818 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003819 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003820 return ImplicitConversionSequence::Worse;
3821 }
3822 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003824 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003825 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003826 // -- binding of an expression of type C to a reference of type
3827 // B& is better than binding an expression of type C to a
3828 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003829 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3830 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3831 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003832 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003833 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003834 return ImplicitConversionSequence::Worse;
3835 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003836
Douglas Gregor225c41e2008-11-03 19:09:14 +00003837 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003838 // -- binding of an expression of type B to a reference of type
3839 // A& is better than binding an expression of type C to a
3840 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003841 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3842 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3843 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003844 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003845 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003846 return ImplicitConversionSequence::Worse;
3847 }
3848 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003849
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003850 return ImplicitConversionSequence::Indistinguishable;
3851}
3852
Douglas Gregorabe183d2010-04-13 16:31:36 +00003853/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3854/// determine whether they are reference-related,
3855/// reference-compatible, reference-compatible with added
3856/// qualification, or incompatible, for use in C++ initialization by
3857/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3858/// type, and the first type (T1) is the pointee type of the reference
3859/// type being initialized.
3860Sema::ReferenceCompareResult
3861Sema::CompareReferenceRelationship(SourceLocation Loc,
3862 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003863 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003864 bool &ObjCConversion,
3865 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003866 assert(!OrigT1->isReferenceType() &&
3867 "T1 must be the pointee type of the reference type");
3868 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3869
3870 QualType T1 = Context.getCanonicalType(OrigT1);
3871 QualType T2 = Context.getCanonicalType(OrigT2);
3872 Qualifiers T1Quals, T2Quals;
3873 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3874 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3875
3876 // C++ [dcl.init.ref]p4:
3877 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3878 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3879 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003880 DerivedToBase = false;
3881 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003882 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003883 if (UnqualT1 == UnqualT2) {
3884 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003885 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003886 IsDerivedFrom(UnqualT2, UnqualT1))
3887 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003888 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3889 UnqualT2->isObjCObjectOrInterfaceType() &&
3890 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3891 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003892 else
3893 return Ref_Incompatible;
3894
3895 // At this point, we know that T1 and T2 are reference-related (at
3896 // least).
3897
3898 // If the type is an array type, promote the element qualifiers to the type
3899 // for comparison.
3900 if (isa<ArrayType>(T1) && T1Quals)
3901 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3902 if (isa<ArrayType>(T2) && T2Quals)
3903 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3904
3905 // C++ [dcl.init.ref]p4:
3906 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3907 // reference-related to T2 and cv1 is the same cv-qualification
3908 // as, or greater cv-qualification than, cv2. For purposes of
3909 // overload resolution, cases for which cv1 is greater
3910 // cv-qualification than cv2 are identified as
3911 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003912 //
3913 // Note that we also require equivalence of Objective-C GC and address-space
3914 // qualifiers when performing these computations, so that e.g., an int in
3915 // address space 1 is not reference-compatible with an int in address
3916 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003917 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3918 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3919 T1Quals.removeObjCLifetime();
3920 T2Quals.removeObjCLifetime();
3921 ObjCLifetimeConversion = true;
3922 }
3923
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003924 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003925 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003926 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003927 return Ref_Compatible_With_Added_Qualification;
3928 else
3929 return Ref_Related;
3930}
3931
Douglas Gregor604eb652010-08-11 02:15:33 +00003932/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003933/// with DeclType. Return true if something definite is found.
3934static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003935FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3936 QualType DeclType, SourceLocation DeclLoc,
3937 Expr *Init, QualType T2, bool AllowRvalues,
3938 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003939 assert(T2->isRecordType() && "Can only find conversions of record types.");
3940 CXXRecordDecl *T2RecordDecl
3941 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3942
3943 OverloadCandidateSet CandidateSet(DeclLoc);
3944 const UnresolvedSetImpl *Conversions
3945 = T2RecordDecl->getVisibleConversionFunctions();
3946 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3947 E = Conversions->end(); I != E; ++I) {
3948 NamedDecl *D = *I;
3949 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3950 if (isa<UsingShadowDecl>(D))
3951 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3952
3953 FunctionTemplateDecl *ConvTemplate
3954 = dyn_cast<FunctionTemplateDecl>(D);
3955 CXXConversionDecl *Conv;
3956 if (ConvTemplate)
3957 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3958 else
3959 Conv = cast<CXXConversionDecl>(D);
3960
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003962 // explicit conversions, skip it.
3963 if (!AllowExplicit && Conv->isExplicit())
3964 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965
Douglas Gregor604eb652010-08-11 02:15:33 +00003966 if (AllowRvalues) {
3967 bool DerivedToBase = false;
3968 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003969 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003970
3971 // If we are initializing an rvalue reference, don't permit conversion
3972 // functions that return lvalues.
3973 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3974 const ReferenceType *RefType
3975 = Conv->getConversionType()->getAs<LValueReferenceType>();
3976 if (RefType && !RefType->getPointeeType()->isFunctionType())
3977 continue;
3978 }
3979
Douglas Gregor604eb652010-08-11 02:15:33 +00003980 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003981 S.CompareReferenceRelationship(
3982 DeclLoc,
3983 Conv->getConversionType().getNonReferenceType()
3984 .getUnqualifiedType(),
3985 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003986 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003987 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003988 continue;
3989 } else {
3990 // If the conversion function doesn't return a reference type,
3991 // it can't be considered for this conversion. An rvalue reference
3992 // is only acceptable if its referencee is a function type.
3993
3994 const ReferenceType *RefType =
3995 Conv->getConversionType()->getAs<ReferenceType>();
3996 if (!RefType ||
3997 (!RefType->isLValueReferenceType() &&
3998 !RefType->getPointeeType()->isFunctionType()))
3999 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004000 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
Douglas Gregor604eb652010-08-11 02:15:33 +00004002 if (ConvTemplate)
4003 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004004 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004005 else
4006 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004007 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004008 }
4009
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004010 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4011
Sebastian Redl4680bf22010-06-30 18:13:39 +00004012 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004013 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004014 case OR_Success:
4015 // C++ [over.ics.ref]p1:
4016 //
4017 // [...] If the parameter binds directly to the result of
4018 // applying a conversion function to the argument
4019 // expression, the implicit conversion sequence is a
4020 // user-defined conversion sequence (13.3.3.1.2), with the
4021 // second standard conversion sequence either an identity
4022 // conversion or, if the conversion function returns an
4023 // entity of a type that is a derived class of the parameter
4024 // type, a derived-to-base Conversion.
4025 if (!Best->FinalConversion.DirectBinding)
4026 return false;
4027
Chandler Carruth25ca4212011-02-25 19:41:05 +00004028 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004029 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004030 ICS.setUserDefined();
4031 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4032 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004033 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004034 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004035 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004036 ICS.UserDefined.EllipsisConversion = false;
4037 assert(ICS.UserDefined.After.ReferenceBinding &&
4038 ICS.UserDefined.After.DirectBinding &&
4039 "Expected a direct reference binding!");
4040 return true;
4041
4042 case OR_Ambiguous:
4043 ICS.setAmbiguous();
4044 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4045 Cand != CandidateSet.end(); ++Cand)
4046 if (Cand->Viable)
4047 ICS.Ambiguous.addConversion(Cand->Function);
4048 return true;
4049
4050 case OR_No_Viable_Function:
4051 case OR_Deleted:
4052 // There was no suitable conversion, or we found a deleted
4053 // conversion; continue with other checks.
4054 return false;
4055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004056
David Blaikie7530c032012-01-17 06:56:22 +00004057 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004058}
4059
Douglas Gregorabe183d2010-04-13 16:31:36 +00004060/// \brief Compute an implicit conversion sequence for reference
4061/// initialization.
4062static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004063TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004064 SourceLocation DeclLoc,
4065 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004066 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004067 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4068
4069 // Most paths end in a failed conversion.
4070 ImplicitConversionSequence ICS;
4071 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4072
4073 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4074 QualType T2 = Init->getType();
4075
4076 // If the initializer is the address of an overloaded function, try
4077 // to resolve the overloaded function. If all goes well, T2 is the
4078 // type of the resulting function.
4079 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4080 DeclAccessPair Found;
4081 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4082 false, Found))
4083 T2 = Fn->getType();
4084 }
4085
4086 // Compute some basic properties of the types and the initializer.
4087 bool isRValRef = DeclType->isRValueReferenceType();
4088 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004089 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004090 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004091 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004092 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004093 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004094 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004095
Douglas Gregorabe183d2010-04-13 16:31:36 +00004096
Sebastian Redl4680bf22010-06-30 18:13:39 +00004097 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004098 // A reference to type "cv1 T1" is initialized by an expression
4099 // of type "cv2 T2" as follows:
4100
Sebastian Redl4680bf22010-06-30 18:13:39 +00004101 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004102 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004103 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4104 // reference-compatible with "cv2 T2," or
4105 //
4106 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4107 if (InitCategory.isLValue() &&
4108 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004109 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 // When a parameter of reference type binds directly (8.5.3)
4111 // to an argument expression, the implicit conversion sequence
4112 // is the identity conversion, unless the argument expression
4113 // has a type that is a derived class of the parameter type,
4114 // in which case the implicit conversion sequence is a
4115 // derived-to-base Conversion (13.3.3.1).
4116 ICS.setStandard();
4117 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004118 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4119 : ObjCConversion? ICK_Compatible_Conversion
4120 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004121 ICS.Standard.Third = ICK_Identity;
4122 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4123 ICS.Standard.setToType(0, T2);
4124 ICS.Standard.setToType(1, T1);
4125 ICS.Standard.setToType(2, T1);
4126 ICS.Standard.ReferenceBinding = true;
4127 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004128 ICS.Standard.IsLvalueReference = !isRValRef;
4129 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4130 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004131 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004132 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004133 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004134
Sebastian Redl4680bf22010-06-30 18:13:39 +00004135 // Nothing more to do: the inaccessibility/ambiguity check for
4136 // derived-to-base conversions is suppressed when we're
4137 // computing the implicit conversion sequence (C++
4138 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004139 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004140 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004141
Sebastian Redl4680bf22010-06-30 18:13:39 +00004142 // -- has a class type (i.e., T2 is a class type), where T1 is
4143 // not reference-related to T2, and can be implicitly
4144 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4145 // is reference-compatible with "cv3 T3" 92) (this
4146 // conversion is selected by enumerating the applicable
4147 // conversion functions (13.3.1.6) and choosing the best
4148 // one through overload resolution (13.3)),
4149 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004150 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004151 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004152 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4153 Init, T2, /*AllowRvalues=*/false,
4154 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004155 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004156 }
4157 }
4158
Sebastian Redl4680bf22010-06-30 18:13:39 +00004159 // -- Otherwise, the reference shall be an lvalue reference to a
4160 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004161 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004162 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004163 // We actually handle one oddity of C++ [over.ics.ref] at this
4164 // point, which is that, due to p2 (which short-circuits reference
4165 // binding by only attempting a simple conversion for non-direct
4166 // bindings) and p3's strange wording, we allow a const volatile
4167 // reference to bind to an rvalue. Hence the check for the presence
4168 // of "const" rather than checking for "const" being the only
4169 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004170 // This is also the point where rvalue references and lvalue inits no longer
4171 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004172 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004173 return ICS;
4174
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004175 // -- If the initializer expression
4176 //
4177 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004178 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004179 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4180 (InitCategory.isXValue() ||
4181 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4182 (InitCategory.isLValue() && T2->isFunctionType()))) {
4183 ICS.setStandard();
4184 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004186 : ObjCConversion? ICK_Compatible_Conversion
4187 : ICK_Identity;
4188 ICS.Standard.Third = ICK_Identity;
4189 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4190 ICS.Standard.setToType(0, T2);
4191 ICS.Standard.setToType(1, T1);
4192 ICS.Standard.setToType(2, T1);
4193 ICS.Standard.ReferenceBinding = true;
4194 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4195 // binding unless we're binding to a class prvalue.
4196 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4197 // allow the use of rvalue references in C++98/03 for the benefit of
4198 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004199 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004200 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004201 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004202 ICS.Standard.IsLvalueReference = !isRValRef;
4203 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004205 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004206 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004207 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004208 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004211 // -- has a class type (i.e., T2 is a class type), where T1 is not
4212 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004213 // an xvalue, class prvalue, or function lvalue of type
4214 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004215 // "cv3 T3",
4216 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004218 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004220 // class subobject).
4221 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004223 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4224 Init, T2, /*AllowRvalues=*/true,
4225 AllowExplicit)) {
4226 // In the second case, if the reference is an rvalue reference
4227 // and the second standard conversion sequence of the
4228 // user-defined conversion sequence includes an lvalue-to-rvalue
4229 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004230 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004231 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4232 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4233
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004234 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236
Douglas Gregorabe183d2010-04-13 16:31:36 +00004237 // -- Otherwise, a temporary of type "cv1 T1" is created and
4238 // initialized from the initializer expression using the
4239 // rules for a non-reference copy initialization (8.5). The
4240 // reference is then bound to the temporary. If T1 is
4241 // reference-related to T2, cv1 must be the same
4242 // cv-qualification as, or greater cv-qualification than,
4243 // cv2; otherwise, the program is ill-formed.
4244 if (RefRelationship == Sema::Ref_Related) {
4245 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4246 // we would be reference-compatible or reference-compatible with
4247 // added qualification. But that wasn't the case, so the reference
4248 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004249 //
4250 // Note that we only want to check address spaces and cvr-qualifiers here.
4251 // ObjC GC and lifetime qualifiers aren't important.
4252 Qualifiers T1Quals = T1.getQualifiers();
4253 Qualifiers T2Quals = T2.getQualifiers();
4254 T1Quals.removeObjCGCAttr();
4255 T1Quals.removeObjCLifetime();
4256 T2Quals.removeObjCGCAttr();
4257 T2Quals.removeObjCLifetime();
4258 if (!T1Quals.compatiblyIncludes(T2Quals))
4259 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004260 }
4261
4262 // If at least one of the types is a class type, the types are not
4263 // related, and we aren't allowed any user conversions, the
4264 // reference binding fails. This case is important for breaking
4265 // recursion, since TryImplicitConversion below will attempt to
4266 // create a temporary through the use of a copy constructor.
4267 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4268 (T1->isRecordType() || T2->isRecordType()))
4269 return ICS;
4270
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004271 // If T1 is reference-related to T2 and the reference is an rvalue
4272 // reference, the initializer expression shall not be an lvalue.
4273 if (RefRelationship >= Sema::Ref_Related &&
4274 isRValRef && Init->Classify(S.Context).isLValue())
4275 return ICS;
4276
Douglas Gregorabe183d2010-04-13 16:31:36 +00004277 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004278 // When a parameter of reference type is not bound directly to
4279 // an argument expression, the conversion sequence is the one
4280 // required to convert the argument expression to the
4281 // underlying type of the reference according to
4282 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4283 // to copy-initializing a temporary of the underlying type with
4284 // the argument expression. Any difference in top-level
4285 // cv-qualification is subsumed by the initialization itself
4286 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004287 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4288 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004289 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004290 /*CStyle=*/false,
4291 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004292
4293 // Of course, that's still a reference binding.
4294 if (ICS.isStandard()) {
4295 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004296 ICS.Standard.IsLvalueReference = !isRValRef;
4297 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4298 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004299 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004300 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004301 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004302 // Don't allow rvalue references to bind to lvalues.
4303 if (DeclType->isRValueReferenceType()) {
4304 if (const ReferenceType *RefType
4305 = ICS.UserDefined.ConversionFunction->getResultType()
4306 ->getAs<LValueReferenceType>()) {
4307 if (!RefType->getPointeeType()->isFunctionType()) {
4308 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4309 DeclType);
4310 return ICS;
4311 }
4312 }
4313 }
4314
Douglas Gregorabe183d2010-04-13 16:31:36 +00004315 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004316 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4317 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4318 ICS.UserDefined.After.BindsToRvalue = true;
4319 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4320 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004321 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004322
Douglas Gregorabe183d2010-04-13 16:31:36 +00004323 return ICS;
4324}
4325
Sebastian Redl5405b812011-10-16 18:19:34 +00004326static ImplicitConversionSequence
4327TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4328 bool SuppressUserConversions,
4329 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004330 bool AllowObjCWritebackConversion,
4331 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004332
4333/// TryListConversion - Try to copy-initialize a value of type ToType from the
4334/// initializer list From.
4335static ImplicitConversionSequence
4336TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4337 bool SuppressUserConversions,
4338 bool InOverloadResolution,
4339 bool AllowObjCWritebackConversion) {
4340 // C++11 [over.ics.list]p1:
4341 // When an argument is an initializer list, it is not an expression and
4342 // special rules apply for converting it to a parameter type.
4343
4344 ImplicitConversionSequence Result;
4345 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004346 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004347
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004348 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004349 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004350 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004351 return Result;
4352
Sebastian Redl5405b812011-10-16 18:19:34 +00004353 // C++11 [over.ics.list]p2:
4354 // If the parameter type is std::initializer_list<X> or "array of X" and
4355 // all the elements can be implicitly converted to X, the implicit
4356 // conversion sequence is the worst conversion necessary to convert an
4357 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004358 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004359 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004360 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004361 X = S.Context.getBaseElementType(ToType);
4362 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004363 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004364 if (!X.isNull()) {
4365 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4366 Expr *Init = From->getInit(i);
4367 ImplicitConversionSequence ICS =
4368 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4369 InOverloadResolution,
4370 AllowObjCWritebackConversion);
4371 // If a single element isn't convertible, fail.
4372 if (ICS.isBad()) {
4373 Result = ICS;
4374 break;
4375 }
4376 // Otherwise, look for the worst conversion.
4377 if (Result.isBad() ||
4378 CompareImplicitConversionSequences(S, ICS, Result) ==
4379 ImplicitConversionSequence::Worse)
4380 Result = ICS;
4381 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004382
4383 // For an empty list, we won't have computed any conversion sequence.
4384 // Introduce the identity conversion sequence.
4385 if (From->getNumInits() == 0) {
4386 Result.setStandard();
4387 Result.Standard.setAsIdentityConversion();
4388 Result.Standard.setFromType(ToType);
4389 Result.Standard.setAllToTypes(ToType);
4390 }
4391
Sebastian Redlfe592282012-01-17 22:49:48 +00004392 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004393 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004394 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004395 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004396
4397 // C++11 [over.ics.list]p3:
4398 // Otherwise, if the parameter is a non-aggregate class X and overload
4399 // resolution chooses a single best constructor [...] the implicit
4400 // conversion sequence is a user-defined conversion sequence. If multiple
4401 // constructors are viable but none is better than the others, the
4402 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004403 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4404 // This function can deal with initializer lists.
4405 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4406 /*AllowExplicit=*/false,
4407 InOverloadResolution, /*CStyle=*/false,
4408 AllowObjCWritebackConversion);
4409 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004410 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004411 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004412
4413 // C++11 [over.ics.list]p4:
4414 // Otherwise, if the parameter has an aggregate type which can be
4415 // initialized from the initializer list [...] the implicit conversion
4416 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004417 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004418 // Type is an aggregate, argument is an init list. At this point it comes
4419 // down to checking whether the initialization works.
4420 // FIXME: Find out whether this parameter is consumed or not.
4421 InitializedEntity Entity =
4422 InitializedEntity::InitializeParameter(S.Context, ToType,
4423 /*Consumed=*/false);
4424 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4425 Result.setUserDefined();
4426 Result.UserDefined.Before.setAsIdentityConversion();
4427 // Initializer lists don't have a type.
4428 Result.UserDefined.Before.setFromType(QualType());
4429 Result.UserDefined.Before.setAllToTypes(QualType());
4430
4431 Result.UserDefined.After.setAsIdentityConversion();
4432 Result.UserDefined.After.setFromType(ToType);
4433 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004434 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004435 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004436 return Result;
4437 }
4438
4439 // C++11 [over.ics.list]p5:
4440 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004441 if (ToType->isReferenceType()) {
4442 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4443 // mention initializer lists in any way. So we go by what list-
4444 // initialization would do and try to extrapolate from that.
4445
4446 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4447
4448 // If the initializer list has a single element that is reference-related
4449 // to the parameter type, we initialize the reference from that.
4450 if (From->getNumInits() == 1) {
4451 Expr *Init = From->getInit(0);
4452
4453 QualType T2 = Init->getType();
4454
4455 // If the initializer is the address of an overloaded function, try
4456 // to resolve the overloaded function. If all goes well, T2 is the
4457 // type of the resulting function.
4458 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4459 DeclAccessPair Found;
4460 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4461 Init, ToType, false, Found))
4462 T2 = Fn->getType();
4463 }
4464
4465 // Compute some basic properties of the types and the initializer.
4466 bool dummy1 = false;
4467 bool dummy2 = false;
4468 bool dummy3 = false;
4469 Sema::ReferenceCompareResult RefRelationship
4470 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4471 dummy2, dummy3);
4472
4473 if (RefRelationship >= Sema::Ref_Related)
4474 return TryReferenceInit(S, Init, ToType,
4475 /*FIXME:*/From->getLocStart(),
4476 SuppressUserConversions,
4477 /*AllowExplicit=*/false);
4478 }
4479
4480 // Otherwise, we bind the reference to a temporary created from the
4481 // initializer list.
4482 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4483 InOverloadResolution,
4484 AllowObjCWritebackConversion);
4485 if (Result.isFailure())
4486 return Result;
4487 assert(!Result.isEllipsis() &&
4488 "Sub-initialization cannot result in ellipsis conversion.");
4489
4490 // Can we even bind to a temporary?
4491 if (ToType->isRValueReferenceType() ||
4492 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4493 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4494 Result.UserDefined.After;
4495 SCS.ReferenceBinding = true;
4496 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4497 SCS.BindsToRvalue = true;
4498 SCS.BindsToFunctionLvalue = false;
4499 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4500 SCS.ObjCLifetimeConversionBinding = false;
4501 } else
4502 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4503 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004504 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004505 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004506
4507 // C++11 [over.ics.list]p6:
4508 // Otherwise, if the parameter type is not a class:
4509 if (!ToType->isRecordType()) {
4510 // - if the initializer list has one element, the implicit conversion
4511 // sequence is the one required to convert the element to the
4512 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004513 unsigned NumInits = From->getNumInits();
4514 if (NumInits == 1)
4515 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4516 SuppressUserConversions,
4517 InOverloadResolution,
4518 AllowObjCWritebackConversion);
4519 // - if the initializer list has no elements, the implicit conversion
4520 // sequence is the identity conversion.
4521 else if (NumInits == 0) {
4522 Result.setStandard();
4523 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004524 Result.Standard.setFromType(ToType);
4525 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004526 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004527 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004528 return Result;
4529 }
4530
4531 // C++11 [over.ics.list]p7:
4532 // In all cases other than those enumerated above, no conversion is possible
4533 return Result;
4534}
4535
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004536/// TryCopyInitialization - Try to copy-initialize a value of type
4537/// ToType from the expression From. Return the implicit conversion
4538/// sequence required to pass this argument, which may be a bad
4539/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004540/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004541/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004542static ImplicitConversionSequence
4543TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004544 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004545 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004546 bool AllowObjCWritebackConversion,
4547 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004548 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4549 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4550 InOverloadResolution,AllowObjCWritebackConversion);
4551
Douglas Gregorabe183d2010-04-13 16:31:36 +00004552 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004553 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004554 /*FIXME:*/From->getLocStart(),
4555 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004556 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004557
John McCall120d63c2010-08-24 20:38:10 +00004558 return TryImplicitConversion(S, From, ToType,
4559 SuppressUserConversions,
4560 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004561 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004562 /*CStyle=*/false,
4563 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004564}
4565
Anna Zaksf3546ee2011-07-28 19:46:48 +00004566static bool TryCopyInitialization(const CanQualType FromQTy,
4567 const CanQualType ToQTy,
4568 Sema &S,
4569 SourceLocation Loc,
4570 ExprValueKind FromVK) {
4571 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4572 ImplicitConversionSequence ICS =
4573 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4574
4575 return !ICS.isBad();
4576}
4577
Douglas Gregor96176b32008-11-18 23:14:02 +00004578/// TryObjectArgumentInitialization - Try to initialize the object
4579/// parameter of the given member function (@c Method) from the
4580/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004581static ImplicitConversionSequence
4582TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004583 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004584 CXXMethodDecl *Method,
4585 CXXRecordDecl *ActingContext) {
4586 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004587 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4588 // const volatile object.
4589 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4590 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004591 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004592
4593 // Set up the conversion sequence as a "bad" conversion, to allow us
4594 // to exit early.
4595 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004596
4597 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004598 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004599 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004600 FromType = PT->getPointeeType();
4601
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004602 // When we had a pointer, it's implicitly dereferenced, so we
4603 // better have an lvalue.
4604 assert(FromClassification.isLValue());
4605 }
4606
Anders Carlssona552f7c2009-05-01 18:34:30 +00004607 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004608
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004609 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004610 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004611 // parameter is
4612 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004613 // - "lvalue reference to cv X" for functions declared without a
4614 // ref-qualifier or with the & ref-qualifier
4615 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004616 // ref-qualifier
4617 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004619 // cv-qualification on the member function declaration.
4620 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004621 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004622 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004623 // (C++ [over.match.funcs]p5). We perform a simplified version of
4624 // reference binding here, that allows class rvalues to bind to
4625 // non-constant references.
4626
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004627 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004628 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004629 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004630 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004631 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004632 ICS.setBad(BadConversionSequence::bad_qualifiers,
4633 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004634 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004635 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004636
4637 // Check that we have either the same type or a derived type. It
4638 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004639 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004640 ImplicitConversionKind SecondKind;
4641 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4642 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004643 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004644 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004645 else {
John McCallb1bdc622010-02-25 01:37:24 +00004646 ICS.setBad(BadConversionSequence::unrelated_class,
4647 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004648 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004649 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004650
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004651 // Check the ref-qualifier.
4652 switch (Method->getRefQualifier()) {
4653 case RQ_None:
4654 // Do nothing; we don't care about lvalueness or rvalueness.
4655 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004656
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004657 case RQ_LValue:
4658 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4659 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004660 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004661 ImplicitParamType);
4662 return ICS;
4663 }
4664 break;
4665
4666 case RQ_RValue:
4667 if (!FromClassification.isRValue()) {
4668 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004669 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004670 ImplicitParamType);
4671 return ICS;
4672 }
4673 break;
4674 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004675
Douglas Gregor96176b32008-11-18 23:14:02 +00004676 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004677 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004678 ICS.Standard.setAsIdentityConversion();
4679 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004680 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004681 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004682 ICS.Standard.ReferenceBinding = true;
4683 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004685 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004686 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4687 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4688 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004689 return ICS;
4690}
4691
4692/// PerformObjectArgumentInitialization - Perform initialization of
4693/// the implicit object parameter for the given Method with the given
4694/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004695ExprResult
4696Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004697 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004698 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004699 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004700 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004701 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004702 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004705 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004706 FromRecordType = PT->getPointeeType();
4707 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004708 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004709 } else {
4710 FromRecordType = From->getType();
4711 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004712 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004713 }
4714
John McCall701c89e2009-12-03 04:06:58 +00004715 // Note that we always use the true parent context when performing
4716 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004717 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004718 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4719 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004720 if (ICS.isBad()) {
4721 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4722 Qualifiers FromQs = FromRecordType.getQualifiers();
4723 Qualifiers ToQs = DestType.getQualifiers();
4724 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4725 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004726 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004727 diag::err_member_function_call_bad_cvr)
4728 << Method->getDeclName() << FromRecordType << (CVR - 1)
4729 << From->getSourceRange();
4730 Diag(Method->getLocation(), diag::note_previous_decl)
4731 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004732 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004733 }
4734 }
4735
Daniel Dunbar96a00142012-03-09 18:35:03 +00004736 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004737 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004738 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004739 }
Mike Stump1eb44332009-09-09 15:08:12 +00004740
John Wiegley429bb272011-04-08 18:41:53 +00004741 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4742 ExprResult FromRes =
4743 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4744 if (FromRes.isInvalid())
4745 return ExprError();
4746 From = FromRes.take();
4747 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004748
Douglas Gregor5fccd362010-03-03 23:55:11 +00004749 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004750 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004751 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004752 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004753}
4754
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004755/// TryContextuallyConvertToBool - Attempt to contextually convert the
4756/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004757static ImplicitConversionSequence
4758TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004759 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004760 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004761 // FIXME: Are these flags correct?
4762 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004763 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004764 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004765 /*CStyle=*/false,
4766 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004767}
4768
4769/// PerformContextuallyConvertToBool - Perform a contextual conversion
4770/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004771ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004772 if (checkPlaceholderForOverload(*this, From))
4773 return ExprError();
4774
John McCall120d63c2010-08-24 20:38:10 +00004775 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004776 if (!ICS.isBad())
4777 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004778
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004779 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004780 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004781 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004782 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004783 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004784}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004785
Richard Smith8ef7b202012-01-18 23:55:52 +00004786/// Check that the specified conversion is permitted in a converted constant
4787/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4788/// is acceptable.
4789static bool CheckConvertedConstantConversions(Sema &S,
4790 StandardConversionSequence &SCS) {
4791 // Since we know that the target type is an integral or unscoped enumeration
4792 // type, most conversion kinds are impossible. All possible First and Third
4793 // conversions are fine.
4794 switch (SCS.Second) {
4795 case ICK_Identity:
4796 case ICK_Integral_Promotion:
4797 case ICK_Integral_Conversion:
4798 return true;
4799
4800 case ICK_Boolean_Conversion:
4801 // Conversion from an integral or unscoped enumeration type to bool is
4802 // classified as ICK_Boolean_Conversion, but it's also an integral
4803 // conversion, so it's permitted in a converted constant expression.
4804 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4805 SCS.getToType(2)->isBooleanType();
4806
4807 case ICK_Floating_Integral:
4808 case ICK_Complex_Real:
4809 return false;
4810
4811 case ICK_Lvalue_To_Rvalue:
4812 case ICK_Array_To_Pointer:
4813 case ICK_Function_To_Pointer:
4814 case ICK_NoReturn_Adjustment:
4815 case ICK_Qualification:
4816 case ICK_Compatible_Conversion:
4817 case ICK_Vector_Conversion:
4818 case ICK_Vector_Splat:
4819 case ICK_Derived_To_Base:
4820 case ICK_Pointer_Conversion:
4821 case ICK_Pointer_Member:
4822 case ICK_Block_Pointer_Conversion:
4823 case ICK_Writeback_Conversion:
4824 case ICK_Floating_Promotion:
4825 case ICK_Complex_Promotion:
4826 case ICK_Complex_Conversion:
4827 case ICK_Floating_Conversion:
4828 case ICK_TransparentUnionConversion:
4829 llvm_unreachable("unexpected second conversion kind");
4830
4831 case ICK_Num_Conversion_Kinds:
4832 break;
4833 }
4834
4835 llvm_unreachable("unknown conversion kind");
4836}
4837
4838/// CheckConvertedConstantExpression - Check that the expression From is a
4839/// converted constant expression of type T, perform the conversion and produce
4840/// the converted expression, per C++11 [expr.const]p3.
4841ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4842 llvm::APSInt &Value,
4843 CCEKind CCE) {
4844 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4845 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4846
4847 if (checkPlaceholderForOverload(*this, From))
4848 return ExprError();
4849
4850 // C++11 [expr.const]p3 with proposed wording fixes:
4851 // A converted constant expression of type T is a core constant expression,
4852 // implicitly converted to a prvalue of type T, where the converted
4853 // expression is a literal constant expression and the implicit conversion
4854 // sequence contains only user-defined conversions, lvalue-to-rvalue
4855 // conversions, integral promotions, and integral conversions other than
4856 // narrowing conversions.
4857 ImplicitConversionSequence ICS =
4858 TryImplicitConversion(From, T,
4859 /*SuppressUserConversions=*/false,
4860 /*AllowExplicit=*/false,
4861 /*InOverloadResolution=*/false,
4862 /*CStyle=*/false,
4863 /*AllowObjcWritebackConversion=*/false);
4864 StandardConversionSequence *SCS = 0;
4865 switch (ICS.getKind()) {
4866 case ImplicitConversionSequence::StandardConversion:
4867 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004868 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004869 diag::err_typecheck_converted_constant_expression_disallowed)
4870 << From->getType() << From->getSourceRange() << T;
4871 SCS = &ICS.Standard;
4872 break;
4873 case ImplicitConversionSequence::UserDefinedConversion:
4874 // We are converting from class type to an integral or enumeration type, so
4875 // the Before sequence must be trivial.
4876 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004877 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004878 diag::err_typecheck_converted_constant_expression_disallowed)
4879 << From->getType() << From->getSourceRange() << T;
4880 SCS = &ICS.UserDefined.After;
4881 break;
4882 case ImplicitConversionSequence::AmbiguousConversion:
4883 case ImplicitConversionSequence::BadConversion:
4884 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004885 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004886 diag::err_typecheck_converted_constant_expression)
4887 << From->getType() << From->getSourceRange() << T;
4888 return ExprError();
4889
4890 case ImplicitConversionSequence::EllipsisConversion:
4891 llvm_unreachable("ellipsis conversion in converted constant expression");
4892 }
4893
4894 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4895 if (Result.isInvalid())
4896 return Result;
4897
4898 // Check for a narrowing implicit conversion.
4899 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004900 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004901 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4902 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004903 case NK_Variable_Narrowing:
4904 // Implicit conversion to a narrower type, and the value is not a constant
4905 // expression. We'll diagnose this in a moment.
4906 case NK_Not_Narrowing:
4907 break;
4908
4909 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004910 Diag(From->getLocStart(),
4911 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4912 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004913 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004914 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004915 break;
4916
4917 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004918 Diag(From->getLocStart(),
4919 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4920 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004921 << CCE << /*Constant*/0 << From->getType() << T;
4922 break;
4923 }
4924
4925 // Check the expression is a constant expression.
4926 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4927 Expr::EvalResult Eval;
4928 Eval.Diag = &Notes;
4929
4930 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4931 // The expression can't be folded, so we can't keep it at this position in
4932 // the AST.
4933 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004934 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004935 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004936
4937 if (Notes.empty()) {
4938 // It's a constant expression.
4939 return Result;
4940 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004941 }
4942
4943 // It's not a constant expression. Produce an appropriate diagnostic.
4944 if (Notes.size() == 1 &&
4945 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4946 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4947 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004948 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004949 << CCE << From->getSourceRange();
4950 for (unsigned I = 0; I < Notes.size(); ++I)
4951 Diag(Notes[I].first, Notes[I].second);
4952 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004953 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004954}
4955
John McCall0bcc9bc2011-09-09 06:11:02 +00004956/// dropPointerConversions - If the given standard conversion sequence
4957/// involves any pointer conversions, remove them. This may change
4958/// the result type of the conversion sequence.
4959static void dropPointerConversion(StandardConversionSequence &SCS) {
4960 if (SCS.Second == ICK_Pointer_Conversion) {
4961 SCS.Second = ICK_Identity;
4962 SCS.Third = ICK_Identity;
4963 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4964 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004965}
John McCall120d63c2010-08-24 20:38:10 +00004966
John McCall0bcc9bc2011-09-09 06:11:02 +00004967/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4968/// convert the expression From to an Objective-C pointer type.
4969static ImplicitConversionSequence
4970TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4971 // Do an implicit conversion to 'id'.
4972 QualType Ty = S.Context.getObjCIdType();
4973 ImplicitConversionSequence ICS
4974 = TryImplicitConversion(S, From, Ty,
4975 // FIXME: Are these flags correct?
4976 /*SuppressUserConversions=*/false,
4977 /*AllowExplicit=*/true,
4978 /*InOverloadResolution=*/false,
4979 /*CStyle=*/false,
4980 /*AllowObjCWritebackConversion=*/false);
4981
4982 // Strip off any final conversions to 'id'.
4983 switch (ICS.getKind()) {
4984 case ImplicitConversionSequence::BadConversion:
4985 case ImplicitConversionSequence::AmbiguousConversion:
4986 case ImplicitConversionSequence::EllipsisConversion:
4987 break;
4988
4989 case ImplicitConversionSequence::UserDefinedConversion:
4990 dropPointerConversion(ICS.UserDefined.After);
4991 break;
4992
4993 case ImplicitConversionSequence::StandardConversion:
4994 dropPointerConversion(ICS.Standard);
4995 break;
4996 }
4997
4998 return ICS;
4999}
5000
5001/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5002/// conversion of the expression From to an Objective-C pointer type.
5003ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005004 if (checkPlaceholderForOverload(*this, From))
5005 return ExprError();
5006
John McCallc12c5bb2010-05-15 11:32:37 +00005007 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005008 ImplicitConversionSequence ICS =
5009 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005010 if (!ICS.isBad())
5011 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005012 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005013}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005014
Richard Smithf39aec12012-02-04 07:07:42 +00005015/// Determine whether the provided type is an integral type, or an enumeration
5016/// type of a permitted flavor.
5017static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5018 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5019 : T->isIntegralOrUnscopedEnumerationType();
5020}
5021
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005022/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005023/// enumeration type.
5024///
5025/// This routine will attempt to convert an expression of class type to an
5026/// integral or enumeration type, if that class type only has a single
5027/// conversion to an integral or enumeration type.
5028///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005029/// \param Loc The source location of the construct that requires the
5030/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005031///
James Dennett40ae6662012-06-22 08:52:37 +00005032/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005033///
James Dennett40ae6662012-06-22 08:52:37 +00005034/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005035///
Richard Smithf39aec12012-02-04 07:07:42 +00005036/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5037/// enumerations should be considered.
5038///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005039/// \returns The expression, converted to an integral or enumeration type if
5040/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005041ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005042Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005043 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005044 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005045 // We can't perform any more checking for type-dependent expressions.
5046 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005047 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048
Eli Friedmanceccab92012-01-26 00:26:18 +00005049 // Process placeholders immediately.
5050 if (From->hasPlaceholderType()) {
5051 ExprResult result = CheckPlaceholderExpr(From);
5052 if (result.isInvalid()) return result;
5053 From = result.take();
5054 }
5055
Douglas Gregorc30614b2010-06-29 23:17:37 +00005056 // If the expression already has integral or enumeration type, we're golden.
5057 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005058 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005059 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005060
5061 // FIXME: Check for missing '()' if T is a function type?
5062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00005064 // expression of integral or enumeration type.
5065 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005066 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005067 if (!Diagnoser.Suppress)
5068 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005069 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005071
Douglas Gregorc30614b2010-06-29 23:17:37 +00005072 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005073 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005074 ICEConvertDiagnoser &Diagnoser;
5075 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005076
Douglas Gregorab41fe92012-05-04 22:38:52 +00005077 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5078 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005079
5080 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005081 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005082 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005083 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005084
5085 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005086 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087
Douglas Gregorc30614b2010-06-29 23:17:37 +00005088 // Look for a conversion to an integral or enumeration type.
5089 UnresolvedSet<4> ViableConversions;
5090 UnresolvedSet<4> ExplicitConversions;
5091 const UnresolvedSetImpl *Conversions
5092 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005093
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005094 bool HadMultipleCandidates = (Conversions->size() > 1);
5095
Douglas Gregorc30614b2010-06-29 23:17:37 +00005096 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005097 E = Conversions->end();
5098 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005099 ++I) {
5100 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005101 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5102 if (isIntegralOrEnumerationType(
5103 Conversion->getConversionType().getNonReferenceType(),
5104 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005105 if (Conversion->isExplicit())
5106 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5107 else
5108 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5109 }
Richard Smithf39aec12012-02-04 07:07:42 +00005110 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005112
Douglas Gregorc30614b2010-06-29 23:17:37 +00005113 switch (ViableConversions.size()) {
5114 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005115 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005116 DeclAccessPair Found = ExplicitConversions[0];
5117 CXXConversionDecl *Conversion
5118 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120 // The user probably meant to invoke the given explicit
5121 // conversion; use it.
5122 QualType ConvTy
5123 = Conversion->getConversionType().getNonReferenceType();
5124 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005125 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126
Douglas Gregorab41fe92012-05-04 22:38:52 +00005127 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005128 << FixItHint::CreateInsertion(From->getLocStart(),
5129 "static_cast<" + TypeStr + ">(")
5130 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5131 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005132 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005133
5134 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135 // explicit conversion function.
5136 if (isSFINAEContext())
5137 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138
Douglas Gregorc30614b2010-06-29 23:17:37 +00005139 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005140 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5141 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005142 if (Result.isInvalid())
5143 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005144 // Record usage of conversion in an implicit cast.
5145 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5146 CK_UserDefinedConversion,
5147 Result.get(), 0,
5148 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005149 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005150
Douglas Gregorc30614b2010-06-29 23:17:37 +00005151 // We'll complain below about a non-integral condition type.
5152 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153
Douglas Gregorc30614b2010-06-29 23:17:37 +00005154 case 1: {
5155 // Apply this conversion.
5156 DeclAccessPair Found = ViableConversions[0];
5157 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005158
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005159 CXXConversionDecl *Conversion
5160 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5161 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005162 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005163 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005164 if (isSFINAEContext())
5165 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005166
Douglas Gregorab41fe92012-05-04 22:38:52 +00005167 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5168 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005170
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005171 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5172 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005173 if (Result.isInvalid())
5174 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005175 // Record usage of conversion in an implicit cast.
5176 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5177 CK_UserDefinedConversion,
5178 Result.get(), 0,
5179 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005180 break;
5181 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005182
Douglas Gregorc30614b2010-06-29 23:17:37 +00005183 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005184 if (Diagnoser.Suppress)
5185 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005186
Douglas Gregorab41fe92012-05-04 22:38:52 +00005187 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005188 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5189 CXXConversionDecl *Conv
5190 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5191 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005192 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005193 }
John McCall9ae2f072010-08-23 23:25:46 +00005194 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005195 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196
Richard Smith282e7e62012-02-04 09:53:13 +00005197 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005198 !Diagnoser.Suppress) {
5199 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5200 << From->getSourceRange();
5201 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202
Eli Friedmanceccab92012-01-26 00:26:18 +00005203 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005204}
5205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005206/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005207/// candidate functions, using the given function call arguments. If
5208/// @p SuppressUserConversions, then don't allow user-defined
5209/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005210///
James Dennett699c9042012-06-15 07:13:21 +00005211/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005212/// based on an incomplete set of function arguments. This feature is used by
5213/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005214void
5215Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005216 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005217 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005218 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005219 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005220 bool PartialOverloading,
5221 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005222 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005223 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005224 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005225 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005226 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005227
Douglas Gregor88a35142008-12-22 05:46:06 +00005228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005229 if (!isa<CXXConstructorDecl>(Method)) {
5230 // If we get here, it's because we're calling a member function
5231 // that is named without a member access expression (e.g.,
5232 // "this->f") that was either written explicitly or created
5233 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005234 // function, e.g., X::f(). We use an empty type for the implied
5235 // object argument (C++ [over.call.func]p3), and the acting context
5236 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005237 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005238 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005239 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005240 return;
5241 }
5242 // We treat a constructor like a non-member function, since its object
5243 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005244 }
5245
Douglas Gregorfd476482009-11-13 23:59:09 +00005246 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005247 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005248
Douglas Gregor7edfb692009-11-23 12:27:39 +00005249 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005250 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005251
Douglas Gregor66724ea2009-11-14 01:20:54 +00005252 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5253 // C++ [class.copy]p3:
5254 // A member function template is never instantiated to perform the copy
5255 // of a class object to an object of its class type.
5256 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005257 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005258 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005259 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5260 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005261 return;
5262 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005264 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005265 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005266 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005267 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005268 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005269 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005270 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005271 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005272
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005273 unsigned NumArgsInProto = Proto->getNumArgs();
5274
5275 // (C++ 13.3.2p2): A candidate function having fewer than m
5276 // parameters is viable only if it has an ellipsis in its parameter
5277 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005278 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005279 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005280 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005281 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005282 return;
5283 }
5284
5285 // (C++ 13.3.2p2): A candidate function having more than m parameters
5286 // is viable only if the (m+1)st parameter has a default argument
5287 // (8.3.6). For the purposes of overload resolution, the
5288 // parameter list is truncated on the right, so that there are
5289 // exactly m parameters.
5290 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005291 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005292 // Not enough arguments.
5293 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005294 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005295 return;
5296 }
5297
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005298 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005299 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005300 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5301 if (CheckCUDATarget(Caller, Function)) {
5302 Candidate.Viable = false;
5303 Candidate.FailureKind = ovl_fail_bad_target;
5304 return;
5305 }
5306
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005307 // Determine the implicit conversion sequences for each of the
5308 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005309 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005310 if (ArgIdx < NumArgsInProto) {
5311 // (C++ 13.3.2p3): for F to be a viable function, there shall
5312 // exist for each argument an implicit conversion sequence
5313 // (13.3.3.1) that converts that argument to the corresponding
5314 // parameter of F.
5315 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005316 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005317 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005319 /*InOverloadResolution=*/true,
5320 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005321 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005322 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005323 if (Candidate.Conversions[ArgIdx].isBad()) {
5324 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005325 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005326 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005327 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005328 } else {
5329 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5330 // argument for which there is no corresponding parameter is
5331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005332 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005333 }
5334 }
5335}
5336
Douglas Gregor063daf62009-03-13 18:40:31 +00005337/// \brief Add all of the function declarations in the given function set to
5338/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005339void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005340 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005341 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005342 bool SuppressUserConversions,
5343 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005344 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005345 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005347 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005348 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005349 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005350 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005351 Args.slice(1), CandidateSet,
5352 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005353 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005354 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005355 SuppressUserConversions);
5356 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005357 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005358 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5359 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005360 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005361 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005362 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005363 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005364 Args[0]->Classify(Context), Args.slice(1),
5365 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005366 else
John McCall9aa472c2010-03-19 07:35:19 +00005367 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005368 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005369 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005370 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005371 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005372}
5373
John McCall314be4e2009-11-17 07:50:12 +00005374/// AddMethodCandidate - Adds a named decl (which is some kind of
5375/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005376void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005377 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005378 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005379 Expr **Args, unsigned NumArgs,
5380 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005381 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005382 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005383 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005384
5385 if (isa<UsingShadowDecl>(Decl))
5386 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005387
John McCall314be4e2009-11-17 07:50:12 +00005388 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5389 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5390 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005391 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5392 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005393 ObjectType, ObjectClassification,
5394 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005395 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005396 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005397 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005398 ObjectType, ObjectClassification,
5399 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005400 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005401 }
5402}
5403
Douglas Gregor96176b32008-11-18 23:14:02 +00005404/// AddMethodCandidate - Adds the given C++ member function to the set
5405/// of candidate functions, using the given function call arguments
5406/// and the object argument (@c Object). For example, in a call
5407/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5408/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5409/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005410/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005411void
John McCall9aa472c2010-03-19 07:35:19 +00005412Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005413 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005414 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005415 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005416 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005417 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005418 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005419 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005420 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005421 assert(!isa<CXXConstructorDecl>(Method) &&
5422 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005423
Douglas Gregor3f396022009-09-28 04:47:19 +00005424 if (!CandidateSet.isNewCandidate(Method))
5425 return;
5426
Douglas Gregor7edfb692009-11-23 12:27:39 +00005427 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005429
Douglas Gregor96176b32008-11-18 23:14:02 +00005430 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005431 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005432 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005433 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005434 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005435 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005436 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005437
5438 unsigned NumArgsInProto = Proto->getNumArgs();
5439
5440 // (C++ 13.3.2p2): A candidate function having fewer than m
5441 // parameters is viable only if it has an ellipsis in its parameter
5442 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005443 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005444 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005445 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005446 return;
5447 }
5448
5449 // (C++ 13.3.2p2): A candidate function having more than m parameters
5450 // is viable only if the (m+1)st parameter has a default argument
5451 // (8.3.6). For the purposes of overload resolution, the
5452 // parameter list is truncated on the right, so that there are
5453 // exactly m parameters.
5454 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005455 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005456 // Not enough arguments.
5457 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005458 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005459 return;
5460 }
5461
5462 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005463
John McCall701c89e2009-12-03 04:06:58 +00005464 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005465 // The implicit object argument is ignored.
5466 Candidate.IgnoreObjectArgument = true;
5467 else {
5468 // Determine the implicit conversion sequence for the object
5469 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005470 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005471 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5472 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005473 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005474 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005475 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005476 return;
5477 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005478 }
5479
5480 // Determine the implicit conversion sequences for each of the
5481 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005482 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005483 if (ArgIdx < NumArgsInProto) {
5484 // (C++ 13.3.2p3): for F to be a viable function, there shall
5485 // exist for each argument an implicit conversion sequence
5486 // (13.3.3.1) that converts that argument to the corresponding
5487 // parameter of F.
5488 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005489 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005490 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005491 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005492 /*InOverloadResolution=*/true,
5493 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005494 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005495 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005496 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005497 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005498 break;
5499 }
5500 } else {
5501 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5502 // argument for which there is no corresponding parameter is
5503 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005504 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005505 }
5506 }
5507}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005508
Douglas Gregor6b906862009-08-21 00:16:32 +00005509/// \brief Add a C++ member function template as a candidate to the candidate
5510/// set, using template argument deduction to produce an appropriate member
5511/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005512void
Douglas Gregor6b906862009-08-21 00:16:32 +00005513Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005514 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005515 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005516 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005517 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005518 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005519 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005520 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005521 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005522 if (!CandidateSet.isNewCandidate(MethodTmpl))
5523 return;
5524
Douglas Gregor6b906862009-08-21 00:16:32 +00005525 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005526 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005527 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005528 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005529 // candidate functions in the usual way.113) A given name can refer to one
5530 // or more function templates and also to a set of overloaded non-template
5531 // functions. In such a case, the candidate functions generated from each
5532 // function template are combined with the set of non-template candidate
5533 // functions.
John McCall5769d612010-02-08 23:07:23 +00005534 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005535 FunctionDecl *Specialization = 0;
5536 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005537 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5538 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005539 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005540 Candidate.FoundDecl = FoundDecl;
5541 Candidate.Function = MethodTmpl->getTemplatedDecl();
5542 Candidate.Viable = false;
5543 Candidate.FailureKind = ovl_fail_bad_deduction;
5544 Candidate.IsSurrogate = false;
5545 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005546 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005547 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005548 Info);
5549 return;
5550 }
Mike Stump1eb44332009-09-09 15:08:12 +00005551
Douglas Gregor6b906862009-08-21 00:16:32 +00005552 // Add the function template specialization produced by template argument
5553 // deduction as a candidate.
5554 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005555 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005556 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005557 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005558 ActingContext, ObjectType, ObjectClassification, Args,
5559 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005560}
5561
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005562/// \brief Add a C++ function template specialization as a candidate
5563/// in the candidate set, using template argument deduction to produce
5564/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005565void
Douglas Gregore53060f2009-06-25 22:08:12 +00005566Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005567 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005568 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005569 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005570 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005571 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005572 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5573 return;
5574
Douglas Gregore53060f2009-06-25 22:08:12 +00005575 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005576 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005577 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005578 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005579 // candidate functions in the usual way.113) A given name can refer to one
5580 // or more function templates and also to a set of overloaded non-template
5581 // functions. In such a case, the candidate functions generated from each
5582 // function template are combined with the set of non-template candidate
5583 // functions.
John McCall5769d612010-02-08 23:07:23 +00005584 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005585 FunctionDecl *Specialization = 0;
5586 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005587 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5588 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005589 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005590 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005591 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5592 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005593 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005594 Candidate.IsSurrogate = false;
5595 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005596 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005597 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005598 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005599 return;
5600 }
Mike Stump1eb44332009-09-09 15:08:12 +00005601
Douglas Gregore53060f2009-06-25 22:08:12 +00005602 // Add the function template specialization produced by template argument
5603 // deduction as a candidate.
5604 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005605 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005606 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005607}
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005609/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005610/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005611/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005612/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005613/// (which may or may not be the same type as the type that the
5614/// conversion function produces).
5615void
5616Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005617 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005618 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005619 Expr *From, QualType ToType,
5620 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005621 assert(!Conversion->getDescribedFunctionTemplate() &&
5622 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005623 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005624 if (!CandidateSet.isNewCandidate(Conversion))
5625 return;
5626
Douglas Gregor7edfb692009-11-23 12:27:39 +00005627 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005628 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005629
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005630 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005631 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005632 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005633 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005634 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005635 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005636 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005637 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005638 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005639 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005640 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005641
Douglas Gregorbca39322010-08-19 15:37:02 +00005642 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005643 // For conversion functions, the function is considered to be a member of
5644 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005645 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005646 //
5647 // Determine the implicit conversion sequence for the implicit
5648 // object parameter.
5649 QualType ImplicitParamType = From->getType();
5650 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5651 ImplicitParamType = FromPtrType->getPointeeType();
5652 CXXRecordDecl *ConversionContext
5653 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005654
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005655 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005656 = TryObjectArgumentInitialization(*this, From->getType(),
5657 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005658 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005659
John McCall1d318332010-01-12 00:44:57 +00005660 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005661 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005662 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005663 return;
5664 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005665
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005666 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005667 // derived to base as such conversions are given Conversion Rank. They only
5668 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5669 QualType FromCanon
5670 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5671 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5672 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5673 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005674 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005675 return;
5676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005677
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005678 // To determine what the conversion from the result of calling the
5679 // conversion function to the type we're eventually trying to
5680 // convert to (ToType), we need to synthesize a call to the
5681 // conversion function and attempt copy initialization from it. This
5682 // makes sure that we get the right semantics with respect to
5683 // lvalues/rvalues and the type. Fortunately, we can allocate this
5684 // call on the stack and we don't need its arguments to be
5685 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005686 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005687 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005688 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5689 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005690 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005691 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005692
Richard Smith87c1f1f2011-07-13 22:53:21 +00005693 QualType ConversionType = Conversion->getConversionType();
5694 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005695 Candidate.Viable = false;
5696 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5697 return;
5698 }
5699
Richard Smith87c1f1f2011-07-13 22:53:21 +00005700 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005701
Mike Stump1eb44332009-09-09 15:08:12 +00005702 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005703 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5704 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005705 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005706 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005707 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005708 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005709 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005710 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005711 /*InOverloadResolution=*/false,
5712 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005713
John McCall1d318332010-01-12 00:44:57 +00005714 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005715 case ImplicitConversionSequence::StandardConversion:
5716 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005717
Douglas Gregorc520c842010-04-12 23:42:09 +00005718 // C++ [over.ics.user]p3:
5719 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005720 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005721 // shall have exact match rank.
5722 if (Conversion->getPrimaryTemplate() &&
5723 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5724 Candidate.Viable = false;
5725 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5726 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005727
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005728 // C++0x [dcl.init.ref]p5:
5729 // In the second case, if the reference is an rvalue reference and
5730 // the second standard conversion sequence of the user-defined
5731 // conversion sequence includes an lvalue-to-rvalue conversion, the
5732 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005734 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5735 Candidate.Viable = false;
5736 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5737 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005738 break;
5739
5740 case ImplicitConversionSequence::BadConversion:
5741 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005742 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005743 break;
5744
5745 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005746 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005747 "Can only end up with a standard conversion sequence or failure");
5748 }
5749}
5750
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005751/// \brief Adds a conversion function template specialization
5752/// candidate to the overload set, using template argument deduction
5753/// to deduce the template arguments of the conversion function
5754/// template from the type that we are converting to (C++
5755/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005756void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005757Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005758 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005759 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005760 Expr *From, QualType ToType,
5761 OverloadCandidateSet &CandidateSet) {
5762 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5763 "Only conversion function templates permitted here");
5764
Douglas Gregor3f396022009-09-28 04:47:19 +00005765 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5766 return;
5767
John McCall5769d612010-02-08 23:07:23 +00005768 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005769 CXXConversionDecl *Specialization = 0;
5770 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005771 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005772 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005773 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005774 Candidate.FoundDecl = FoundDecl;
5775 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5776 Candidate.Viable = false;
5777 Candidate.FailureKind = ovl_fail_bad_deduction;
5778 Candidate.IsSurrogate = false;
5779 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005780 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005781 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005782 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005783 return;
5784 }
Mike Stump1eb44332009-09-09 15:08:12 +00005785
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005786 // Add the conversion function template specialization produced by
5787 // template argument deduction as a candidate.
5788 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005789 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005790 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005791}
5792
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005793/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5794/// converts the given @c Object to a function pointer via the
5795/// conversion function @c Conversion, and then attempts to call it
5796/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5797/// the type of function that we'll eventually be calling.
5798void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005799 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005800 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005801 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005802 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005803 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005804 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005805 if (!CandidateSet.isNewCandidate(Conversion))
5806 return;
5807
Douglas Gregor7edfb692009-11-23 12:27:39 +00005808 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005809 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005810
Ahmed Charles13a140c2012-02-25 11:00:22 +00005811 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005812 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005813 Candidate.Function = 0;
5814 Candidate.Surrogate = Conversion;
5815 Candidate.Viable = true;
5816 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005817 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005818 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005819
5820 // Determine the implicit conversion sequence for the implicit
5821 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005822 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005823 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005824 Object->Classify(Context),
5825 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005826 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005827 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005828 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005829 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005830 return;
5831 }
5832
5833 // The first conversion is actually a user-defined conversion whose
5834 // first conversion is ObjectInit's standard conversion (which is
5835 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005836 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005837 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005838 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005839 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005840 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005841 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005842 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005843 = Candidate.Conversions[0].UserDefined.Before;
5844 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5845
Mike Stump1eb44332009-09-09 15:08:12 +00005846 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005847 unsigned NumArgsInProto = Proto->getNumArgs();
5848
5849 // (C++ 13.3.2p2): A candidate function having fewer than m
5850 // parameters is viable only if it has an ellipsis in its parameter
5851 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005852 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005853 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005854 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005855 return;
5856 }
5857
5858 // Function types don't have any default arguments, so just check if
5859 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005860 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005861 // Not enough arguments.
5862 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005863 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005864 return;
5865 }
5866
5867 // Determine the implicit conversion sequences for each of the
5868 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005869 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005870 if (ArgIdx < NumArgsInProto) {
5871 // (C++ 13.3.2p3): for F to be a viable function, there shall
5872 // exist for each argument an implicit conversion sequence
5873 // (13.3.3.1) that converts that argument to the corresponding
5874 // parameter of F.
5875 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005876 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005877 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005878 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005879 /*InOverloadResolution=*/false,
5880 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005881 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005882 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005883 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005884 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005885 break;
5886 }
5887 } else {
5888 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5889 // argument for which there is no corresponding parameter is
5890 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005891 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005892 }
5893 }
5894}
5895
Douglas Gregor063daf62009-03-13 18:40:31 +00005896/// \brief Add overload candidates for overloaded operators that are
5897/// member functions.
5898///
5899/// Add the overloaded operator candidates that are member functions
5900/// for the operator Op that was used in an operator expression such
5901/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5902/// CandidateSet will store the added overload candidates. (C++
5903/// [over.match.oper]).
5904void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5905 SourceLocation OpLoc,
5906 Expr **Args, unsigned NumArgs,
5907 OverloadCandidateSet& CandidateSet,
5908 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005909 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5910
5911 // C++ [over.match.oper]p3:
5912 // For a unary operator @ with an operand of a type whose
5913 // cv-unqualified version is T1, and for a binary operator @ with
5914 // a left operand of a type whose cv-unqualified version is T1 and
5915 // a right operand of a type whose cv-unqualified version is T2,
5916 // three sets of candidate functions, designated member
5917 // candidates, non-member candidates and built-in candidates, are
5918 // constructed as follows:
5919 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005920
5921 // -- If T1 is a class type, the set of member candidates is the
5922 // result of the qualified lookup of T1::operator@
5923 // (13.3.1.1.1); otherwise, the set of member candidates is
5924 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005925 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005926 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005927 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005929
John McCalla24dc2e2009-11-17 02:14:36 +00005930 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5931 LookupQualifiedName(Operators, T1Rec->getDecl());
5932 Operators.suppressDiagnostics();
5933
Mike Stump1eb44332009-09-09 15:08:12 +00005934 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005935 OperEnd = Operators.end();
5936 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005937 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005938 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005939 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005940 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005941 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005942 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005943}
5944
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005945/// AddBuiltinCandidate - Add a candidate for a built-in
5946/// operator. ResultTy and ParamTys are the result and parameter types
5947/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005948/// arguments being passed to the candidate. IsAssignmentOperator
5949/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005950/// operator. NumContextualBoolArguments is the number of arguments
5951/// (at the beginning of the argument list) that will be contextually
5952/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005953void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005954 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005955 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005956 bool IsAssignmentOperator,
5957 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005958 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005959 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005960
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005961 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005962 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005963 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005964 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005965 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005966 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005967 Candidate.BuiltinTypes.ResultTy = ResultTy;
5968 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5969 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5970
5971 // Determine the implicit conversion sequences for each of the
5972 // arguments.
5973 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005974 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005975 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005976 // C++ [over.match.oper]p4:
5977 // For the built-in assignment operators, conversions of the
5978 // left operand are restricted as follows:
5979 // -- no temporaries are introduced to hold the left operand, and
5980 // -- no user-defined conversions are applied to the left
5981 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005982 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005983 //
5984 // We block these conversions by turning off user-defined
5985 // conversions, since that is the only way that initialization of
5986 // a reference to a non-class type can occur from something that
5987 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005988 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005989 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005990 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005991 Candidate.Conversions[ArgIdx]
5992 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005993 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005994 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005995 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005996 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005997 /*InOverloadResolution=*/false,
5998 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005999 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006000 }
John McCall1d318332010-01-12 00:44:57 +00006001 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006002 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006003 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006004 break;
6005 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006006 }
6007}
6008
6009/// BuiltinCandidateTypeSet - A set of types that will be used for the
6010/// candidate operator functions for built-in operators (C++
6011/// [over.built]). The types are separated into pointer types and
6012/// enumeration types.
6013class BuiltinCandidateTypeSet {
6014 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006015 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006016
6017 /// PointerTypes - The set of pointer types that will be used in the
6018 /// built-in candidates.
6019 TypeSet PointerTypes;
6020
Sebastian Redl78eb8742009-04-19 21:53:20 +00006021 /// MemberPointerTypes - The set of member pointer types that will be
6022 /// used in the built-in candidates.
6023 TypeSet MemberPointerTypes;
6024
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006025 /// EnumerationTypes - The set of enumeration types that will be
6026 /// used in the built-in candidates.
6027 TypeSet EnumerationTypes;
6028
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006029 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006030 /// candidates.
6031 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006032
6033 /// \brief A flag indicating non-record types are viable candidates
6034 bool HasNonRecordTypes;
6035
6036 /// \brief A flag indicating whether either arithmetic or enumeration types
6037 /// were present in the candidate set.
6038 bool HasArithmeticOrEnumeralTypes;
6039
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006040 /// \brief A flag indicating whether the nullptr type was present in the
6041 /// candidate set.
6042 bool HasNullPtrType;
6043
Douglas Gregor5842ba92009-08-24 15:23:48 +00006044 /// Sema - The semantic analysis instance where we are building the
6045 /// candidate type set.
6046 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006047
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006048 /// Context - The AST context in which we will build the type sets.
6049 ASTContext &Context;
6050
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006051 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6052 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006053 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006054
6055public:
6056 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006057 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006058
Mike Stump1eb44332009-09-09 15:08:12 +00006059 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006060 : HasNonRecordTypes(false),
6061 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006062 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006063 SemaRef(SemaRef),
6064 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006065
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006066 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006067 SourceLocation Loc,
6068 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006069 bool AllowExplicitConversions,
6070 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006071
6072 /// pointer_begin - First pointer type found;
6073 iterator pointer_begin() { return PointerTypes.begin(); }
6074
Sebastian Redl78eb8742009-04-19 21:53:20 +00006075 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006076 iterator pointer_end() { return PointerTypes.end(); }
6077
Sebastian Redl78eb8742009-04-19 21:53:20 +00006078 /// member_pointer_begin - First member pointer type found;
6079 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6080
6081 /// member_pointer_end - Past the last member pointer type found;
6082 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6083
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006084 /// enumeration_begin - First enumeration type found;
6085 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6086
Sebastian Redl78eb8742009-04-19 21:53:20 +00006087 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006088 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006089
Douglas Gregor26bcf672010-05-19 03:21:00 +00006090 iterator vector_begin() { return VectorTypes.begin(); }
6091 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006092
6093 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6094 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006095 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006096};
6097
Sebastian Redl78eb8742009-04-19 21:53:20 +00006098/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006099/// the set of pointer types along with any more-qualified variants of
6100/// that type. For example, if @p Ty is "int const *", this routine
6101/// will add "int const *", "int const volatile *", "int const
6102/// restrict *", and "int const volatile restrict *" to the set of
6103/// pointer types. Returns true if the add of @p Ty itself succeeded,
6104/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006105///
6106/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006107bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006108BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6109 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006110
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006111 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006112 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006113 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006114
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006115 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006116 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006117 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006118 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006119 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6120 PointeeTy = PTy->getPointeeType();
6121 buildObjCPtr = true;
6122 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006123 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006124 }
6125
Sebastian Redla9efada2009-11-18 20:39:26 +00006126 // Don't add qualified variants of arrays. For one, they're not allowed
6127 // (the qualifier would sink to the element type), and for another, the
6128 // only overload situation where it matters is subscript or pointer +- int,
6129 // and those shouldn't have qualifier variants anyway.
6130 if (PointeeTy->isArrayType())
6131 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006132
John McCall0953e762009-09-24 19:53:00 +00006133 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006134 bool hasVolatile = VisibleQuals.hasVolatile();
6135 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006136
John McCall0953e762009-09-24 19:53:00 +00006137 // Iterate through all strict supersets of BaseCVR.
6138 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6139 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006140 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006141 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006142
6143 // Skip over restrict if no restrict found anywhere in the types, or if
6144 // the type cannot be restrict-qualified.
6145 if ((CVR & Qualifiers::Restrict) &&
6146 (!hasRestrict ||
6147 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6148 continue;
6149
6150 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006151 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006152
6153 // Build qualified pointer type.
6154 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006155 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006156 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006157 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006158 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6159
6160 // Insert qualified pointer type.
6161 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006162 }
6163
6164 return true;
6165}
6166
Sebastian Redl78eb8742009-04-19 21:53:20 +00006167/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6168/// to the set of pointer types along with any more-qualified variants of
6169/// that type. For example, if @p Ty is "int const *", this routine
6170/// will add "int const *", "int const volatile *", "int const
6171/// restrict *", and "int const volatile restrict *" to the set of
6172/// pointer types. Returns true if the add of @p Ty itself succeeded,
6173/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006174///
6175/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006176bool
6177BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6178 QualType Ty) {
6179 // Insert this type.
6180 if (!MemberPointerTypes.insert(Ty))
6181 return false;
6182
John McCall0953e762009-09-24 19:53:00 +00006183 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6184 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006185
John McCall0953e762009-09-24 19:53:00 +00006186 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006187 // Don't add qualified variants of arrays. For one, they're not allowed
6188 // (the qualifier would sink to the element type), and for another, the
6189 // only overload situation where it matters is subscript or pointer +- int,
6190 // and those shouldn't have qualifier variants anyway.
6191 if (PointeeTy->isArrayType())
6192 return true;
John McCall0953e762009-09-24 19:53:00 +00006193 const Type *ClassTy = PointerTy->getClass();
6194
6195 // Iterate through all strict supersets of the pointee type's CVR
6196 // qualifiers.
6197 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6198 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6199 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006200
John McCall0953e762009-09-24 19:53:00 +00006201 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006202 MemberPointerTypes.insert(
6203 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006204 }
6205
6206 return true;
6207}
6208
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006209/// AddTypesConvertedFrom - Add each of the types to which the type @p
6210/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006211/// primarily interested in pointer types and enumeration types. We also
6212/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006213/// AllowUserConversions is true if we should look at the conversion
6214/// functions of a class type, and AllowExplicitConversions if we
6215/// should also include the explicit conversion functions of a class
6216/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006217void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006218BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006219 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006220 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006221 bool AllowExplicitConversions,
6222 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006223 // Only deal with canonical types.
6224 Ty = Context.getCanonicalType(Ty);
6225
6226 // Look through reference types; they aren't part of the type of an
6227 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006228 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006229 Ty = RefTy->getPointeeType();
6230
John McCall3b657512011-01-19 10:06:00 +00006231 // If we're dealing with an array type, decay to the pointer.
6232 if (Ty->isArrayType())
6233 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6234
6235 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006236 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006237
Chandler Carruth6a577462010-12-13 01:44:01 +00006238 // Flag if we ever add a non-record type.
6239 const RecordType *TyRec = Ty->getAs<RecordType>();
6240 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6241
Chandler Carruth6a577462010-12-13 01:44:01 +00006242 // Flag if we encounter an arithmetic type.
6243 HasArithmeticOrEnumeralTypes =
6244 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6245
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006246 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6247 PointerTypes.insert(Ty);
6248 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006249 // Insert our type, and its more-qualified variants, into the set
6250 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006251 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006252 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006253 } else if (Ty->isMemberPointerType()) {
6254 // Member pointers are far easier, since the pointee can't be converted.
6255 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6256 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006257 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006258 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006259 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006260 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006261 // We treat vector types as arithmetic types in many contexts as an
6262 // extension.
6263 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006264 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006265 } else if (Ty->isNullPtrType()) {
6266 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006267 } else if (AllowUserConversions && TyRec) {
6268 // No conversion functions in incomplete types.
6269 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6270 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006271
Chandler Carruth6a577462010-12-13 01:44:01 +00006272 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6273 const UnresolvedSetImpl *Conversions
6274 = ClassDecl->getVisibleConversionFunctions();
6275 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6276 E = Conversions->end(); I != E; ++I) {
6277 NamedDecl *D = I.getDecl();
6278 if (isa<UsingShadowDecl>(D))
6279 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006280
Chandler Carruth6a577462010-12-13 01:44:01 +00006281 // Skip conversion function templates; they don't tell us anything
6282 // about which builtin types we can convert to.
6283 if (isa<FunctionTemplateDecl>(D))
6284 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006285
Chandler Carruth6a577462010-12-13 01:44:01 +00006286 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6287 if (AllowExplicitConversions || !Conv->isExplicit()) {
6288 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6289 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006290 }
6291 }
6292 }
6293}
6294
Douglas Gregor19b7b152009-08-24 13:43:27 +00006295/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6296/// the volatile- and non-volatile-qualified assignment operators for the
6297/// given type to the candidate set.
6298static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6299 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006300 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006301 unsigned NumArgs,
6302 OverloadCandidateSet &CandidateSet) {
6303 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006304
Douglas Gregor19b7b152009-08-24 13:43:27 +00006305 // T& operator=(T&, T)
6306 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6307 ParamTypes[1] = T;
6308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6309 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006310
Douglas Gregor19b7b152009-08-24 13:43:27 +00006311 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6312 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006313 ParamTypes[0]
6314 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006315 ParamTypes[1] = T;
6316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006317 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006318 }
6319}
Mike Stump1eb44332009-09-09 15:08:12 +00006320
Sebastian Redl9994a342009-10-25 17:03:50 +00006321/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6322/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006323static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6324 Qualifiers VRQuals;
6325 const RecordType *TyRec;
6326 if (const MemberPointerType *RHSMPType =
6327 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006328 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006329 else
6330 TyRec = ArgExpr->getType()->getAs<RecordType>();
6331 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006332 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006333 VRQuals.addVolatile();
6334 VRQuals.addRestrict();
6335 return VRQuals;
6336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006337
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006338 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006339 if (!ClassDecl->hasDefinition())
6340 return VRQuals;
6341
John McCalleec51cf2010-01-20 00:46:10 +00006342 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006343 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006344
John McCalleec51cf2010-01-20 00:46:10 +00006345 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006346 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006347 NamedDecl *D = I.getDecl();
6348 if (isa<UsingShadowDecl>(D))
6349 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6350 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006351 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6352 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6353 CanTy = ResTypeRef->getPointeeType();
6354 // Need to go down the pointer/mempointer chain and add qualifiers
6355 // as see them.
6356 bool done = false;
6357 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006358 if (CanTy.isRestrictQualified())
6359 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006360 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6361 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006362 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006363 CanTy->getAs<MemberPointerType>())
6364 CanTy = ResTypeMPtr->getPointeeType();
6365 else
6366 done = true;
6367 if (CanTy.isVolatileQualified())
6368 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006369 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6370 return VRQuals;
6371 }
6372 }
6373 }
6374 return VRQuals;
6375}
John McCall00071ec2010-11-13 05:51:15 +00006376
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006377namespace {
John McCall00071ec2010-11-13 05:51:15 +00006378
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006379/// \brief Helper class to manage the addition of builtin operator overload
6380/// candidates. It provides shared state and utility methods used throughout
6381/// the process, as well as a helper method to add each group of builtin
6382/// operator overloads from the standard to a candidate set.
6383class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006384 // Common instance state available to all overload candidate addition methods.
6385 Sema &S;
6386 Expr **Args;
6387 unsigned NumArgs;
6388 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006389 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006390 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006391 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006392
Chandler Carruth6d695582010-12-12 10:35:00 +00006393 // Define some constants used to index and iterate over the arithemetic types
6394 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006395 // The "promoted arithmetic types" are the arithmetic
6396 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006397 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006398 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006399 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006400 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006401 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006402 LastPromotedArithmeticType = 11;
6403 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006404
Chandler Carruth6d695582010-12-12 10:35:00 +00006405 /// \brief Get the canonical type for a given arithmetic type index.
6406 CanQualType getArithmeticType(unsigned index) {
6407 assert(index < NumArithmeticTypes);
6408 static CanQualType ASTContext::* const
6409 ArithmeticTypes[NumArithmeticTypes] = {
6410 // Start of promoted types.
6411 &ASTContext::FloatTy,
6412 &ASTContext::DoubleTy,
6413 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006414
Chandler Carruth6d695582010-12-12 10:35:00 +00006415 // Start of integral types.
6416 &ASTContext::IntTy,
6417 &ASTContext::LongTy,
6418 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006419 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006420 &ASTContext::UnsignedIntTy,
6421 &ASTContext::UnsignedLongTy,
6422 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006423 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006424 // End of promoted types.
6425
6426 &ASTContext::BoolTy,
6427 &ASTContext::CharTy,
6428 &ASTContext::WCharTy,
6429 &ASTContext::Char16Ty,
6430 &ASTContext::Char32Ty,
6431 &ASTContext::SignedCharTy,
6432 &ASTContext::ShortTy,
6433 &ASTContext::UnsignedCharTy,
6434 &ASTContext::UnsignedShortTy,
6435 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006436 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006437 };
6438 return S.Context.*ArithmeticTypes[index];
6439 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006440
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006441 /// \brief Gets the canonical type resulting from the usual arithemetic
6442 /// converions for the given arithmetic types.
6443 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6444 // Accelerator table for performing the usual arithmetic conversions.
6445 // The rules are basically:
6446 // - if either is floating-point, use the wider floating-point
6447 // - if same signedness, use the higher rank
6448 // - if same size, use unsigned of the higher rank
6449 // - use the larger type
6450 // These rules, together with the axiom that higher ranks are
6451 // never smaller, are sufficient to precompute all of these results
6452 // *except* when dealing with signed types of higher rank.
6453 // (we could precompute SLL x UI for all known platforms, but it's
6454 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006455 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006456 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006457 Dep=-1,
6458 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006459 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006460 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006461 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006462/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6463/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6464/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6465/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6466/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6467/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6468/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6469/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6470/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6471/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6472/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006473 };
6474
6475 assert(L < LastPromotedArithmeticType);
6476 assert(R < LastPromotedArithmeticType);
6477 int Idx = ConversionsTable[L][R];
6478
6479 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006480 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006481
6482 // Slow path: we need to compare widths.
6483 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006484 CanQualType LT = getArithmeticType(L),
6485 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006486 unsigned LW = S.Context.getIntWidth(LT),
6487 RW = S.Context.getIntWidth(RT);
6488
6489 // If they're different widths, use the signed type.
6490 if (LW > RW) return LT;
6491 else if (LW < RW) return RT;
6492
6493 // Otherwise, use the unsigned type of the signed type's rank.
6494 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6495 assert(L == SLL || R == SLL);
6496 return S.Context.UnsignedLongLongTy;
6497 }
6498
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006499 /// \brief Helper method to factor out the common pattern of adding overloads
6500 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006501 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006502 bool HasVolatile,
6503 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006504 QualType ParamTypes[2] = {
6505 S.Context.getLValueReferenceType(CandidateTy),
6506 S.Context.IntTy
6507 };
6508
6509 // Non-volatile version.
6510 if (NumArgs == 1)
6511 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6512 else
6513 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6514
6515 // Use a heuristic to reduce number of builtin candidates in the set:
6516 // add volatile version only if there are conversions to a volatile type.
6517 if (HasVolatile) {
6518 ParamTypes[0] =
6519 S.Context.getLValueReferenceType(
6520 S.Context.getVolatileType(CandidateTy));
6521 if (NumArgs == 1)
6522 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6523 else
6524 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6525 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006526
6527 // Add restrict version only if there are conversions to a restrict type
6528 // and our candidate type is a non-restrict-qualified pointer.
6529 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6530 !CandidateTy.isRestrictQualified()) {
6531 ParamTypes[0]
6532 = S.Context.getLValueReferenceType(
6533 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6534 if (NumArgs == 1)
6535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6536 else
6537 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6538
6539 if (HasVolatile) {
6540 ParamTypes[0]
6541 = S.Context.getLValueReferenceType(
6542 S.Context.getCVRQualifiedType(CandidateTy,
6543 (Qualifiers::Volatile |
6544 Qualifiers::Restrict)));
6545 if (NumArgs == 1)
6546 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6547 CandidateSet);
6548 else
6549 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6550 }
6551 }
6552
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006553 }
6554
6555public:
6556 BuiltinOperatorOverloadBuilder(
6557 Sema &S, Expr **Args, unsigned NumArgs,
6558 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006559 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006560 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006561 OverloadCandidateSet &CandidateSet)
6562 : S(S), Args(Args), NumArgs(NumArgs),
6563 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006564 HasArithmeticOrEnumeralCandidateType(
6565 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006566 CandidateTypes(CandidateTypes),
6567 CandidateSet(CandidateSet) {
6568 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006569 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006570 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006571 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006572 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006573 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006574 assert(getArithmeticType(FirstPromotedArithmeticType)
6575 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006576 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006577 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006578 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006579 "Invalid last promoted arithmetic type");
6580 }
6581
6582 // C++ [over.built]p3:
6583 //
6584 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6585 // is either volatile or empty, there exist candidate operator
6586 // functions of the form
6587 //
6588 // VQ T& operator++(VQ T&);
6589 // T operator++(VQ T&, int);
6590 //
6591 // C++ [over.built]p4:
6592 //
6593 // For every pair (T, VQ), where T is an arithmetic type other
6594 // than bool, and VQ is either volatile or empty, there exist
6595 // candidate operator functions of the form
6596 //
6597 // VQ T& operator--(VQ T&);
6598 // T operator--(VQ T&, int);
6599 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006600 if (!HasArithmeticOrEnumeralCandidateType)
6601 return;
6602
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006603 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6604 Arith < NumArithmeticTypes; ++Arith) {
6605 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006606 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006607 VisibleTypeConversionsQuals.hasVolatile(),
6608 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006609 }
6610 }
6611
6612 // C++ [over.built]p5:
6613 //
6614 // For every pair (T, VQ), where T is a cv-qualified or
6615 // cv-unqualified object type, and VQ is either volatile or
6616 // empty, there exist candidate operator functions of the form
6617 //
6618 // T*VQ& operator++(T*VQ&);
6619 // T*VQ& operator--(T*VQ&);
6620 // T* operator++(T*VQ&, int);
6621 // T* operator--(T*VQ&, int);
6622 void addPlusPlusMinusMinusPointerOverloads() {
6623 for (BuiltinCandidateTypeSet::iterator
6624 Ptr = CandidateTypes[0].pointer_begin(),
6625 PtrEnd = CandidateTypes[0].pointer_end();
6626 Ptr != PtrEnd; ++Ptr) {
6627 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006628 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006629 continue;
6630
6631 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006632 (!(*Ptr).isVolatileQualified() &&
6633 VisibleTypeConversionsQuals.hasVolatile()),
6634 (!(*Ptr).isRestrictQualified() &&
6635 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006636 }
6637 }
6638
6639 // C++ [over.built]p6:
6640 // For every cv-qualified or cv-unqualified object type T, there
6641 // exist candidate operator functions of the form
6642 //
6643 // T& operator*(T*);
6644 //
6645 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006646 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006647 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006648 // T& operator*(T*);
6649 void addUnaryStarPointerOverloads() {
6650 for (BuiltinCandidateTypeSet::iterator
6651 Ptr = CandidateTypes[0].pointer_begin(),
6652 PtrEnd = CandidateTypes[0].pointer_end();
6653 Ptr != PtrEnd; ++Ptr) {
6654 QualType ParamTy = *Ptr;
6655 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006656 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6657 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006658
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006659 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6660 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6661 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006662
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006663 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6664 &ParamTy, Args, 1, CandidateSet);
6665 }
6666 }
6667
6668 // C++ [over.built]p9:
6669 // For every promoted arithmetic type T, there exist candidate
6670 // operator functions of the form
6671 //
6672 // T operator+(T);
6673 // T operator-(T);
6674 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006675 if (!HasArithmeticOrEnumeralCandidateType)
6676 return;
6677
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006678 for (unsigned Arith = FirstPromotedArithmeticType;
6679 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006680 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006681 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6682 }
6683
6684 // Extension: We also add these operators for vector types.
6685 for (BuiltinCandidateTypeSet::iterator
6686 Vec = CandidateTypes[0].vector_begin(),
6687 VecEnd = CandidateTypes[0].vector_end();
6688 Vec != VecEnd; ++Vec) {
6689 QualType VecTy = *Vec;
6690 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6691 }
6692 }
6693
6694 // C++ [over.built]p8:
6695 // For every type T, there exist candidate operator functions of
6696 // the form
6697 //
6698 // T* operator+(T*);
6699 void addUnaryPlusPointerOverloads() {
6700 for (BuiltinCandidateTypeSet::iterator
6701 Ptr = CandidateTypes[0].pointer_begin(),
6702 PtrEnd = CandidateTypes[0].pointer_end();
6703 Ptr != PtrEnd; ++Ptr) {
6704 QualType ParamTy = *Ptr;
6705 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6706 }
6707 }
6708
6709 // C++ [over.built]p10:
6710 // For every promoted integral type T, there exist candidate
6711 // operator functions of the form
6712 //
6713 // T operator~(T);
6714 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006715 if (!HasArithmeticOrEnumeralCandidateType)
6716 return;
6717
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006718 for (unsigned Int = FirstPromotedIntegralType;
6719 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006720 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006721 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6722 }
6723
6724 // Extension: We also add this operator for vector types.
6725 for (BuiltinCandidateTypeSet::iterator
6726 Vec = CandidateTypes[0].vector_begin(),
6727 VecEnd = CandidateTypes[0].vector_end();
6728 Vec != VecEnd; ++Vec) {
6729 QualType VecTy = *Vec;
6730 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6731 }
6732 }
6733
6734 // C++ [over.match.oper]p16:
6735 // For every pointer to member type T, there exist candidate operator
6736 // functions of the form
6737 //
6738 // bool operator==(T,T);
6739 // bool operator!=(T,T);
6740 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6741 /// Set of (canonical) types that we've already handled.
6742 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6743
6744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6745 for (BuiltinCandidateTypeSet::iterator
6746 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6747 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6748 MemPtr != MemPtrEnd;
6749 ++MemPtr) {
6750 // Don't add the same builtin candidate twice.
6751 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6752 continue;
6753
6754 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6755 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6756 CandidateSet);
6757 }
6758 }
6759 }
6760
6761 // C++ [over.built]p15:
6762 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006763 // For every T, where T is an enumeration type, a pointer type, or
6764 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006765 //
6766 // bool operator<(T, T);
6767 // bool operator>(T, T);
6768 // bool operator<=(T, T);
6769 // bool operator>=(T, T);
6770 // bool operator==(T, T);
6771 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006772 void addRelationalPointerOrEnumeralOverloads() {
6773 // C++ [over.built]p1:
6774 // If there is a user-written candidate with the same name and parameter
6775 // types as a built-in candidate operator function, the built-in operator
6776 // function is hidden and is not included in the set of candidate
6777 // functions.
6778 //
6779 // The text is actually in a note, but if we don't implement it then we end
6780 // up with ambiguities when the user provides an overloaded operator for
6781 // an enumeration type. Note that only enumeration types have this problem,
6782 // so we track which enumeration types we've seen operators for. Also, the
6783 // only other overloaded operator with enumeration argumenst, operator=,
6784 // cannot be overloaded for enumeration types, so this is the only place
6785 // where we must suppress candidates like this.
6786 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6787 UserDefinedBinaryOperators;
6788
6789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6790 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6791 CandidateTypes[ArgIdx].enumeration_end()) {
6792 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6793 CEnd = CandidateSet.end();
6794 C != CEnd; ++C) {
6795 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6796 continue;
6797
6798 QualType FirstParamType =
6799 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6800 QualType SecondParamType =
6801 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6802
6803 // Skip if either parameter isn't of enumeral type.
6804 if (!FirstParamType->isEnumeralType() ||
6805 !SecondParamType->isEnumeralType())
6806 continue;
6807
6808 // Add this operator to the set of known user-defined operators.
6809 UserDefinedBinaryOperators.insert(
6810 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6811 S.Context.getCanonicalType(SecondParamType)));
6812 }
6813 }
6814 }
6815
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006816 /// Set of (canonical) types that we've already handled.
6817 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6818
6819 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6820 for (BuiltinCandidateTypeSet::iterator
6821 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6822 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6823 Ptr != PtrEnd; ++Ptr) {
6824 // Don't add the same builtin candidate twice.
6825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6826 continue;
6827
6828 QualType ParamTypes[2] = { *Ptr, *Ptr };
6829 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6830 CandidateSet);
6831 }
6832 for (BuiltinCandidateTypeSet::iterator
6833 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6834 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6835 Enum != EnumEnd; ++Enum) {
6836 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6837
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006838 // Don't add the same builtin candidate twice, or if a user defined
6839 // candidate exists.
6840 if (!AddedTypes.insert(CanonType) ||
6841 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6842 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006843 continue;
6844
6845 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006846 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6847 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006848 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006849
6850 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6851 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6852 if (AddedTypes.insert(NullPtrTy) &&
6853 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6854 NullPtrTy))) {
6855 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6856 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6857 CandidateSet);
6858 }
6859 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006860 }
6861 }
6862
6863 // C++ [over.built]p13:
6864 //
6865 // For every cv-qualified or cv-unqualified object type T
6866 // there exist candidate operator functions of the form
6867 //
6868 // T* operator+(T*, ptrdiff_t);
6869 // T& operator[](T*, ptrdiff_t); [BELOW]
6870 // T* operator-(T*, ptrdiff_t);
6871 // T* operator+(ptrdiff_t, T*);
6872 // T& operator[](ptrdiff_t, T*); [BELOW]
6873 //
6874 // C++ [over.built]p14:
6875 //
6876 // For every T, where T is a pointer to object type, there
6877 // exist candidate operator functions of the form
6878 //
6879 // ptrdiff_t operator-(T, T);
6880 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6881 /// Set of (canonical) types that we've already handled.
6882 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6883
6884 for (int Arg = 0; Arg < 2; ++Arg) {
6885 QualType AsymetricParamTypes[2] = {
6886 S.Context.getPointerDiffType(),
6887 S.Context.getPointerDiffType(),
6888 };
6889 for (BuiltinCandidateTypeSet::iterator
6890 Ptr = CandidateTypes[Arg].pointer_begin(),
6891 PtrEnd = CandidateTypes[Arg].pointer_end();
6892 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006893 QualType PointeeTy = (*Ptr)->getPointeeType();
6894 if (!PointeeTy->isObjectType())
6895 continue;
6896
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006897 AsymetricParamTypes[Arg] = *Ptr;
6898 if (Arg == 0 || Op == OO_Plus) {
6899 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6900 // T* operator+(ptrdiff_t, T*);
6901 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6902 CandidateSet);
6903 }
6904 if (Op == OO_Minus) {
6905 // ptrdiff_t operator-(T, T);
6906 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6907 continue;
6908
6909 QualType ParamTypes[2] = { *Ptr, *Ptr };
6910 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6911 Args, 2, CandidateSet);
6912 }
6913 }
6914 }
6915 }
6916
6917 // C++ [over.built]p12:
6918 //
6919 // For every pair of promoted arithmetic types L and R, there
6920 // exist candidate operator functions of the form
6921 //
6922 // LR operator*(L, R);
6923 // LR operator/(L, R);
6924 // LR operator+(L, R);
6925 // LR operator-(L, R);
6926 // bool operator<(L, R);
6927 // bool operator>(L, R);
6928 // bool operator<=(L, R);
6929 // bool operator>=(L, R);
6930 // bool operator==(L, R);
6931 // bool operator!=(L, R);
6932 //
6933 // where LR is the result of the usual arithmetic conversions
6934 // between types L and R.
6935 //
6936 // C++ [over.built]p24:
6937 //
6938 // For every pair of promoted arithmetic types L and R, there exist
6939 // candidate operator functions of the form
6940 //
6941 // LR operator?(bool, L, R);
6942 //
6943 // where LR is the result of the usual arithmetic conversions
6944 // between types L and R.
6945 // Our candidates ignore the first parameter.
6946 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006947 if (!HasArithmeticOrEnumeralCandidateType)
6948 return;
6949
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 for (unsigned Left = FirstPromotedArithmeticType;
6951 Left < LastPromotedArithmeticType; ++Left) {
6952 for (unsigned Right = FirstPromotedArithmeticType;
6953 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006954 QualType LandR[2] = { getArithmeticType(Left),
6955 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006956 QualType Result =
6957 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006958 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006959 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6960 }
6961 }
6962
6963 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6964 // conditional operator for vector types.
6965 for (BuiltinCandidateTypeSet::iterator
6966 Vec1 = CandidateTypes[0].vector_begin(),
6967 Vec1End = CandidateTypes[0].vector_end();
6968 Vec1 != Vec1End; ++Vec1) {
6969 for (BuiltinCandidateTypeSet::iterator
6970 Vec2 = CandidateTypes[1].vector_begin(),
6971 Vec2End = CandidateTypes[1].vector_end();
6972 Vec2 != Vec2End; ++Vec2) {
6973 QualType LandR[2] = { *Vec1, *Vec2 };
6974 QualType Result = S.Context.BoolTy;
6975 if (!isComparison) {
6976 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6977 Result = *Vec1;
6978 else
6979 Result = *Vec2;
6980 }
6981
6982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6983 }
6984 }
6985 }
6986
6987 // C++ [over.built]p17:
6988 //
6989 // For every pair of promoted integral types L and R, there
6990 // exist candidate operator functions of the form
6991 //
6992 // LR operator%(L, R);
6993 // LR operator&(L, R);
6994 // LR operator^(L, R);
6995 // LR operator|(L, R);
6996 // L operator<<(L, R);
6997 // L operator>>(L, R);
6998 //
6999 // where LR is the result of the usual arithmetic conversions
7000 // between types L and R.
7001 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007002 if (!HasArithmeticOrEnumeralCandidateType)
7003 return;
7004
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007005 for (unsigned Left = FirstPromotedIntegralType;
7006 Left < LastPromotedIntegralType; ++Left) {
7007 for (unsigned Right = FirstPromotedIntegralType;
7008 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007009 QualType LandR[2] = { getArithmeticType(Left),
7010 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007011 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7012 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007013 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007014 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7015 }
7016 }
7017 }
7018
7019 // C++ [over.built]p20:
7020 //
7021 // For every pair (T, VQ), where T is an enumeration or
7022 // pointer to member type and VQ is either volatile or
7023 // empty, there exist candidate operator functions of the form
7024 //
7025 // VQ T& operator=(VQ T&, T);
7026 void addAssignmentMemberPointerOrEnumeralOverloads() {
7027 /// Set of (canonical) types that we've already handled.
7028 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7029
7030 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7031 for (BuiltinCandidateTypeSet::iterator
7032 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7033 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7034 Enum != EnumEnd; ++Enum) {
7035 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7036 continue;
7037
7038 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7039 CandidateSet);
7040 }
7041
7042 for (BuiltinCandidateTypeSet::iterator
7043 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7044 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7045 MemPtr != MemPtrEnd; ++MemPtr) {
7046 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7047 continue;
7048
7049 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7050 CandidateSet);
7051 }
7052 }
7053 }
7054
7055 // C++ [over.built]p19:
7056 //
7057 // For every pair (T, VQ), where T is any type and VQ is either
7058 // volatile or empty, there exist candidate operator functions
7059 // of the form
7060 //
7061 // T*VQ& operator=(T*VQ&, T*);
7062 //
7063 // C++ [over.built]p21:
7064 //
7065 // For every pair (T, VQ), where T is a cv-qualified or
7066 // cv-unqualified object type and VQ is either volatile or
7067 // empty, there exist candidate operator functions of the form
7068 //
7069 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7070 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7071 void addAssignmentPointerOverloads(bool isEqualOp) {
7072 /// Set of (canonical) types that we've already handled.
7073 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7074
7075 for (BuiltinCandidateTypeSet::iterator
7076 Ptr = CandidateTypes[0].pointer_begin(),
7077 PtrEnd = CandidateTypes[0].pointer_end();
7078 Ptr != PtrEnd; ++Ptr) {
7079 // If this is operator=, keep track of the builtin candidates we added.
7080 if (isEqualOp)
7081 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007082 else if (!(*Ptr)->getPointeeType()->isObjectType())
7083 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007084
7085 // non-volatile version
7086 QualType ParamTypes[2] = {
7087 S.Context.getLValueReferenceType(*Ptr),
7088 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7089 };
7090 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7091 /*IsAssigmentOperator=*/ isEqualOp);
7092
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007093 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7094 VisibleTypeConversionsQuals.hasVolatile();
7095 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007096 // volatile version
7097 ParamTypes[0] =
7098 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7100 /*IsAssigmentOperator=*/isEqualOp);
7101 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007102
7103 if (!(*Ptr).isRestrictQualified() &&
7104 VisibleTypeConversionsQuals.hasRestrict()) {
7105 // restrict version
7106 ParamTypes[0]
7107 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7109 /*IsAssigmentOperator=*/isEqualOp);
7110
7111 if (NeedVolatile) {
7112 // volatile restrict version
7113 ParamTypes[0]
7114 = S.Context.getLValueReferenceType(
7115 S.Context.getCVRQualifiedType(*Ptr,
7116 (Qualifiers::Volatile |
7117 Qualifiers::Restrict)));
7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7119 CandidateSet,
7120 /*IsAssigmentOperator=*/isEqualOp);
7121 }
7122 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007123 }
7124
7125 if (isEqualOp) {
7126 for (BuiltinCandidateTypeSet::iterator
7127 Ptr = CandidateTypes[1].pointer_begin(),
7128 PtrEnd = CandidateTypes[1].pointer_end();
7129 Ptr != PtrEnd; ++Ptr) {
7130 // Make sure we don't add the same candidate twice.
7131 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7132 continue;
7133
Chandler Carruth6df868e2010-12-12 08:17:55 +00007134 QualType ParamTypes[2] = {
7135 S.Context.getLValueReferenceType(*Ptr),
7136 *Ptr,
7137 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007138
7139 // non-volatile version
7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7141 /*IsAssigmentOperator=*/true);
7142
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007143 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7144 VisibleTypeConversionsQuals.hasVolatile();
7145 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007146 // volatile version
7147 ParamTypes[0] =
7148 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7150 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007151 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007152
7153 if (!(*Ptr).isRestrictQualified() &&
7154 VisibleTypeConversionsQuals.hasRestrict()) {
7155 // restrict version
7156 ParamTypes[0]
7157 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7159 CandidateSet, /*IsAssigmentOperator=*/true);
7160
7161 if (NeedVolatile) {
7162 // volatile restrict version
7163 ParamTypes[0]
7164 = S.Context.getLValueReferenceType(
7165 S.Context.getCVRQualifiedType(*Ptr,
7166 (Qualifiers::Volatile |
7167 Qualifiers::Restrict)));
7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7169 CandidateSet, /*IsAssigmentOperator=*/true);
7170
7171 }
7172 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007173 }
7174 }
7175 }
7176
7177 // C++ [over.built]p18:
7178 //
7179 // For every triple (L, VQ, R), where L is an arithmetic type,
7180 // VQ is either volatile or empty, and R is a promoted
7181 // arithmetic type, there exist candidate operator functions of
7182 // the form
7183 //
7184 // VQ L& operator=(VQ L&, R);
7185 // VQ L& operator*=(VQ L&, R);
7186 // VQ L& operator/=(VQ L&, R);
7187 // VQ L& operator+=(VQ L&, R);
7188 // VQ L& operator-=(VQ L&, R);
7189 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007190 if (!HasArithmeticOrEnumeralCandidateType)
7191 return;
7192
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007193 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7194 for (unsigned Right = FirstPromotedArithmeticType;
7195 Right < LastPromotedArithmeticType; ++Right) {
7196 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007197 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007198
7199 // Add this built-in operator as a candidate (VQ is empty).
7200 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007201 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7203 /*IsAssigmentOperator=*/isEqualOp);
7204
7205 // Add this built-in operator as a candidate (VQ is 'volatile').
7206 if (VisibleTypeConversionsQuals.hasVolatile()) {
7207 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007208 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007209 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7211 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007212 /*IsAssigmentOperator=*/isEqualOp);
7213 }
7214 }
7215 }
7216
7217 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7218 for (BuiltinCandidateTypeSet::iterator
7219 Vec1 = CandidateTypes[0].vector_begin(),
7220 Vec1End = CandidateTypes[0].vector_end();
7221 Vec1 != Vec1End; ++Vec1) {
7222 for (BuiltinCandidateTypeSet::iterator
7223 Vec2 = CandidateTypes[1].vector_begin(),
7224 Vec2End = CandidateTypes[1].vector_end();
7225 Vec2 != Vec2End; ++Vec2) {
7226 QualType ParamTypes[2];
7227 ParamTypes[1] = *Vec2;
7228 // Add this built-in operator as a candidate (VQ is empty).
7229 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7231 /*IsAssigmentOperator=*/isEqualOp);
7232
7233 // Add this built-in operator as a candidate (VQ is 'volatile').
7234 if (VisibleTypeConversionsQuals.hasVolatile()) {
7235 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7236 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7238 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007239 /*IsAssigmentOperator=*/isEqualOp);
7240 }
7241 }
7242 }
7243 }
7244
7245 // C++ [over.built]p22:
7246 //
7247 // For every triple (L, VQ, R), where L is an integral type, VQ
7248 // is either volatile or empty, and R is a promoted integral
7249 // type, there exist candidate operator functions of the form
7250 //
7251 // VQ L& operator%=(VQ L&, R);
7252 // VQ L& operator<<=(VQ L&, R);
7253 // VQ L& operator>>=(VQ L&, R);
7254 // VQ L& operator&=(VQ L&, R);
7255 // VQ L& operator^=(VQ L&, R);
7256 // VQ L& operator|=(VQ L&, R);
7257 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007258 if (!HasArithmeticOrEnumeralCandidateType)
7259 return;
7260
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007261 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7262 for (unsigned Right = FirstPromotedIntegralType;
7263 Right < LastPromotedIntegralType; ++Right) {
7264 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007265 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007266
7267 // Add this built-in operator as a candidate (VQ is empty).
7268 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007269 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7271 if (VisibleTypeConversionsQuals.hasVolatile()) {
7272 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007273 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007274 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7275 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7276 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7277 CandidateSet);
7278 }
7279 }
7280 }
7281 }
7282
7283 // C++ [over.operator]p23:
7284 //
7285 // There also exist candidate operator functions of the form
7286 //
7287 // bool operator!(bool);
7288 // bool operator&&(bool, bool);
7289 // bool operator||(bool, bool);
7290 void addExclaimOverload() {
7291 QualType ParamTy = S.Context.BoolTy;
7292 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7293 /*IsAssignmentOperator=*/false,
7294 /*NumContextualBoolArguments=*/1);
7295 }
7296 void addAmpAmpOrPipePipeOverload() {
7297 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7298 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7299 /*IsAssignmentOperator=*/false,
7300 /*NumContextualBoolArguments=*/2);
7301 }
7302
7303 // C++ [over.built]p13:
7304 //
7305 // For every cv-qualified or cv-unqualified object type T there
7306 // exist candidate operator functions of the form
7307 //
7308 // T* operator+(T*, ptrdiff_t); [ABOVE]
7309 // T& operator[](T*, ptrdiff_t);
7310 // T* operator-(T*, ptrdiff_t); [ABOVE]
7311 // T* operator+(ptrdiff_t, T*); [ABOVE]
7312 // T& operator[](ptrdiff_t, T*);
7313 void addSubscriptOverloads() {
7314 for (BuiltinCandidateTypeSet::iterator
7315 Ptr = CandidateTypes[0].pointer_begin(),
7316 PtrEnd = CandidateTypes[0].pointer_end();
7317 Ptr != PtrEnd; ++Ptr) {
7318 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7319 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007320 if (!PointeeType->isObjectType())
7321 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007322
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007323 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7324
7325 // T& operator[](T*, ptrdiff_t)
7326 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7327 }
7328
7329 for (BuiltinCandidateTypeSet::iterator
7330 Ptr = CandidateTypes[1].pointer_begin(),
7331 PtrEnd = CandidateTypes[1].pointer_end();
7332 Ptr != PtrEnd; ++Ptr) {
7333 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7334 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007335 if (!PointeeType->isObjectType())
7336 continue;
7337
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007338 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7339
7340 // T& operator[](ptrdiff_t, T*)
7341 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7342 }
7343 }
7344
7345 // C++ [over.built]p11:
7346 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7347 // C1 is the same type as C2 or is a derived class of C2, T is an object
7348 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7349 // there exist candidate operator functions of the form
7350 //
7351 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7352 //
7353 // where CV12 is the union of CV1 and CV2.
7354 void addArrowStarOverloads() {
7355 for (BuiltinCandidateTypeSet::iterator
7356 Ptr = CandidateTypes[0].pointer_begin(),
7357 PtrEnd = CandidateTypes[0].pointer_end();
7358 Ptr != PtrEnd; ++Ptr) {
7359 QualType C1Ty = (*Ptr);
7360 QualType C1;
7361 QualifierCollector Q1;
7362 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7363 if (!isa<RecordType>(C1))
7364 continue;
7365 // heuristic to reduce number of builtin candidates in the set.
7366 // Add volatile/restrict version only if there are conversions to a
7367 // volatile/restrict type.
7368 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7369 continue;
7370 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7371 continue;
7372 for (BuiltinCandidateTypeSet::iterator
7373 MemPtr = CandidateTypes[1].member_pointer_begin(),
7374 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7375 MemPtr != MemPtrEnd; ++MemPtr) {
7376 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7377 QualType C2 = QualType(mptr->getClass(), 0);
7378 C2 = C2.getUnqualifiedType();
7379 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7380 break;
7381 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7382 // build CV12 T&
7383 QualType T = mptr->getPointeeType();
7384 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7385 T.isVolatileQualified())
7386 continue;
7387 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7388 T.isRestrictQualified())
7389 continue;
7390 T = Q1.apply(S.Context, T);
7391 QualType ResultTy = S.Context.getLValueReferenceType(T);
7392 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7393 }
7394 }
7395 }
7396
7397 // Note that we don't consider the first argument, since it has been
7398 // contextually converted to bool long ago. The candidates below are
7399 // therefore added as binary.
7400 //
7401 // C++ [over.built]p25:
7402 // For every type T, where T is a pointer, pointer-to-member, or scoped
7403 // enumeration type, there exist candidate operator functions of the form
7404 //
7405 // T operator?(bool, T, T);
7406 //
7407 void addConditionalOperatorOverloads() {
7408 /// Set of (canonical) types that we've already handled.
7409 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7410
7411 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7412 for (BuiltinCandidateTypeSet::iterator
7413 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7414 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7415 Ptr != PtrEnd; ++Ptr) {
7416 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7417 continue;
7418
7419 QualType ParamTypes[2] = { *Ptr, *Ptr };
7420 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7421 }
7422
7423 for (BuiltinCandidateTypeSet::iterator
7424 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7425 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7426 MemPtr != MemPtrEnd; ++MemPtr) {
7427 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7428 continue;
7429
7430 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7431 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7432 }
7433
David Blaikie4e4d0842012-03-11 07:00:24 +00007434 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007435 for (BuiltinCandidateTypeSet::iterator
7436 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7437 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7438 Enum != EnumEnd; ++Enum) {
7439 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7440 continue;
7441
7442 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7443 continue;
7444
7445 QualType ParamTypes[2] = { *Enum, *Enum };
7446 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7447 }
7448 }
7449 }
7450 }
7451};
7452
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007453} // end anonymous namespace
7454
7455/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7456/// operator overloads to the candidate set (C++ [over.built]), based
7457/// on the operator @p Op and the arguments given. For example, if the
7458/// operator is a binary '+', this routine might add "int
7459/// operator+(int, int)" to cover integer addition.
7460void
7461Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7462 SourceLocation OpLoc,
7463 Expr **Args, unsigned NumArgs,
7464 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007465 // Find all of the types that the arguments can convert to, but only
7466 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007467 // that make use of these types. Also record whether we encounter non-record
7468 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007469 Qualifiers VisibleTypeConversionsQuals;
7470 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007471 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7472 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007473
7474 bool HasNonRecordCandidateType = false;
7475 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007476 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007477 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7478 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7479 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7480 OpLoc,
7481 true,
7482 (Op == OO_Exclaim ||
7483 Op == OO_AmpAmp ||
7484 Op == OO_PipePipe),
7485 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007486 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7487 CandidateTypes[ArgIdx].hasNonRecordTypes();
7488 HasArithmeticOrEnumeralCandidateType =
7489 HasArithmeticOrEnumeralCandidateType ||
7490 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007491 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007492
Chandler Carruth6a577462010-12-13 01:44:01 +00007493 // Exit early when no non-record types have been added to the candidate set
7494 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007495 //
7496 // We can't exit early for !, ||, or &&, since there we have always have
7497 // 'bool' overloads.
7498 if (!HasNonRecordCandidateType &&
7499 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007500 return;
7501
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007502 // Setup an object to manage the common state for building overloads.
7503 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7504 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007505 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007506 CandidateTypes, CandidateSet);
7507
7508 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007509 switch (Op) {
7510 case OO_None:
7511 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007512 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007513
Chandler Carruthabb71842010-12-12 08:51:33 +00007514 case OO_New:
7515 case OO_Delete:
7516 case OO_Array_New:
7517 case OO_Array_Delete:
7518 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007519 llvm_unreachable(
7520 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007521
7522 case OO_Comma:
7523 case OO_Arrow:
7524 // C++ [over.match.oper]p3:
7525 // -- For the operator ',', the unary operator '&', or the
7526 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007527 break;
7528
7529 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007530 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007531 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007532 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007533
7534 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007535 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007536 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007537 } else {
7538 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7539 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7540 }
Douglas Gregor74253732008-11-19 15:42:04 +00007541 break;
7542
Chandler Carruthabb71842010-12-12 08:51:33 +00007543 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007544 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007545 OpBuilder.addUnaryStarPointerOverloads();
7546 else
7547 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7548 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007549
Chandler Carruthabb71842010-12-12 08:51:33 +00007550 case OO_Slash:
7551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007552 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007553
7554 case OO_PlusPlus:
7555 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007556 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7557 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007558 break;
7559
Douglas Gregor19b7b152009-08-24 13:43:27 +00007560 case OO_EqualEqual:
7561 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007563 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007564
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007565 case OO_Less:
7566 case OO_Greater:
7567 case OO_LessEqual:
7568 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007569 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7571 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007572
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007573 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007574 case OO_Caret:
7575 case OO_Pipe:
7576 case OO_LessLess:
7577 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007578 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007579 break;
7580
Chandler Carruthabb71842010-12-12 08:51:33 +00007581 case OO_Amp: // '&' is either unary or binary
7582 if (NumArgs == 1)
7583 // C++ [over.match.oper]p3:
7584 // -- For the operator ',', the unary operator '&', or the
7585 // operator '->', the built-in candidates set is empty.
7586 break;
7587
7588 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7589 break;
7590
7591 case OO_Tilde:
7592 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7593 break;
7594
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007595 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007596 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007597 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007598
7599 case OO_PlusEqual:
7600 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007601 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007602 // Fall through.
7603
7604 case OO_StarEqual:
7605 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007606 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007607 break;
7608
7609 case OO_PercentEqual:
7610 case OO_LessLessEqual:
7611 case OO_GreaterGreaterEqual:
7612 case OO_AmpEqual:
7613 case OO_CaretEqual:
7614 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007615 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007616 break;
7617
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007618 case OO_Exclaim:
7619 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007620 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007621
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007622 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007623 case OO_PipePipe:
7624 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007625 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007626
7627 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007628 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629 break;
7630
7631 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007633 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007634
7635 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007636 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007637 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7638 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007639 }
7640}
7641
Douglas Gregorfa047642009-02-04 00:32:51 +00007642/// \brief Add function candidates found via argument-dependent lookup
7643/// to the set of overloading candidates.
7644///
7645/// This routine performs argument-dependent name lookup based on the
7646/// given function name (which may also be an operator name) and adds
7647/// all of the overload candidates found by ADL to the overload
7648/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007649void
Douglas Gregorfa047642009-02-04 00:32:51 +00007650Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007651 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007652 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007653 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007654 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007655 bool PartialOverloading,
7656 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007657 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007658
John McCalla113e722010-01-26 06:04:06 +00007659 // FIXME: This approach for uniquing ADL results (and removing
7660 // redundant candidates from the set) relies on pointer-equality,
7661 // which means we need to key off the canonical decl. However,
7662 // always going back to the canonical decl might not get us the
7663 // right set of default arguments. What default arguments are
7664 // we supposed to consider on ADL candidates, anyway?
7665
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007666 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007667 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007668 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007669
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007670 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007671 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7672 CandEnd = CandidateSet.end();
7673 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007674 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007675 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007676 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007677 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007678 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007679
7680 // For each of the ADL candidates we found, add it to the overload
7681 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007682 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007683 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007685 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007686 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007687
Ahmed Charles13a140c2012-02-25 11:00:22 +00007688 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7689 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007690 } else
John McCall6e266892010-01-26 03:27:55 +00007691 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007692 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007693 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007694 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007695}
7696
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007697/// isBetterOverloadCandidate - Determines whether the first overload
7698/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007699bool
John McCall120d63c2010-08-24 20:38:10 +00007700isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007701 const OverloadCandidate &Cand1,
7702 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007703 SourceLocation Loc,
7704 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007705 // Define viable functions to be better candidates than non-viable
7706 // functions.
7707 if (!Cand2.Viable)
7708 return Cand1.Viable;
7709 else if (!Cand1.Viable)
7710 return false;
7711
Douglas Gregor88a35142008-12-22 05:46:06 +00007712 // C++ [over.match.best]p1:
7713 //
7714 // -- if F is a static member function, ICS1(F) is defined such
7715 // that ICS1(F) is neither better nor worse than ICS1(G) for
7716 // any function G, and, symmetrically, ICS1(G) is neither
7717 // better nor worse than ICS1(F).
7718 unsigned StartArg = 0;
7719 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7720 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007721
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007722 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007723 // A viable function F1 is defined to be a better function than another
7724 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007725 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007726 unsigned NumArgs = Cand1.NumConversions;
7727 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007728 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007729 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007730 switch (CompareImplicitConversionSequences(S,
7731 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007732 Cand2.Conversions[ArgIdx])) {
7733 case ImplicitConversionSequence::Better:
7734 // Cand1 has a better conversion sequence.
7735 HasBetterConversion = true;
7736 break;
7737
7738 case ImplicitConversionSequence::Worse:
7739 // Cand1 can't be better than Cand2.
7740 return false;
7741
7742 case ImplicitConversionSequence::Indistinguishable:
7743 // Do nothing.
7744 break;
7745 }
7746 }
7747
Mike Stump1eb44332009-09-09 15:08:12 +00007748 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007749 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007750 if (HasBetterConversion)
7751 return true;
7752
Mike Stump1eb44332009-09-09 15:08:12 +00007753 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007754 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007755 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007756 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7757 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007758
7759 // -- F1 and F2 are function template specializations, and the function
7760 // template for F1 is more specialized than the template for F2
7761 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007762 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007763 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007764 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007765 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007766 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7767 Cand2.Function->getPrimaryTemplate(),
7768 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007769 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007770 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007771 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007772 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007774
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007775 // -- the context is an initialization by user-defined conversion
7776 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7777 // from the return type of F1 to the destination type (i.e.,
7778 // the type of the entity being initialized) is a better
7779 // conversion sequence than the standard conversion sequence
7780 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007781 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007782 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007783 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007784 // First check whether we prefer one of the conversion functions over the
7785 // other. This only distinguishes the results in non-standard, extension
7786 // cases such as the conversion from a lambda closure type to a function
7787 // pointer or block.
7788 ImplicitConversionSequence::CompareKind FuncResult
7789 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7790 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7791 return FuncResult;
7792
John McCall120d63c2010-08-24 20:38:10 +00007793 switch (CompareStandardConversionSequences(S,
7794 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007795 Cand2.FinalConversion)) {
7796 case ImplicitConversionSequence::Better:
7797 // Cand1 has a better conversion sequence.
7798 return true;
7799
7800 case ImplicitConversionSequence::Worse:
7801 // Cand1 can't be better than Cand2.
7802 return false;
7803
7804 case ImplicitConversionSequence::Indistinguishable:
7805 // Do nothing
7806 break;
7807 }
7808 }
7809
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007810 return false;
7811}
7812
Mike Stump1eb44332009-09-09 15:08:12 +00007813/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007814/// within an overload candidate set.
7815///
James Dennettefce31f2012-06-22 08:10:18 +00007816/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007817/// which overload resolution occurs.
7818///
James Dennettefce31f2012-06-22 08:10:18 +00007819/// \param Best If overload resolution was successful or found a deleted
7820/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007821///
7822/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007823OverloadingResult
7824OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007825 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007826 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007827 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007828 Best = end();
7829 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7830 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007831 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007832 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007833 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007834 }
7835
7836 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007837 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007838 return OR_No_Viable_Function;
7839
7840 // Make sure that this function is better than every other viable
7841 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007842 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007843 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007844 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007845 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007846 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007847 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007848 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007849 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007850 }
Mike Stump1eb44332009-09-09 15:08:12 +00007851
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007852 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007853 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007854 (Best->Function->isDeleted() ||
7855 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007856 return OR_Deleted;
7857
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007858 return OR_Success;
7859}
7860
John McCall3c80f572010-01-12 02:15:36 +00007861namespace {
7862
7863enum OverloadCandidateKind {
7864 oc_function,
7865 oc_method,
7866 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007867 oc_function_template,
7868 oc_method_template,
7869 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007870 oc_implicit_default_constructor,
7871 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007872 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007873 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007874 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007875 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007876};
7877
John McCall220ccbf2010-01-13 00:25:19 +00007878OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7879 FunctionDecl *Fn,
7880 std::string &Description) {
7881 bool isTemplate = false;
7882
7883 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7884 isTemplate = true;
7885 Description = S.getTemplateArgumentBindingsText(
7886 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7887 }
John McCallb1622a12010-01-06 09:43:14 +00007888
7889 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007890 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007891 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007892
Sebastian Redlf677ea32011-02-05 19:23:19 +00007893 if (Ctor->getInheritedConstructor())
7894 return oc_implicit_inherited_constructor;
7895
Sean Hunt82713172011-05-25 23:16:36 +00007896 if (Ctor->isDefaultConstructor())
7897 return oc_implicit_default_constructor;
7898
7899 if (Ctor->isMoveConstructor())
7900 return oc_implicit_move_constructor;
7901
7902 assert(Ctor->isCopyConstructor() &&
7903 "unexpected sort of implicit constructor");
7904 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007905 }
7906
7907 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7908 // This actually gets spelled 'candidate function' for now, but
7909 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007910 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007911 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007912
Sean Hunt82713172011-05-25 23:16:36 +00007913 if (Meth->isMoveAssignmentOperator())
7914 return oc_implicit_move_assignment;
7915
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007916 if (Meth->isCopyAssignmentOperator())
7917 return oc_implicit_copy_assignment;
7918
7919 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7920 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007921 }
7922
John McCall220ccbf2010-01-13 00:25:19 +00007923 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007924}
7925
Sebastian Redlf677ea32011-02-05 19:23:19 +00007926void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7927 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7928 if (!Ctor) return;
7929
7930 Ctor = Ctor->getInheritedConstructor();
7931 if (!Ctor) return;
7932
7933 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7934}
7935
John McCall3c80f572010-01-12 02:15:36 +00007936} // end anonymous namespace
7937
7938// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007939void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007940 std::string FnDesc;
7941 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007942 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7943 << (unsigned) K << FnDesc;
7944 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7945 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007946 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007947}
7948
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007949//Notes the location of all overload candidates designated through
7950// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007951void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007952 assert(OverloadedExpr->getType() == Context.OverloadTy);
7953
7954 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7955 OverloadExpr *OvlExpr = Ovl.Expression;
7956
7957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7958 IEnd = OvlExpr->decls_end();
7959 I != IEnd; ++I) {
7960 if (FunctionTemplateDecl *FunTmpl =
7961 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007962 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007963 } else if (FunctionDecl *Fun
7964 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007965 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007966 }
7967 }
7968}
7969
John McCall1d318332010-01-12 00:44:57 +00007970/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7971/// "lead" diagnostic; it will be given two arguments, the source and
7972/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007973void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7974 Sema &S,
7975 SourceLocation CaretLoc,
7976 const PartialDiagnostic &PDiag) const {
7977 S.Diag(CaretLoc, PDiag)
7978 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007979 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007980 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7981 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007982 }
John McCall81201622010-01-08 04:41:39 +00007983}
7984
John McCall1d318332010-01-12 00:44:57 +00007985namespace {
7986
John McCalladbb8f82010-01-13 09:16:55 +00007987void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7988 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7989 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007990 assert(Cand->Function && "for now, candidate must be a function");
7991 FunctionDecl *Fn = Cand->Function;
7992
7993 // There's a conversion slot for the object argument if this is a
7994 // non-constructor method. Note that 'I' corresponds the
7995 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007996 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007997 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007998 if (I == 0)
7999 isObjectArgument = true;
8000 else
8001 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008002 }
8003
John McCall220ccbf2010-01-13 00:25:19 +00008004 std::string FnDesc;
8005 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8006
John McCalladbb8f82010-01-13 09:16:55 +00008007 Expr *FromExpr = Conv.Bad.FromExpr;
8008 QualType FromTy = Conv.Bad.getFromType();
8009 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008010
John McCall5920dbb2010-02-02 02:42:52 +00008011 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008012 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008013 Expr *E = FromExpr->IgnoreParens();
8014 if (isa<UnaryOperator>(E))
8015 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008016 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008017
8018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8019 << (unsigned) FnKind << FnDesc
8020 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8021 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008022 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008023 return;
8024 }
8025
John McCall258b2032010-01-23 08:10:49 +00008026 // Do some hand-waving analysis to see if the non-viability is due
8027 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008028 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8029 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8030 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8031 CToTy = RT->getPointeeType();
8032 else {
8033 // TODO: detect and diagnose the full richness of const mismatches.
8034 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8035 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8036 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8037 }
8038
8039 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8040 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008041 Qualifiers FromQs = CFromTy.getQualifiers();
8042 Qualifiers ToQs = CToTy.getQualifiers();
8043
8044 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8046 << (unsigned) FnKind << FnDesc
8047 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8048 << FromTy
8049 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8050 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008051 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008052 return;
8053 }
8054
John McCallf85e1932011-06-15 23:02:42 +00008055 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008057 << (unsigned) FnKind << FnDesc
8058 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8059 << FromTy
8060 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8061 << (unsigned) isObjectArgument << I+1;
8062 MaybeEmitInheritedConstructorNote(S, Fn);
8063 return;
8064 }
8065
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008066 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8068 << (unsigned) FnKind << FnDesc
8069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8070 << FromTy
8071 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8072 << (unsigned) isObjectArgument << I+1;
8073 MaybeEmitInheritedConstructorNote(S, Fn);
8074 return;
8075 }
8076
John McCall651f3ee2010-01-14 03:28:57 +00008077 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8078 assert(CVR && "unexpected qualifiers mismatch");
8079
8080 if (isObjectArgument) {
8081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8082 << (unsigned) FnKind << FnDesc
8083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8084 << FromTy << (CVR - 1);
8085 } else {
8086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8087 << (unsigned) FnKind << FnDesc
8088 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8089 << FromTy << (CVR - 1) << I+1;
8090 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008091 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008092 return;
8093 }
8094
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008095 // Special diagnostic for failure to convert an initializer list, since
8096 // telling the user that it has type void is not useful.
8097 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8099 << (unsigned) FnKind << FnDesc
8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8101 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8102 MaybeEmitInheritedConstructorNote(S, Fn);
8103 return;
8104 }
8105
John McCall258b2032010-01-23 08:10:49 +00008106 // Diagnose references or pointers to incomplete types differently,
8107 // since it's far from impossible that the incompleteness triggered
8108 // the failure.
8109 QualType TempFromTy = FromTy.getNonReferenceType();
8110 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8111 TempFromTy = PTy->getPointeeType();
8112 if (TempFromTy->isIncompleteType()) {
8113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8114 << (unsigned) FnKind << FnDesc
8115 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8116 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008117 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008118 return;
8119 }
8120
Douglas Gregor85789812010-06-30 23:01:39 +00008121 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008122 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008123 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8124 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8126 FromPtrTy->getPointeeType()) &&
8127 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8128 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008129 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008130 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008131 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008132 }
8133 } else if (const ObjCObjectPointerType *FromPtrTy
8134 = FromTy->getAs<ObjCObjectPointerType>()) {
8135 if (const ObjCObjectPointerType *ToPtrTy
8136 = ToTy->getAs<ObjCObjectPointerType>())
8137 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8138 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8139 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8140 FromPtrTy->getPointeeType()) &&
8141 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008142 BaseToDerivedConversion = 2;
8143 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008144 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8145 !FromTy->isIncompleteType() &&
8146 !ToRefTy->getPointeeType()->isIncompleteType() &&
8147 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8148 BaseToDerivedConversion = 3;
8149 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8150 ToTy.getNonReferenceType().getCanonicalType() ==
8151 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8153 << (unsigned) FnKind << FnDesc
8154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8155 << (unsigned) isObjectArgument << I + 1;
8156 MaybeEmitInheritedConstructorNote(S, Fn);
8157 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008158 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008160
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008161 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008162 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008163 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008164 << (unsigned) FnKind << FnDesc
8165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008166 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008167 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008168 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008169 return;
8170 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008171
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008172 if (isa<ObjCObjectPointerType>(CFromTy) &&
8173 isa<PointerType>(CToTy)) {
8174 Qualifiers FromQs = CFromTy.getQualifiers();
8175 Qualifiers ToQs = CToTy.getQualifiers();
8176 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8178 << (unsigned) FnKind << FnDesc
8179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8180 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8181 MaybeEmitInheritedConstructorNote(S, Fn);
8182 return;
8183 }
8184 }
8185
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008186 // Emit the generic diagnostic and, optionally, add the hints to it.
8187 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8188 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008189 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008190 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8191 << (unsigned) (Cand->Fix.Kind);
8192
8193 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008194 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8195 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008196 FDiag << *HI;
8197 S.Diag(Fn->getLocation(), FDiag);
8198
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008200}
8201
8202void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8203 unsigned NumFormalArgs) {
8204 // TODO: treat calls to a missing default constructor as a special case
8205
8206 FunctionDecl *Fn = Cand->Function;
8207 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8208
8209 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008210
Douglas Gregor439d3c32011-05-05 00:13:13 +00008211 // With invalid overloaded operators, it's possible that we think we
8212 // have an arity mismatch when it fact it looks like we have the
8213 // right number of arguments, because only overloaded operators have
8214 // the weird behavior of overloading member and non-member functions.
8215 // Just don't report anything.
8216 if (Fn->isInvalidDecl() &&
8217 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8218 return;
8219
John McCalladbb8f82010-01-13 09:16:55 +00008220 // at least / at most / exactly
8221 unsigned mode, modeCount;
8222 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008223 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8224 (Cand->FailureKind == ovl_fail_bad_deduction &&
8225 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008226 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008227 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008228 mode = 0; // "at least"
8229 else
8230 mode = 2; // "exactly"
8231 modeCount = MinParams;
8232 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008233 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8234 (Cand->FailureKind == ovl_fail_bad_deduction &&
8235 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008236 if (MinParams != FnTy->getNumArgs())
8237 mode = 1; // "at most"
8238 else
8239 mode = 2; // "exactly"
8240 modeCount = FnTy->getNumArgs();
8241 }
8242
8243 std::string Description;
8244 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8245
Richard Smithf7b80562012-05-11 05:16:41 +00008246 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8249 << Fn->getParamDecl(0) << NumFormalArgs;
8250 else
8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8252 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8253 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008254 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008255}
8256
John McCall342fec42010-02-01 18:53:26 +00008257/// Diagnose a failed template-argument deduction.
8258void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008259 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008260 FunctionDecl *Fn = Cand->Function; // pattern
8261
Douglas Gregora9333192010-05-08 17:41:32 +00008262 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008263 NamedDecl *ParamD;
8264 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8265 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8266 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008267 switch (Cand->DeductionFailure.Result) {
8268 case Sema::TDK_Success:
8269 llvm_unreachable("TDK_success while diagnosing bad deduction");
8270
8271 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008272 assert(ParamD && "no parameter found for incomplete deduction result");
8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8274 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008275 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008276 return;
8277 }
8278
John McCall57e97782010-08-05 09:05:08 +00008279 case Sema::TDK_Underqualified: {
8280 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8281 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8282
8283 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8284
8285 // Param will have been canonicalized, but it should just be a
8286 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008287 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008288 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008289 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008290 assert(S.Context.hasSameType(Param, NonCanonParam));
8291
8292 // Arg has also been canonicalized, but there's nothing we can do
8293 // about that. It also doesn't matter as much, because it won't
8294 // have any template parameters in it (because deduction isn't
8295 // done on dependent types).
8296 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8297
8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8299 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008300 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008301 return;
8302 }
8303
8304 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008305 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008306 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008307 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008308 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008309 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008310 which = 1;
8311 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008312 which = 2;
8313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008314
Douglas Gregora9333192010-05-08 17:41:32 +00008315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008316 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008317 << *Cand->DeductionFailure.getFirstArg()
8318 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008319 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008320 return;
8321 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008322
Douglas Gregorf1a84452010-05-08 19:15:54 +00008323 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008324 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008325 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008326 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008327 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8328 << ParamD->getDeclName();
8329 else {
8330 int index = 0;
8331 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8332 index = TTP->getIndex();
8333 else if (NonTypeTemplateParmDecl *NTTP
8334 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8335 index = NTTP->getIndex();
8336 else
8337 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008338 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008339 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8340 << (index + 1);
8341 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008342 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008343 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008344
Douglas Gregora18592e2010-05-08 18:13:28 +00008345 case Sema::TDK_TooManyArguments:
8346 case Sema::TDK_TooFewArguments:
8347 DiagnoseArityMismatch(S, Cand, NumArgs);
8348 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008349
8350 case Sema::TDK_InstantiationDepth:
8351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008352 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008353 return;
8354
8355 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008356 // Format the template argument list into the argument string.
8357 llvm::SmallString<128> TemplateArgString;
8358 if (TemplateArgumentList *Args =
8359 Cand->DeductionFailure.getTemplateArgumentList()) {
8360 TemplateArgString = " ";
8361 TemplateArgString += S.getTemplateArgumentBindingsText(
8362 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8363 }
8364
Richard Smith4493c0a2012-05-09 05:17:00 +00008365 // If this candidate was disabled by enable_if, say so.
8366 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8367 if (PDiag && PDiag->second.getDiagID() ==
8368 diag::err_typename_nested_not_found_enable_if) {
8369 // FIXME: Use the source range of the condition, and the fully-qualified
8370 // name of the enable_if template. These are both present in PDiag.
8371 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8372 << "'enable_if'" << TemplateArgString;
8373 return;
8374 }
8375
Richard Smithb8590f32012-05-07 09:03:25 +00008376 // Format the SFINAE diagnostic into the argument string.
8377 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8378 // formatted message in another diagnostic.
8379 llvm::SmallString<128> SFINAEArgString;
8380 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008381 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008382 SFINAEArgString = ": ";
8383 R = SourceRange(PDiag->first, PDiag->first);
8384 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8385 }
8386
Douglas Gregorec20f462010-05-08 20:07:26 +00008387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008388 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008389 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008390 return;
8391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008392
John McCall342fec42010-02-01 18:53:26 +00008393 // TODO: diagnose these individually, then kill off
8394 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008395 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008396 case Sema::TDK_FailedOverloadResolution:
8397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008398 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008399 return;
8400 }
8401}
8402
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008403/// CUDA: diagnose an invalid call across targets.
8404void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8405 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8406 FunctionDecl *Callee = Cand->Function;
8407
8408 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8409 CalleeTarget = S.IdentifyCUDATarget(Callee);
8410
8411 std::string FnDesc;
8412 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8413
8414 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8415 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8416}
8417
John McCall342fec42010-02-01 18:53:26 +00008418/// Generates a 'note' diagnostic for an overload candidate. We've
8419/// already generated a primary error at the call site.
8420///
8421/// It really does need to be a single diagnostic with its caret
8422/// pointed at the candidate declaration. Yes, this creates some
8423/// major challenges of technical writing. Yes, this makes pointing
8424/// out problems with specific arguments quite awkward. It's still
8425/// better than generating twenty screens of text for every failed
8426/// overload.
8427///
8428/// It would be great to be able to express per-candidate problems
8429/// more richly for those diagnostic clients that cared, but we'd
8430/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008431void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008432 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008433 FunctionDecl *Fn = Cand->Function;
8434
John McCall81201622010-01-08 04:41:39 +00008435 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008436 if (Cand->Viable && (Fn->isDeleted() ||
8437 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008438 std::string FnDesc;
8439 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008440
8441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008442 << FnKind << FnDesc
8443 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008444 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008445 return;
John McCall81201622010-01-08 04:41:39 +00008446 }
8447
John McCall220ccbf2010-01-13 00:25:19 +00008448 // We don't really have anything else to say about viable candidates.
8449 if (Cand->Viable) {
8450 S.NoteOverloadCandidate(Fn);
8451 return;
8452 }
John McCall1d318332010-01-12 00:44:57 +00008453
John McCalladbb8f82010-01-13 09:16:55 +00008454 switch (Cand->FailureKind) {
8455 case ovl_fail_too_many_arguments:
8456 case ovl_fail_too_few_arguments:
8457 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008458
John McCalladbb8f82010-01-13 09:16:55 +00008459 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008460 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008461
John McCall717e8912010-01-23 05:17:32 +00008462 case ovl_fail_trivial_conversion:
8463 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008464 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008465 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008466
John McCallb1bdc622010-02-25 01:37:24 +00008467 case ovl_fail_bad_conversion: {
8468 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008469 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008470 if (Cand->Conversions[I].isBad())
8471 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008472
John McCalladbb8f82010-01-13 09:16:55 +00008473 // FIXME: this currently happens when we're called from SemaInit
8474 // when user-conversion overload fails. Figure out how to handle
8475 // those conditions and diagnose them well.
8476 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008477 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008478
8479 case ovl_fail_bad_target:
8480 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008481 }
John McCalla1d7d622010-01-08 00:58:21 +00008482}
8483
8484void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8485 // Desugar the type of the surrogate down to a function type,
8486 // retaining as many typedefs as possible while still showing
8487 // the function type (and, therefore, its parameter types).
8488 QualType FnType = Cand->Surrogate->getConversionType();
8489 bool isLValueReference = false;
8490 bool isRValueReference = false;
8491 bool isPointer = false;
8492 if (const LValueReferenceType *FnTypeRef =
8493 FnType->getAs<LValueReferenceType>()) {
8494 FnType = FnTypeRef->getPointeeType();
8495 isLValueReference = true;
8496 } else if (const RValueReferenceType *FnTypeRef =
8497 FnType->getAs<RValueReferenceType>()) {
8498 FnType = FnTypeRef->getPointeeType();
8499 isRValueReference = true;
8500 }
8501 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8502 FnType = FnTypePtr->getPointeeType();
8503 isPointer = true;
8504 }
8505 // Desugar down to a function type.
8506 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8507 // Reconstruct the pointer/reference as appropriate.
8508 if (isPointer) FnType = S.Context.getPointerType(FnType);
8509 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8510 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8511
8512 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8513 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008514 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008515}
8516
8517void NoteBuiltinOperatorCandidate(Sema &S,
8518 const char *Opc,
8519 SourceLocation OpLoc,
8520 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008521 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008522 std::string TypeStr("operator");
8523 TypeStr += Opc;
8524 TypeStr += "(";
8525 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008526 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008527 TypeStr += ")";
8528 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8529 } else {
8530 TypeStr += ", ";
8531 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8532 TypeStr += ")";
8533 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8534 }
8535}
8536
8537void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8538 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008539 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008540 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8541 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008542 if (ICS.isBad()) break; // all meaningless after first invalid
8543 if (!ICS.isAmbiguous()) continue;
8544
John McCall120d63c2010-08-24 20:38:10 +00008545 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008546 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008547 }
8548}
8549
John McCall1b77e732010-01-15 23:32:50 +00008550SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8551 if (Cand->Function)
8552 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008553 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008554 return Cand->Surrogate->getLocation();
8555 return SourceLocation();
8556}
8557
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008558static unsigned
8559RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008560 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008561 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008562 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008563
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008564 case Sema::TDK_Incomplete:
8565 return 1;
8566
8567 case Sema::TDK_Underqualified:
8568 case Sema::TDK_Inconsistent:
8569 return 2;
8570
8571 case Sema::TDK_SubstitutionFailure:
8572 case Sema::TDK_NonDeducedMismatch:
8573 return 3;
8574
8575 case Sema::TDK_InstantiationDepth:
8576 case Sema::TDK_FailedOverloadResolution:
8577 return 4;
8578
8579 case Sema::TDK_InvalidExplicitArguments:
8580 return 5;
8581
8582 case Sema::TDK_TooManyArguments:
8583 case Sema::TDK_TooFewArguments:
8584 return 6;
8585 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008586 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008587}
8588
John McCallbf65c0b2010-01-12 00:48:53 +00008589struct CompareOverloadCandidatesForDisplay {
8590 Sema &S;
8591 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008592
8593 bool operator()(const OverloadCandidate *L,
8594 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008595 // Fast-path this check.
8596 if (L == R) return false;
8597
John McCall81201622010-01-08 04:41:39 +00008598 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008599 if (L->Viable) {
8600 if (!R->Viable) return true;
8601
8602 // TODO: introduce a tri-valued comparison for overload
8603 // candidates. Would be more worthwhile if we had a sort
8604 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008605 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8606 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008607 } else if (R->Viable)
8608 return false;
John McCall81201622010-01-08 04:41:39 +00008609
John McCall1b77e732010-01-15 23:32:50 +00008610 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008611
John McCall1b77e732010-01-15 23:32:50 +00008612 // Criteria by which we can sort non-viable candidates:
8613 if (!L->Viable) {
8614 // 1. Arity mismatches come after other candidates.
8615 if (L->FailureKind == ovl_fail_too_many_arguments ||
8616 L->FailureKind == ovl_fail_too_few_arguments)
8617 return false;
8618 if (R->FailureKind == ovl_fail_too_many_arguments ||
8619 R->FailureKind == ovl_fail_too_few_arguments)
8620 return true;
John McCall81201622010-01-08 04:41:39 +00008621
John McCall717e8912010-01-23 05:17:32 +00008622 // 2. Bad conversions come first and are ordered by the number
8623 // of bad conversions and quality of good conversions.
8624 if (L->FailureKind == ovl_fail_bad_conversion) {
8625 if (R->FailureKind != ovl_fail_bad_conversion)
8626 return true;
8627
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008628 // The conversion that can be fixed with a smaller number of changes,
8629 // comes first.
8630 unsigned numLFixes = L->Fix.NumConversionsFixed;
8631 unsigned numRFixes = R->Fix.NumConversionsFixed;
8632 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8633 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008634 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008635 if (numLFixes < numRFixes)
8636 return true;
8637 else
8638 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008639 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008640
John McCall717e8912010-01-23 05:17:32 +00008641 // If there's any ordering between the defined conversions...
8642 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008643 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008644
8645 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008646 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008647 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008648 switch (CompareImplicitConversionSequences(S,
8649 L->Conversions[I],
8650 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008651 case ImplicitConversionSequence::Better:
8652 leftBetter++;
8653 break;
8654
8655 case ImplicitConversionSequence::Worse:
8656 leftBetter--;
8657 break;
8658
8659 case ImplicitConversionSequence::Indistinguishable:
8660 break;
8661 }
8662 }
8663 if (leftBetter > 0) return true;
8664 if (leftBetter < 0) return false;
8665
8666 } else if (R->FailureKind == ovl_fail_bad_conversion)
8667 return false;
8668
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008669 if (L->FailureKind == ovl_fail_bad_deduction) {
8670 if (R->FailureKind != ovl_fail_bad_deduction)
8671 return true;
8672
8673 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8674 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008675 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008676 } else if (R->FailureKind == ovl_fail_bad_deduction)
8677 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008678
John McCall1b77e732010-01-15 23:32:50 +00008679 // TODO: others?
8680 }
8681
8682 // Sort everything else by location.
8683 SourceLocation LLoc = GetLocationForCandidate(L);
8684 SourceLocation RLoc = GetLocationForCandidate(R);
8685
8686 // Put candidates without locations (e.g. builtins) at the end.
8687 if (LLoc.isInvalid()) return false;
8688 if (RLoc.isInvalid()) return true;
8689
8690 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008691 }
8692};
8693
John McCall717e8912010-01-23 05:17:32 +00008694/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008695/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008696void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008697 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008698 assert(!Cand->Viable);
8699
8700 // Don't do anything on failures other than bad conversion.
8701 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8702
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008703 // We only want the FixIts if all the arguments can be corrected.
8704 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008705 // Use a implicit copy initialization to check conversion fixes.
8706 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008707
John McCall717e8912010-01-23 05:17:32 +00008708 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008709 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008710 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008711 while (true) {
8712 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8713 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008714 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008715 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008716 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008717 }
John McCall717e8912010-01-23 05:17:32 +00008718 }
8719
8720 if (ConvIdx == ConvCount)
8721 return;
8722
John McCallb1bdc622010-02-25 01:37:24 +00008723 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8724 "remaining conversion is initialized?");
8725
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008726 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008727 // operation somehow.
8728 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008729
8730 const FunctionProtoType* Proto;
8731 unsigned ArgIdx = ConvIdx;
8732
8733 if (Cand->IsSurrogate) {
8734 QualType ConvType
8735 = Cand->Surrogate->getConversionType().getNonReferenceType();
8736 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8737 ConvType = ConvPtrType->getPointeeType();
8738 Proto = ConvType->getAs<FunctionProtoType>();
8739 ArgIdx--;
8740 } else if (Cand->Function) {
8741 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8742 if (isa<CXXMethodDecl>(Cand->Function) &&
8743 !isa<CXXConstructorDecl>(Cand->Function))
8744 ArgIdx--;
8745 } else {
8746 // Builtin binary operator with a bad first conversion.
8747 assert(ConvCount <= 3);
8748 for (; ConvIdx != ConvCount; ++ConvIdx)
8749 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008750 = TryCopyInitialization(S, Args[ConvIdx],
8751 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008752 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008753 /*InOverloadResolution*/ true,
8754 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008755 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008756 return;
8757 }
8758
8759 // Fill in the rest of the conversions.
8760 unsigned NumArgsInProto = Proto->getNumArgs();
8761 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008762 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008763 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008764 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008765 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008766 /*InOverloadResolution=*/true,
8767 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008768 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008769 // Store the FixIt in the candidate if it exists.
8770 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008771 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008772 }
John McCall717e8912010-01-23 05:17:32 +00008773 else
8774 Cand->Conversions[ConvIdx].setEllipsis();
8775 }
8776}
8777
John McCalla1d7d622010-01-08 00:58:21 +00008778} // end anonymous namespace
8779
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008780/// PrintOverloadCandidates - When overload resolution fails, prints
8781/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008782/// set.
John McCall120d63c2010-08-24 20:38:10 +00008783void OverloadCandidateSet::NoteCandidates(Sema &S,
8784 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008785 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008786 const char *Opc,
8787 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008788 // Sort the candidates by viability and position. Sorting directly would
8789 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008790 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008791 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8792 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008793 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008794 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008795 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008796 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008797 if (Cand->Function || Cand->IsSurrogate)
8798 Cands.push_back(Cand);
8799 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8800 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008801 }
8802 }
8803
John McCallbf65c0b2010-01-12 00:48:53 +00008804 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008805 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008806
John McCall1d318332010-01-12 00:44:57 +00008807 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008808
Chris Lattner5f9e2722011-07-23 10:55:15 +00008809 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008810 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8811 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008812 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008813 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8814 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008815
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008816 // Set an arbitrary limit on the number of candidate functions we'll spam
8817 // the user with. FIXME: This limit should depend on details of the
8818 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008819 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008820 break;
8821 }
8822 ++CandsShown;
8823
John McCalla1d7d622010-01-08 00:58:21 +00008824 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008825 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008826 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008827 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008828 else {
8829 assert(Cand->Viable &&
8830 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008831 // Generally we only see ambiguities including viable builtin
8832 // operators if overload resolution got screwed up by an
8833 // ambiguous user-defined conversion.
8834 //
8835 // FIXME: It's quite possible for different conversions to see
8836 // different ambiguities, though.
8837 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008838 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008839 ReportedAmbiguousConversions = true;
8840 }
John McCalla1d7d622010-01-08 00:58:21 +00008841
John McCall1d318332010-01-12 00:44:57 +00008842 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008843 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008844 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008845 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008846
8847 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008848 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008849}
8850
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008851// [PossiblyAFunctionType] --> [Return]
8852// NonFunctionType --> NonFunctionType
8853// R (A) --> R(A)
8854// R (*)(A) --> R (A)
8855// R (&)(A) --> R (A)
8856// R (S::*)(A) --> R (A)
8857QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8858 QualType Ret = PossiblyAFunctionType;
8859 if (const PointerType *ToTypePtr =
8860 PossiblyAFunctionType->getAs<PointerType>())
8861 Ret = ToTypePtr->getPointeeType();
8862 else if (const ReferenceType *ToTypeRef =
8863 PossiblyAFunctionType->getAs<ReferenceType>())
8864 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008865 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008866 PossiblyAFunctionType->getAs<MemberPointerType>())
8867 Ret = MemTypePtr->getPointeeType();
8868 Ret =
8869 Context.getCanonicalType(Ret).getUnqualifiedType();
8870 return Ret;
8871}
Douglas Gregor904eed32008-11-10 20:40:00 +00008872
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008873// A helper class to help with address of function resolution
8874// - allows us to avoid passing around all those ugly parameters
8875class AddressOfFunctionResolver
8876{
8877 Sema& S;
8878 Expr* SourceExpr;
8879 const QualType& TargetType;
8880 QualType TargetFunctionType; // Extracted function type from target type
8881
8882 bool Complain;
8883 //DeclAccessPair& ResultFunctionAccessPair;
8884 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008885
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008886 bool TargetTypeIsNonStaticMemberFunction;
8887 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008888
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008889 OverloadExpr::FindResult OvlExprInfo;
8890 OverloadExpr *OvlExpr;
8891 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008892 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008893
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008894public:
8895 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8896 const QualType& TargetType, bool Complain)
8897 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8898 Complain(Complain), Context(S.getASTContext()),
8899 TargetTypeIsNonStaticMemberFunction(
8900 !!TargetType->getAs<MemberPointerType>()),
8901 FoundNonTemplateFunction(false),
8902 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8903 OvlExpr(OvlExprInfo.Expression)
8904 {
8905 ExtractUnqualifiedFunctionTypeFromTargetType();
8906
8907 if (!TargetFunctionType->isFunctionType()) {
8908 if (OvlExpr->hasExplicitTemplateArgs()) {
8909 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008910 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008911 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008912
8913 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8914 if (!Method->isStatic()) {
8915 // If the target type is a non-function type and the function
8916 // found is a non-static member function, pretend as if that was
8917 // the target, it's the only possible type to end up with.
8918 TargetTypeIsNonStaticMemberFunction = true;
8919
8920 // And skip adding the function if its not in the proper form.
8921 // We'll diagnose this due to an empty set of functions.
8922 if (!OvlExprInfo.HasFormOfMemberPointer)
8923 return;
8924 }
8925 }
8926
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008927 Matches.push_back(std::make_pair(dap,Fn));
8928 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008929 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008930 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008931 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008932
8933 if (OvlExpr->hasExplicitTemplateArgs())
8934 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008935
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008936 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8937 // C++ [over.over]p4:
8938 // If more than one function is selected, [...]
8939 if (Matches.size() > 1) {
8940 if (FoundNonTemplateFunction)
8941 EliminateAllTemplateMatches();
8942 else
8943 EliminateAllExceptMostSpecializedTemplate();
8944 }
8945 }
8946 }
8947
8948private:
8949 bool isTargetTypeAFunction() const {
8950 return TargetFunctionType->isFunctionType();
8951 }
8952
8953 // [ToType] [Return]
8954
8955 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8956 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8957 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8958 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8959 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8960 }
8961
8962 // return true if any matching specializations were found
8963 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8964 const DeclAccessPair& CurAccessFunPair) {
8965 if (CXXMethodDecl *Method
8966 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8967 // Skip non-static function templates when converting to pointer, and
8968 // static when converting to member pointer.
8969 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8970 return false;
8971 }
8972 else if (TargetTypeIsNonStaticMemberFunction)
8973 return false;
8974
8975 // C++ [over.over]p2:
8976 // If the name is a function template, template argument deduction is
8977 // done (14.8.2.2), and if the argument deduction succeeds, the
8978 // resulting template argument list is used to generate a single
8979 // function template specialization, which is added to the set of
8980 // overloaded functions considered.
8981 FunctionDecl *Specialization = 0;
8982 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8983 if (Sema::TemplateDeductionResult Result
8984 = S.DeduceTemplateArguments(FunctionTemplate,
8985 &OvlExplicitTemplateArgs,
8986 TargetFunctionType, Specialization,
8987 Info)) {
8988 // FIXME: make a note of the failed deduction for diagnostics.
8989 (void)Result;
8990 return false;
8991 }
8992
8993 // Template argument deduction ensures that we have an exact match.
8994 // This function template specicalization works.
8995 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8996 assert(TargetFunctionType
8997 == Context.getCanonicalType(Specialization->getType()));
8998 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8999 return true;
9000 }
9001
9002 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9003 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009004 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009005 // Skip non-static functions when converting to pointer, and static
9006 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009007 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9008 return false;
9009 }
9010 else if (TargetTypeIsNonStaticMemberFunction)
9011 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009012
Chandler Carruthbd647292009-12-29 06:17:27 +00009013 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009014 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009015 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9016 if (S.CheckCUDATarget(Caller, FunDecl))
9017 return false;
9018
Douglas Gregor43c79c22009-12-09 00:47:37 +00009019 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009020 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9021 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009022 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9023 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009024 Matches.push_back(std::make_pair(CurAccessFunPair,
9025 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009026 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009027 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009028 }
Mike Stump1eb44332009-09-09 15:08:12 +00009029 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009030
9031 return false;
9032 }
9033
9034 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9035 bool Ret = false;
9036
9037 // If the overload expression doesn't have the form of a pointer to
9038 // member, don't try to convert it to a pointer-to-member type.
9039 if (IsInvalidFormOfPointerToMemberFunction())
9040 return false;
9041
9042 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9043 E = OvlExpr->decls_end();
9044 I != E; ++I) {
9045 // Look through any using declarations to find the underlying function.
9046 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9047
9048 // C++ [over.over]p3:
9049 // Non-member functions and static member functions match
9050 // targets of type "pointer-to-function" or "reference-to-function."
9051 // Nonstatic member functions match targets of
9052 // type "pointer-to-member-function."
9053 // Note that according to DR 247, the containing class does not matter.
9054 if (FunctionTemplateDecl *FunctionTemplate
9055 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9056 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9057 Ret = true;
9058 }
9059 // If we have explicit template arguments supplied, skip non-templates.
9060 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9061 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9062 Ret = true;
9063 }
9064 assert(Ret || Matches.empty());
9065 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009066 }
9067
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009068 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009069 // [...] and any given function template specialization F1 is
9070 // eliminated if the set contains a second function template
9071 // specialization whose function template is more specialized
9072 // than the function template of F1 according to the partial
9073 // ordering rules of 14.5.5.2.
9074
9075 // The algorithm specified above is quadratic. We instead use a
9076 // two-pass algorithm (similar to the one used to identify the
9077 // best viable function in an overload set) that identifies the
9078 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009079
9080 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9081 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9082 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009083
John McCallc373d482010-01-27 01:50:18 +00009084 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009085 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9086 TPOC_Other, 0, SourceExpr->getLocStart(),
9087 S.PDiag(),
9088 S.PDiag(diag::err_addr_ovl_ambiguous)
9089 << Matches[0].second->getDeclName(),
9090 S.PDiag(diag::note_ovl_candidate)
9091 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009092 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009093
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009094 if (Result != MatchesCopy.end()) {
9095 // Make it the first and only element
9096 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9097 Matches[0].second = cast<FunctionDecl>(*Result);
9098 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009099 }
9100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009101
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009102 void EliminateAllTemplateMatches() {
9103 // [...] any function template specializations in the set are
9104 // eliminated if the set also contains a non-template function, [...]
9105 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9106 if (Matches[I].second->getPrimaryTemplate() == 0)
9107 ++I;
9108 else {
9109 Matches[I] = Matches[--N];
9110 Matches.set_size(N);
9111 }
9112 }
9113 }
9114
9115public:
9116 void ComplainNoMatchesFound() const {
9117 assert(Matches.empty());
9118 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9119 << OvlExpr->getName() << TargetFunctionType
9120 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009121 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009122 }
9123
9124 bool IsInvalidFormOfPointerToMemberFunction() const {
9125 return TargetTypeIsNonStaticMemberFunction &&
9126 !OvlExprInfo.HasFormOfMemberPointer;
9127 }
9128
9129 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9130 // TODO: Should we condition this on whether any functions might
9131 // have matched, or is it more appropriate to do that in callers?
9132 // TODO: a fixit wouldn't hurt.
9133 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9134 << TargetType << OvlExpr->getSourceRange();
9135 }
9136
9137 void ComplainOfInvalidConversion() const {
9138 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9139 << OvlExpr->getName() << TargetType;
9140 }
9141
9142 void ComplainMultipleMatchesFound() const {
9143 assert(Matches.size() > 1);
9144 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9145 << OvlExpr->getName()
9146 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009147 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009148 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009149
9150 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9151
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009152 int getNumMatches() const { return Matches.size(); }
9153
9154 FunctionDecl* getMatchingFunctionDecl() const {
9155 if (Matches.size() != 1) return 0;
9156 return Matches[0].second;
9157 }
9158
9159 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9160 if (Matches.size() != 1) return 0;
9161 return &Matches[0].first;
9162 }
9163};
9164
9165/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9166/// an overloaded function (C++ [over.over]), where @p From is an
9167/// expression with overloaded function type and @p ToType is the type
9168/// we're trying to resolve to. For example:
9169///
9170/// @code
9171/// int f(double);
9172/// int f(int);
9173///
9174/// int (*pfd)(double) = f; // selects f(double)
9175/// @endcode
9176///
9177/// This routine returns the resulting FunctionDecl if it could be
9178/// resolved, and NULL otherwise. When @p Complain is true, this
9179/// routine will emit diagnostics if there is an error.
9180FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009181Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9182 QualType TargetType,
9183 bool Complain,
9184 DeclAccessPair &FoundResult,
9185 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009186 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009187
9188 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9189 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009190 int NumMatches = Resolver.getNumMatches();
9191 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009192 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009193 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9194 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9195 else
9196 Resolver.ComplainNoMatchesFound();
9197 }
9198 else if (NumMatches > 1 && Complain)
9199 Resolver.ComplainMultipleMatchesFound();
9200 else if (NumMatches == 1) {
9201 Fn = Resolver.getMatchingFunctionDecl();
9202 assert(Fn);
9203 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009204 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009205 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009206 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009207 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009208
9209 if (pHadMultipleCandidates)
9210 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009211 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009212}
9213
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009214/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009215/// resolve that overloaded function expression down to a single function.
9216///
9217/// This routine can only resolve template-ids that refer to a single function
9218/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009219/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009220/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009221FunctionDecl *
9222Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9223 bool Complain,
9224 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009225 // C++ [over.over]p1:
9226 // [...] [Note: any redundant set of parentheses surrounding the
9227 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009228 // C++ [over.over]p1:
9229 // [...] The overloaded function name can be preceded by the &
9230 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009231
Douglas Gregor4b52e252009-12-21 23:17:24 +00009232 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009233 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009234 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009235
9236 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009237 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009238
Douglas Gregor4b52e252009-12-21 23:17:24 +00009239 // Look through all of the overloaded functions, searching for one
9240 // whose type matches exactly.
9241 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009242 for (UnresolvedSetIterator I = ovl->decls_begin(),
9243 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009244 // C++0x [temp.arg.explicit]p3:
9245 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009246 // where deduction is not done, if a template argument list is
9247 // specified and it, along with any default template arguments,
9248 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009249 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009250 FunctionTemplateDecl *FunctionTemplate
9251 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009252
Douglas Gregor4b52e252009-12-21 23:17:24 +00009253 // C++ [over.over]p2:
9254 // If the name is a function template, template argument deduction is
9255 // done (14.8.2.2), and if the argument deduction succeeds, the
9256 // resulting template argument list is used to generate a single
9257 // function template specialization, which is added to the set of
9258 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009259 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009260 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009261 if (TemplateDeductionResult Result
9262 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9263 Specialization, Info)) {
9264 // FIXME: make a note of the failed deduction for diagnostics.
9265 (void)Result;
9266 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009267 }
9268
John McCall864c0412011-04-26 20:42:42 +00009269 assert(Specialization && "no specialization and no error?");
9270
Douglas Gregor4b52e252009-12-21 23:17:24 +00009271 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009272 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009273 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9275 << ovl->getName();
9276 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009277 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009278 return 0;
John McCall864c0412011-04-26 20:42:42 +00009279 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009280
John McCall864c0412011-04-26 20:42:42 +00009281 Matched = Specialization;
9282 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009283 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009284
Douglas Gregor4b52e252009-12-21 23:17:24 +00009285 return Matched;
9286}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009287
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009288
9289
9290
John McCall6dbba4f2011-10-11 23:14:30 +00009291// Resolve and fix an overloaded expression that can be resolved
9292// because it identifies a single function template specialization.
9293//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009294// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009295//
9296// Return true if it was logically possible to so resolve the
9297// expression, regardless of whether or not it succeeded. Always
9298// returns true if 'complain' is set.
9299bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9300 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9301 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009302 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009303 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009304 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009305
John McCall6dbba4f2011-10-11 23:14:30 +00009306 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009307
John McCall864c0412011-04-26 20:42:42 +00009308 DeclAccessPair found;
9309 ExprResult SingleFunctionExpression;
9310 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9311 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009312 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009313 SrcExpr = ExprError();
9314 return true;
9315 }
John McCall864c0412011-04-26 20:42:42 +00009316
9317 // It is only correct to resolve to an instance method if we're
9318 // resolving a form that's permitted to be a pointer to member.
9319 // Otherwise we'll end up making a bound member expression, which
9320 // is illegal in all the contexts we resolve like this.
9321 if (!ovl.HasFormOfMemberPointer &&
9322 isa<CXXMethodDecl>(fn) &&
9323 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009324 if (!complain) return false;
9325
9326 Diag(ovl.Expression->getExprLoc(),
9327 diag::err_bound_member_function)
9328 << 0 << ovl.Expression->getSourceRange();
9329
9330 // TODO: I believe we only end up here if there's a mix of
9331 // static and non-static candidates (otherwise the expression
9332 // would have 'bound member' type, not 'overload' type).
9333 // Ideally we would note which candidate was chosen and why
9334 // the static candidates were rejected.
9335 SrcExpr = ExprError();
9336 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009337 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009338
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009339 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009340 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009341 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009342
9343 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009344 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009345 SingleFunctionExpression =
9346 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009347 if (SingleFunctionExpression.isInvalid()) {
9348 SrcExpr = ExprError();
9349 return true;
9350 }
9351 }
John McCall864c0412011-04-26 20:42:42 +00009352 }
9353
9354 if (!SingleFunctionExpression.isUsable()) {
9355 if (complain) {
9356 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9357 << ovl.Expression->getName()
9358 << DestTypeForComplaining
9359 << OpRangeForComplaining
9360 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009361 NoteAllOverloadCandidates(SrcExpr.get());
9362
9363 SrcExpr = ExprError();
9364 return true;
9365 }
9366
9367 return false;
John McCall864c0412011-04-26 20:42:42 +00009368 }
9369
John McCall6dbba4f2011-10-11 23:14:30 +00009370 SrcExpr = SingleFunctionExpression;
9371 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009372}
9373
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009374/// \brief Add a single candidate to the overload set.
9375static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009376 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009377 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009378 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009379 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009380 bool PartialOverloading,
9381 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009382 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009383 if (isa<UsingShadowDecl>(Callee))
9384 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9385
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009386 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009387 if (ExplicitTemplateArgs) {
9388 assert(!KnownValid && "Explicit template arguments?");
9389 return;
9390 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009391 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9392 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009393 return;
John McCallba135432009-11-21 08:51:07 +00009394 }
9395
9396 if (FunctionTemplateDecl *FuncTemplate
9397 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009398 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009399 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009400 return;
9401 }
9402
Richard Smith2ced0442011-06-26 22:19:54 +00009403 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009404}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009405
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009406/// \brief Add the overload candidates named by callee and/or found by argument
9407/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009408void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009409 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009410 OverloadCandidateSet &CandidateSet,
9411 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009412
9413#ifndef NDEBUG
9414 // Verify that ArgumentDependentLookup is consistent with the rules
9415 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009416 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009417 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9418 // and let Y be the lookup set produced by argument dependent
9419 // lookup (defined as follows). If X contains
9420 //
9421 // -- a declaration of a class member, or
9422 //
9423 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009424 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009425 //
9426 // -- a declaration that is neither a function or a function
9427 // template
9428 //
9429 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009430
John McCall3b4294e2009-12-16 12:17:52 +00009431 if (ULE->requiresADL()) {
9432 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9433 E = ULE->decls_end(); I != E; ++I) {
9434 assert(!(*I)->getDeclContext()->isRecord());
9435 assert(isa<UsingShadowDecl>(*I) ||
9436 !(*I)->getDeclContext()->isFunctionOrMethod());
9437 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009438 }
9439 }
9440#endif
9441
John McCall3b4294e2009-12-16 12:17:52 +00009442 // It would be nice to avoid this copy.
9443 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009444 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009445 if (ULE->hasExplicitTemplateArgs()) {
9446 ULE->copyTemplateArgumentsInto(TABuffer);
9447 ExplicitTemplateArgs = &TABuffer;
9448 }
9449
9450 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9451 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009452 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9453 CandidateSet, PartialOverloading,
9454 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009455
John McCall3b4294e2009-12-16 12:17:52 +00009456 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009457 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009458 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009459 Args, ExplicitTemplateArgs,
9460 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009461 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009462}
John McCall578b69b2009-12-16 08:11:27 +00009463
Richard Smithf50e88a2011-06-05 22:42:48 +00009464/// Attempt to recover from an ill-formed use of a non-dependent name in a
9465/// template, where the non-dependent name was declared after the template
9466/// was defined. This is common in code written for a compilers which do not
9467/// correctly implement two-stage name lookup.
9468///
9469/// Returns true if a viable candidate was found and a diagnostic was issued.
9470static bool
9471DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9472 const CXXScopeSpec &SS, LookupResult &R,
9473 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009474 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009475 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9476 return false;
9477
9478 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009479 if (DC->isTransparentContext())
9480 continue;
9481
Richard Smithf50e88a2011-06-05 22:42:48 +00009482 SemaRef.LookupQualifiedName(R, DC);
9483
9484 if (!R.empty()) {
9485 R.suppressDiagnostics();
9486
9487 if (isa<CXXRecordDecl>(DC)) {
9488 // Don't diagnose names we find in classes; we get much better
9489 // diagnostics for these from DiagnoseEmptyLookup.
9490 R.clear();
9491 return false;
9492 }
9493
9494 OverloadCandidateSet Candidates(FnLoc);
9495 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9496 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009497 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009498 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009499
9500 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009501 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009502 // No viable functions. Don't bother the user with notes for functions
9503 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009504 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009505 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009506 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009507
9508 // Find the namespaces where ADL would have looked, and suggest
9509 // declaring the function there instead.
9510 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9511 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009512 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009513 AssociatedNamespaces,
9514 AssociatedClasses);
9515 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009516 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009517 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009518 for (Sema::AssociatedNamespaceSet::iterator
9519 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009520 end = AssociatedNamespaces.end(); it != end; ++it) {
9521 if (!Std->Encloses(*it))
9522 SuggestedNamespaces.insert(*it);
9523 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009524 } else {
9525 // Lacking the 'std::' namespace, use all of the associated namespaces.
9526 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009527 }
9528
9529 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9530 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009531 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009532 SemaRef.Diag(Best->Function->getLocation(),
9533 diag::note_not_found_by_two_phase_lookup)
9534 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009535 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009536 SemaRef.Diag(Best->Function->getLocation(),
9537 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009538 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009539 } else {
9540 // FIXME: It would be useful to list the associated namespaces here,
9541 // but the diagnostics infrastructure doesn't provide a way to produce
9542 // a localized representation of a list of items.
9543 SemaRef.Diag(Best->Function->getLocation(),
9544 diag::note_not_found_by_two_phase_lookup)
9545 << R.getLookupName() << 2;
9546 }
9547
9548 // Try to recover by calling this function.
9549 return true;
9550 }
9551
9552 R.clear();
9553 }
9554
9555 return false;
9556}
9557
9558/// Attempt to recover from ill-formed use of a non-dependent operator in a
9559/// template, where the non-dependent operator was declared after the template
9560/// was defined.
9561///
9562/// Returns true if a viable candidate was found and a diagnostic was issued.
9563static bool
9564DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9565 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009566 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009567 DeclarationName OpName =
9568 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9569 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9570 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009571 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009572}
9573
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009574namespace {
9575// Callback to limit the allowed keywords and to only accept typo corrections
9576// that are keywords or whose decls refer to functions (or template functions)
9577// that accept the given number of arguments.
9578class RecoveryCallCCC : public CorrectionCandidateCallback {
9579 public:
9580 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9581 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009582 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009583 WantRemainingKeywords = false;
9584 }
9585
9586 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9587 if (!candidate.getCorrectionDecl())
9588 return candidate.isKeyword();
9589
9590 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9591 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9592 FunctionDecl *FD = 0;
9593 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9594 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9595 FD = FTD->getTemplatedDecl();
9596 if (!HasExplicitTemplateArgs && !FD) {
9597 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9598 // If the Decl is neither a function nor a template function,
9599 // determine if it is a pointer or reference to a function. If so,
9600 // check against the number of arguments expected for the pointee.
9601 QualType ValType = cast<ValueDecl>(ND)->getType();
9602 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9603 ValType = ValType->getPointeeType();
9604 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9605 if (FPT->getNumArgs() == NumArgs)
9606 return true;
9607 }
9608 }
9609 if (FD && FD->getNumParams() >= NumArgs &&
9610 FD->getMinRequiredArguments() <= NumArgs)
9611 return true;
9612 }
9613 return false;
9614 }
9615
9616 private:
9617 unsigned NumArgs;
9618 bool HasExplicitTemplateArgs;
9619};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009620
9621// Callback that effectively disabled typo correction
9622class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9623 public:
9624 NoTypoCorrectionCCC() {
9625 WantTypeSpecifiers = false;
9626 WantExpressionKeywords = false;
9627 WantCXXNamedCasts = false;
9628 WantRemainingKeywords = false;
9629 }
9630
9631 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9632 return false;
9633 }
9634};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009635}
9636
John McCall578b69b2009-12-16 08:11:27 +00009637/// Attempts to recover from a call where no functions were found.
9638///
9639/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009640static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009641BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009642 UnresolvedLookupExpr *ULE,
9643 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009644 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009645 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009646 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009647
9648 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009649 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009650 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009651
John McCall3b4294e2009-12-16 12:17:52 +00009652 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009653 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009654 if (ULE->hasExplicitTemplateArgs()) {
9655 ULE->copyTemplateArgumentsInto(TABuffer);
9656 ExplicitTemplateArgs = &TABuffer;
9657 }
9658
John McCall578b69b2009-12-16 08:11:27 +00009659 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9660 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009661 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009662 NoTypoCorrectionCCC RejectAll;
9663 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9664 (CorrectionCandidateCallback*)&Validator :
9665 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009666 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009667 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009668 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009669 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009670 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009671 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009672
John McCall3b4294e2009-12-16 12:17:52 +00009673 assert(!R.empty() && "lookup results empty despite recovery");
9674
9675 // Build an implicit member call if appropriate. Just drop the
9676 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009677 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009678 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009679 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9680 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009681 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009682 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009683 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009684 else
9685 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9686
9687 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009688 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009689
9690 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009691 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009692 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009693 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009694 MultiExprArg(Args.data(), Args.size()),
9695 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009696}
Douglas Gregord7a95972010-06-08 17:35:15 +00009697
Douglas Gregorf6b89692008-11-26 05:54:23 +00009698/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009699/// (which eventually refers to the declaration Func) and the call
9700/// arguments Args/NumArgs, attempt to resolve the function call down
9701/// to a specific function. If overload resolution succeeds, returns
9702/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009703/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009704/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009705ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009706Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009707 SourceLocation LParenLoc,
9708 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009709 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009710 Expr *ExecConfig,
9711 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009712#ifndef NDEBUG
9713 if (ULE->requiresADL()) {
9714 // To do ADL, we must have found an unqualified name.
9715 assert(!ULE->getQualifier() && "qualified name with ADL");
9716
9717 // We don't perform ADL for implicit declarations of builtins.
9718 // Verify that this was correctly set up.
9719 FunctionDecl *F;
9720 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9721 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9722 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009723 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009724
John McCall3b4294e2009-12-16 12:17:52 +00009725 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009726 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009727 } else
9728 assert(!ULE->isStdAssociatedNamespace() &&
9729 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009730#endif
9731
John McCall5acb0c92011-10-17 18:40:02 +00009732 UnbridgedCastsSet UnbridgedCasts;
9733 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9734 return ExprError();
9735
John McCall5769d612010-02-08 23:07:23 +00009736 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009737
John McCall3b4294e2009-12-16 12:17:52 +00009738 // Add the functions denoted by the callee to the set of candidate
9739 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009740 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9741 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009742
9743 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009744 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9745 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009746 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009747 // In Microsoft mode, if we are inside a template class member function then
9748 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009749 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009750 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009751 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009752 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009753 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9754 Context.DependentTy, VK_RValue,
9755 RParenLoc);
9756 CE->setTypeDependent(true);
9757 return Owned(CE);
9758 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009759 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9760 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009761 RParenLoc, /*EmptyLookup=*/true,
9762 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009763 }
John McCall578b69b2009-12-16 08:11:27 +00009764
John McCall5acb0c92011-10-17 18:40:02 +00009765 UnbridgedCasts.restore();
9766
Douglas Gregorf6b89692008-11-26 05:54:23 +00009767 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009768 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009769 case OR_Success: {
9770 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009771 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009772 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009773 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009774 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009775 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9776 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009777 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009778
Richard Smithf50e88a2011-06-05 22:42:48 +00009779 case OR_No_Viable_Function: {
9780 // Try to recover by looking for viable functions which the user might
9781 // have meant to call.
9782 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009783 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9784 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009785 /*EmptyLookup=*/false,
9786 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009787 if (!Recovery.isInvalid())
9788 return Recovery;
9789
Daniel Dunbar96a00142012-03-09 18:35:03 +00009790 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009791 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009792 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009793 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9794 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009795 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009796 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009797
9798 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009799 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009800 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009801 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9802 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009803 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009804
9805 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009806 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009807 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009808 << Best->Function->isDeleted()
9809 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009810 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009811 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009812 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9813 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009814
9815 // We emitted an error for the unvailable/deleted function call but keep
9816 // the call in the AST.
9817 FunctionDecl *FDecl = Best->Function;
9818 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9819 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9820 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009821 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009822 }
9823
Douglas Gregorff331c12010-07-25 18:17:45 +00009824 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009825 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009826}
9827
John McCall6e266892010-01-26 03:27:55 +00009828static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009829 return Functions.size() > 1 ||
9830 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9831}
9832
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009833/// \brief Create a unary operation that may resolve to an overloaded
9834/// operator.
9835///
9836/// \param OpLoc The location of the operator itself (e.g., '*').
9837///
9838/// \param OpcIn The UnaryOperator::Opcode that describes this
9839/// operator.
9840///
James Dennett40ae6662012-06-22 08:52:37 +00009841/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009842/// considered by overload resolution. The caller needs to build this
9843/// set based on the context using, e.g.,
9844/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9845/// set should not contain any member functions; those will be added
9846/// by CreateOverloadedUnaryOp().
9847///
James Dennett8da16872012-06-22 10:32:46 +00009848/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009849ExprResult
John McCall6e266892010-01-26 03:27:55 +00009850Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9851 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009852 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009853 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009854
9855 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9856 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9857 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009858 // TODO: provide better source location info.
9859 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009860
John McCall5acb0c92011-10-17 18:40:02 +00009861 if (checkPlaceholderForOverload(*this, Input))
9862 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009863
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009864 Expr *Args[2] = { Input, 0 };
9865 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009866
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009867 // For post-increment and post-decrement, add the implicit '0' as
9868 // the second argument, so that we know this is a post-increment or
9869 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009870 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009871 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009872 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9873 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009874 NumArgs = 2;
9875 }
9876
9877 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009878 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009879 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009880 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009881 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009882 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009883 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009884
John McCallc373d482010-01-27 01:50:18 +00009885 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009886 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009887 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009888 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009889 /*ADL*/ true, IsOverloaded(Fns),
9890 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009891 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009892 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009893 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009894 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009895 OpLoc));
9896 }
9897
9898 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009899 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009900
9901 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009902 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9903 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009904
9905 // Add operator candidates that are member functions.
9906 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9907
John McCall6e266892010-01-26 03:27:55 +00009908 // Add candidates from ADL.
9909 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009910 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009911 /*ExplicitTemplateArgs*/ 0,
9912 CandidateSet);
9913
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009914 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009915 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009916
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009917 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9918
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009919 // Perform overload resolution.
9920 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009921 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009922 case OR_Success: {
9923 // We found a built-in operator or an overloaded operator.
9924 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009925
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009926 if (FnDecl) {
9927 // We matched an overloaded operator. Build a call to that
9928 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009929
Eli Friedman5f2987c2012-02-02 03:46:19 +00009930 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009931
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009932 // Convert the arguments.
9933 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009934 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009935
John Wiegley429bb272011-04-08 18:41:53 +00009936 ExprResult InputRes =
9937 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9938 Best->FoundDecl, Method);
9939 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009940 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009941 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009942 } else {
9943 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009944 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009945 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009946 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009947 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009948 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009949 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009950 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009951 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009952 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009953 }
9954
John McCallb697e082010-05-06 18:15:07 +00009955 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9956
John McCallf89e55a2010-11-18 06:31:45 +00009957 // Determine the result type.
9958 QualType ResultTy = FnDecl->getResultType();
9959 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9960 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009961
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009962 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009963 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009964 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009965 if (FnExpr.isInvalid())
9966 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009967
Eli Friedman4c3b8962009-11-18 03:58:17 +00009968 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009969 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009970 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009971 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009972
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009973 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009974 FnDecl))
9975 return ExprError();
9976
John McCall9ae2f072010-08-23 23:25:46 +00009977 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009978 } else {
9979 // We matched a built-in operator. Convert the arguments, then
9980 // break out so that we will build the appropriate built-in
9981 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009982 ExprResult InputRes =
9983 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9984 Best->Conversions[0], AA_Passing);
9985 if (InputRes.isInvalid())
9986 return ExprError();
9987 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009988 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009989 }
John Wiegley429bb272011-04-08 18:41:53 +00009990 }
9991
9992 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009993 // This is an erroneous use of an operator which can be overloaded by
9994 // a non-member function. Check for non-member operators which were
9995 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009996 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9997 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009998 // FIXME: Recover by calling the found function.
9999 return ExprError();
10000
John Wiegley429bb272011-04-08 18:41:53 +000010001 // No viable function; fall through to handling this as a
10002 // built-in operator, which will produce an error message for us.
10003 break;
10004
10005 case OR_Ambiguous:
10006 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10007 << UnaryOperator::getOpcodeStr(Opc)
10008 << Input->getType()
10009 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010010 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10011 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010012 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10013 return ExprError();
10014
10015 case OR_Deleted:
10016 Diag(OpLoc, diag::err_ovl_deleted_oper)
10017 << Best->Function->isDeleted()
10018 << UnaryOperator::getOpcodeStr(Opc)
10019 << getDeletedOrUnavailableSuffix(Best->Function)
10020 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10022 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010023 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010024 return ExprError();
10025 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010026
10027 // Either we found no viable overloaded operator or we matched a
10028 // built-in operator. In either case, fall through to trying to
10029 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010030 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010031}
10032
Douglas Gregor063daf62009-03-13 18:40:31 +000010033/// \brief Create a binary operation that may resolve to an overloaded
10034/// operator.
10035///
10036/// \param OpLoc The location of the operator itself (e.g., '+').
10037///
10038/// \param OpcIn The BinaryOperator::Opcode that describes this
10039/// operator.
10040///
James Dennett40ae6662012-06-22 08:52:37 +000010041/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010042/// considered by overload resolution. The caller needs to build this
10043/// set based on the context using, e.g.,
10044/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10045/// set should not contain any member functions; those will be added
10046/// by CreateOverloadedBinOp().
10047///
10048/// \param LHS Left-hand argument.
10049/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010050ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010051Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010052 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010053 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010054 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010055 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010056 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010057
10058 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10059 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10061
10062 // If either side is type-dependent, create an appropriate dependent
10063 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010064 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010065 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010066 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010067 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010068 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010069 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010070 Context.DependentTy,
10071 VK_RValue, OK_Ordinary,
10072 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010073
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010074 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10075 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010076 VK_LValue,
10077 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010078 Context.DependentTy,
10079 Context.DependentTy,
10080 OpLoc));
10081 }
John McCall6e266892010-01-26 03:27:55 +000010082
10083 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010084 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010085 // TODO: provide better source location info in DNLoc component.
10086 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010087 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010088 = UnresolvedLookupExpr::Create(Context, NamingClass,
10089 NestedNameSpecifierLoc(), OpNameInfo,
10090 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010091 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +000010092 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +000010093 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +000010094 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010095 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +000010096 OpLoc));
10097 }
10098
John McCall5acb0c92011-10-17 18:40:02 +000010099 // Always do placeholder-like conversions on the RHS.
10100 if (checkPlaceholderForOverload(*this, Args[1]))
10101 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010102
John McCall3c3b7f92011-10-25 17:37:35 +000010103 // Do placeholder-like conversion on the LHS; note that we should
10104 // not get here with a PseudoObject LHS.
10105 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010106 if (checkPlaceholderForOverload(*this, Args[0]))
10107 return ExprError();
10108
Sebastian Redl275c2b42009-11-18 23:10:33 +000010109 // If this is the assignment operator, we only perform overload resolution
10110 // if the left-hand side is a class or enumeration type. This is actually
10111 // a hack. The standard requires that we do overload resolution between the
10112 // various built-in candidates, but as DR507 points out, this can lead to
10113 // problems. So we do it this way, which pretty much follows what GCC does.
10114 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010115 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010116 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010117
John McCall0e800c92010-12-04 08:14:53 +000010118 // If this is the .* operator, which is not overloadable, just
10119 // create a built-in binary operator.
10120 if (Opc == BO_PtrMemD)
10121 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10122
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010123 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010124 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010125
10126 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010127 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010128
10129 // Add operator candidates that are member functions.
10130 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10131
John McCall6e266892010-01-26 03:27:55 +000010132 // Add candidates from ADL.
10133 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010134 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010135 /*ExplicitTemplateArgs*/ 0,
10136 CandidateSet);
10137
Douglas Gregor063daf62009-03-13 18:40:31 +000010138 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010139 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010140
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010141 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10142
Douglas Gregor063daf62009-03-13 18:40:31 +000010143 // Perform overload resolution.
10144 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010145 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010146 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010147 // We found a built-in operator or an overloaded operator.
10148 FunctionDecl *FnDecl = Best->Function;
10149
10150 if (FnDecl) {
10151 // We matched an overloaded operator. Build a call to that
10152 // operator.
10153
Eli Friedman5f2987c2012-02-02 03:46:19 +000010154 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010155
Douglas Gregor063daf62009-03-13 18:40:31 +000010156 // Convert the arguments.
10157 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010158 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010159 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010160
Chandler Carruth6df868e2010-12-12 08:17:55 +000010161 ExprResult Arg1 =
10162 PerformCopyInitialization(
10163 InitializedEntity::InitializeParameter(Context,
10164 FnDecl->getParamDecl(0)),
10165 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010166 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010167 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010168
John Wiegley429bb272011-04-08 18:41:53 +000010169 ExprResult Arg0 =
10170 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10171 Best->FoundDecl, Method);
10172 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010173 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010174 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010175 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010176 } else {
10177 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010178 ExprResult Arg0 = PerformCopyInitialization(
10179 InitializedEntity::InitializeParameter(Context,
10180 FnDecl->getParamDecl(0)),
10181 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010182 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010183 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010184
Chandler Carruth6df868e2010-12-12 08:17:55 +000010185 ExprResult Arg1 =
10186 PerformCopyInitialization(
10187 InitializedEntity::InitializeParameter(Context,
10188 FnDecl->getParamDecl(1)),
10189 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010190 if (Arg1.isInvalid())
10191 return ExprError();
10192 Args[0] = LHS = Arg0.takeAs<Expr>();
10193 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010194 }
10195
John McCallb697e082010-05-06 18:15:07 +000010196 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10197
John McCallf89e55a2010-11-18 06:31:45 +000010198 // Determine the result type.
10199 QualType ResultTy = FnDecl->getResultType();
10200 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10201 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010202
10203 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010204 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10205 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010206 if (FnExpr.isInvalid())
10207 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010208
John McCall9ae2f072010-08-23 23:25:46 +000010209 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010210 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010211 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010212
10213 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010214 FnDecl))
10215 return ExprError();
10216
John McCall9ae2f072010-08-23 23:25:46 +000010217 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010218 } else {
10219 // We matched a built-in operator. Convert the arguments, then
10220 // break out so that we will build the appropriate built-in
10221 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010222 ExprResult ArgsRes0 =
10223 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10224 Best->Conversions[0], AA_Passing);
10225 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010226 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010227 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010228
John Wiegley429bb272011-04-08 18:41:53 +000010229 ExprResult ArgsRes1 =
10230 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10231 Best->Conversions[1], AA_Passing);
10232 if (ArgsRes1.isInvalid())
10233 return ExprError();
10234 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010235 break;
10236 }
10237 }
10238
Douglas Gregor33074752009-09-30 21:46:01 +000010239 case OR_No_Viable_Function: {
10240 // C++ [over.match.oper]p9:
10241 // If the operator is the operator , [...] and there are no
10242 // viable functions, then the operator is assumed to be the
10243 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010244 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010245 break;
10246
Chandler Carruth6df868e2010-12-12 08:17:55 +000010247 // For class as left operand for assignment or compound assigment
10248 // operator do not fall through to handling in built-in, but report that
10249 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010250 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010251 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010252 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010253 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10254 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010255 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010256 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010257 // This is an erroneous use of an operator which can be overloaded by
10258 // a non-member function. Check for non-member operators which were
10259 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010260 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010261 // FIXME: Recover by calling the found function.
10262 return ExprError();
10263
Douglas Gregor33074752009-09-30 21:46:01 +000010264 // No viable function; try to create a built-in operation, which will
10265 // produce an error. Then, show the non-viable candidates.
10266 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010267 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010268 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010269 "C++ binary operator overloading is missing candidates!");
10270 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010272 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010273 return move(Result);
10274 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010275
10276 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010277 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010278 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010279 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010280 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010281 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010282 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010283 return ExprError();
10284
10285 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010286 if (isImplicitlyDeleted(Best->Function)) {
10287 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10288 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10289 << getSpecialMember(Method)
10290 << BinaryOperator::getOpcodeStr(Opc)
10291 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010292
10293 if (getSpecialMember(Method) != CXXInvalid) {
10294 // The user probably meant to call this special member. Just
10295 // explain why it's deleted.
10296 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010297 return ExprError();
10298 }
10299 } else {
10300 Diag(OpLoc, diag::err_ovl_deleted_oper)
10301 << Best->Function->isDeleted()
10302 << BinaryOperator::getOpcodeStr(Opc)
10303 << getDeletedOrUnavailableSuffix(Best->Function)
10304 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10305 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010307 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010308 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010309 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010310
Douglas Gregor33074752009-09-30 21:46:01 +000010311 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010312 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010313}
10314
John McCall60d7b3a2010-08-24 06:29:42 +000010315ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010316Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10317 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010318 Expr *Base, Expr *Idx) {
10319 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010320 DeclarationName OpName =
10321 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10322
10323 // If either side is type-dependent, create an appropriate dependent
10324 // expression.
10325 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10326
John McCallc373d482010-01-27 01:50:18 +000010327 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010328 // CHECKME: no 'operator' keyword?
10329 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10330 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010331 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010332 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010333 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010334 /*ADL*/ true, /*Overloaded*/ false,
10335 UnresolvedSetIterator(),
10336 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010337 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010338
Sebastian Redlf322ed62009-10-29 20:17:01 +000010339 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10340 Args, 2,
10341 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010342 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010343 RLoc));
10344 }
10345
John McCall5acb0c92011-10-17 18:40:02 +000010346 // Handle placeholders on both operands.
10347 if (checkPlaceholderForOverload(*this, Args[0]))
10348 return ExprError();
10349 if (checkPlaceholderForOverload(*this, Args[1]))
10350 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010351
Sebastian Redlf322ed62009-10-29 20:17:01 +000010352 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010353 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010354
10355 // Subscript can only be overloaded as a member function.
10356
10357 // Add operator candidates that are member functions.
10358 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10359
10360 // Add builtin operator candidates.
10361 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10362
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010363 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10364
Sebastian Redlf322ed62009-10-29 20:17:01 +000010365 // Perform overload resolution.
10366 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010367 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010368 case OR_Success: {
10369 // We found a built-in operator or an overloaded operator.
10370 FunctionDecl *FnDecl = Best->Function;
10371
10372 if (FnDecl) {
10373 // We matched an overloaded operator. Build a call to that
10374 // operator.
10375
Eli Friedman5f2987c2012-02-02 03:46:19 +000010376 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010377
John McCall9aa472c2010-03-19 07:35:19 +000010378 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010379 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010380
Sebastian Redlf322ed62009-10-29 20:17:01 +000010381 // Convert the arguments.
10382 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010383 ExprResult Arg0 =
10384 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10385 Best->FoundDecl, Method);
10386 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010387 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010388 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010389
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010390 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010391 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010392 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010393 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010394 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010395 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010396 Owned(Args[1]));
10397 if (InputInit.isInvalid())
10398 return ExprError();
10399
10400 Args[1] = InputInit.takeAs<Expr>();
10401
Sebastian Redlf322ed62009-10-29 20:17:01 +000010402 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010403 QualType ResultTy = FnDecl->getResultType();
10404 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10405 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010406
10407 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010408 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10409 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010410 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10411 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010412 OpLocInfo.getLoc(),
10413 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010414 if (FnExpr.isInvalid())
10415 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010416
John McCall9ae2f072010-08-23 23:25:46 +000010417 CXXOperatorCallExpr *TheCall =
10418 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010419 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010420 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010421
John McCall9ae2f072010-08-23 23:25:46 +000010422 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010423 FnDecl))
10424 return ExprError();
10425
John McCall9ae2f072010-08-23 23:25:46 +000010426 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010427 } else {
10428 // We matched a built-in operator. Convert the arguments, then
10429 // break out so that we will build the appropriate built-in
10430 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010431 ExprResult ArgsRes0 =
10432 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10433 Best->Conversions[0], AA_Passing);
10434 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010435 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010436 Args[0] = ArgsRes0.take();
10437
10438 ExprResult ArgsRes1 =
10439 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10440 Best->Conversions[1], AA_Passing);
10441 if (ArgsRes1.isInvalid())
10442 return ExprError();
10443 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010444
10445 break;
10446 }
10447 }
10448
10449 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010450 if (CandidateSet.empty())
10451 Diag(LLoc, diag::err_ovl_no_oper)
10452 << Args[0]->getType() << /*subscript*/ 0
10453 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10454 else
10455 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10456 << Args[0]->getType()
10457 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010458 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010459 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010460 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010461 }
10462
10463 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010464 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010465 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010466 << Args[0]->getType() << Args[1]->getType()
10467 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010468 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010469 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010470 return ExprError();
10471
10472 case OR_Deleted:
10473 Diag(LLoc, diag::err_ovl_deleted_oper)
10474 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010475 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010476 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010477 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010478 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010479 return ExprError();
10480 }
10481
10482 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010483 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010484}
10485
Douglas Gregor88a35142008-12-22 05:46:06 +000010486/// BuildCallToMemberFunction - Build a call to a member
10487/// function. MemExpr is the expression that refers to the member
10488/// function (and includes the object parameter), Args/NumArgs are the
10489/// arguments to the function call (not including the object
10490/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010491/// expression refers to a non-static member function or an overloaded
10492/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010493ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010494Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10495 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010496 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010497 assert(MemExprE->getType() == Context.BoundMemberTy ||
10498 MemExprE->getType() == Context.OverloadTy);
10499
Douglas Gregor88a35142008-12-22 05:46:06 +000010500 // Dig out the member expression. This holds both the object
10501 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010502 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010503
John McCall864c0412011-04-26 20:42:42 +000010504 // Determine whether this is a call to a pointer-to-member function.
10505 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10506 assert(op->getType() == Context.BoundMemberTy);
10507 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10508
10509 QualType fnType =
10510 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10511
10512 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10513 QualType resultType = proto->getCallResultType(Context);
10514 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10515
10516 // Check that the object type isn't more qualified than the
10517 // member function we're calling.
10518 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10519
10520 QualType objectType = op->getLHS()->getType();
10521 if (op->getOpcode() == BO_PtrMemI)
10522 objectType = objectType->castAs<PointerType>()->getPointeeType();
10523 Qualifiers objectQuals = objectType.getQualifiers();
10524
10525 Qualifiers difference = objectQuals - funcQuals;
10526 difference.removeObjCGCAttr();
10527 difference.removeAddressSpace();
10528 if (difference) {
10529 std::string qualsString = difference.getAsString();
10530 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10531 << fnType.getUnqualifiedType()
10532 << qualsString
10533 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10534 }
10535
10536 CXXMemberCallExpr *call
10537 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10538 resultType, valueKind, RParenLoc);
10539
10540 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010541 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010542 call, 0))
10543 return ExprError();
10544
10545 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10546 return ExprError();
10547
10548 return MaybeBindToTemporary(call);
10549 }
10550
John McCall5acb0c92011-10-17 18:40:02 +000010551 UnbridgedCastsSet UnbridgedCasts;
10552 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10553 return ExprError();
10554
John McCall129e2df2009-11-30 22:42:35 +000010555 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010556 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010557 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010558 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010559 if (isa<MemberExpr>(NakedMemExpr)) {
10560 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010561 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010562 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010563 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010564 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010565 } else {
10566 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010567 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010568
John McCall701c89e2009-12-03 04:06:58 +000010569 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010570 Expr::Classification ObjectClassification
10571 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10572 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010573
Douglas Gregor88a35142008-12-22 05:46:06 +000010574 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010575 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010576
John McCallaa81e162009-12-01 22:10:20 +000010577 // FIXME: avoid copy.
10578 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10579 if (UnresExpr->hasExplicitTemplateArgs()) {
10580 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10581 TemplateArgs = &TemplateArgsBuffer;
10582 }
10583
John McCall129e2df2009-11-30 22:42:35 +000010584 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10585 E = UnresExpr->decls_end(); I != E; ++I) {
10586
John McCall701c89e2009-12-03 04:06:58 +000010587 NamedDecl *Func = *I;
10588 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10589 if (isa<UsingShadowDecl>(Func))
10590 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10591
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010592
Francois Pichetdbee3412011-01-18 05:04:39 +000010593 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010594 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010595 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10596 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010597 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010598 // If explicit template arguments were provided, we can't call a
10599 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010600 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010601 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010602
John McCall9aa472c2010-03-19 07:35:19 +000010603 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010604 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010605 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010606 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010607 } else {
John McCall129e2df2009-11-30 22:42:35 +000010608 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010609 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010610 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010611 llvm::makeArrayRef(Args, NumArgs),
10612 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010613 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010614 }
Douglas Gregordec06662009-08-21 18:42:58 +000010615 }
Mike Stump1eb44332009-09-09 15:08:12 +000010616
John McCall129e2df2009-11-30 22:42:35 +000010617 DeclarationName DeclName = UnresExpr->getMemberName();
10618
John McCall5acb0c92011-10-17 18:40:02 +000010619 UnbridgedCasts.restore();
10620
Douglas Gregor88a35142008-12-22 05:46:06 +000010621 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010622 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010623 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010624 case OR_Success:
10625 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010626 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010627 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010628 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010629 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010630 break;
10631
10632 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010633 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010634 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010635 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010636 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10637 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010638 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010639 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010640
10641 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010642 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010643 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010644 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10645 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010646 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010647 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010648
10649 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010650 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010651 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010652 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010653 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010654 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010655 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10656 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010657 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010658 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010659 }
10660
John McCall6bb80172010-03-30 21:47:33 +000010661 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010662
John McCallaa81e162009-12-01 22:10:20 +000010663 // If overload resolution picked a static member, build a
10664 // non-member call based on that function.
10665 if (Method->isStatic()) {
10666 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10667 Args, NumArgs, RParenLoc);
10668 }
10669
John McCall129e2df2009-11-30 22:42:35 +000010670 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010671 }
10672
John McCallf89e55a2010-11-18 06:31:45 +000010673 QualType ResultType = Method->getResultType();
10674 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10675 ResultType = ResultType.getNonLValueExprType(Context);
10676
Douglas Gregor88a35142008-12-22 05:46:06 +000010677 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010678 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010679 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010680 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010681
Anders Carlssoneed3e692009-10-10 00:06:20 +000010682 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010683 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010684 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010685 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010686
Douglas Gregor88a35142008-12-22 05:46:06 +000010687 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010688 // We only need to do this if there was actually an overload; otherwise
10689 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010690 if (!Method->isStatic()) {
10691 ExprResult ObjectArg =
10692 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10693 FoundDecl, Method);
10694 if (ObjectArg.isInvalid())
10695 return ExprError();
10696 MemExpr->setBase(ObjectArg.take());
10697 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010698
10699 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010700 const FunctionProtoType *Proto =
10701 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010702 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010703 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010704 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010705
Eli Friedmane61eb042012-02-18 04:48:30 +000010706 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10707
Richard Smith831421f2012-06-25 20:30:08 +000010708 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010709 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010710
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010711 if ((isa<CXXConstructorDecl>(CurContext) ||
10712 isa<CXXDestructorDecl>(CurContext)) &&
10713 TheCall->getMethodDecl()->isPure()) {
10714 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10715
Chandler Carruthae198062011-06-27 08:31:58 +000010716 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010717 Diag(MemExpr->getLocStart(),
10718 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10719 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10720 << MD->getParent()->getDeclName();
10721
10722 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010723 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010724 }
John McCall9ae2f072010-08-23 23:25:46 +000010725 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010726}
10727
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010728/// BuildCallToObjectOfClassType - Build a call to an object of class
10729/// type (C++ [over.call.object]), which can end up invoking an
10730/// overloaded function call operator (@c operator()) or performing a
10731/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010732ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010733Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010734 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010735 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010736 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010737 if (checkPlaceholderForOverload(*this, Obj))
10738 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010739 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010740
10741 UnbridgedCastsSet UnbridgedCasts;
10742 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10743 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010744
John Wiegley429bb272011-04-08 18:41:53 +000010745 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10746 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010747
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010748 // C++ [over.call.object]p1:
10749 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010750 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010751 // candidate functions includes at least the function call
10752 // operators of T. The function call operators of T are obtained by
10753 // ordinary lookup of the name operator() in the context of
10754 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010755 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010757
John Wiegley429bb272011-04-08 18:41:53 +000010758 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010759 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010760 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010761
John McCalla24dc2e2009-11-17 02:14:36 +000010762 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10763 LookupQualifiedName(R, Record->getDecl());
10764 R.suppressDiagnostics();
10765
Douglas Gregor593564b2009-11-15 07:48:03 +000010766 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010767 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010768 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10769 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010770 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010772
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010773 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010774 // In addition, for each (non-explicit in C++0x) conversion function
10775 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010776 //
10777 // operator conversion-type-id () cv-qualifier;
10778 //
10779 // where cv-qualifier is the same cv-qualification as, or a
10780 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010781 // denotes the type "pointer to function of (P1,...,Pn) returning
10782 // R", or the type "reference to pointer to function of
10783 // (P1,...,Pn) returning R", or the type "reference to function
10784 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010785 // is also considered as a candidate function. Similarly,
10786 // surrogate call functions are added to the set of candidate
10787 // functions for each conversion function declared in an
10788 // accessible base class provided the function is not hidden
10789 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010790 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010791 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010792 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010793 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010794 NamedDecl *D = *I;
10795 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10796 if (isa<UsingShadowDecl>(D))
10797 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010798
Douglas Gregor4a27d702009-10-21 06:18:39 +000010799 // Skip over templated conversion functions; they aren't
10800 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010801 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010802 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010803
John McCall701c89e2009-12-03 04:06:58 +000010804 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010805 if (!Conv->isExplicit()) {
10806 // Strip the reference type (if any) and then the pointer type (if
10807 // any) to get down to what might be a function type.
10808 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10809 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10810 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010811
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010812 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10813 {
10814 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010815 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10816 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010817 }
10818 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010819 }
Mike Stump1eb44332009-09-09 15:08:12 +000010820
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010821 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10822
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010823 // Perform overload resolution.
10824 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010825 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010826 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010827 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010828 // Overload resolution succeeded; we'll build the appropriate call
10829 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010830 break;
10831
10832 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010833 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010834 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010835 << Object.get()->getType() << /*call*/ 1
10836 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010837 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010838 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010839 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010840 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010841 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10842 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010843 break;
10844
10845 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010846 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010847 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010848 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010849 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10850 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010851 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010852
10853 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010854 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010855 diag::err_ovl_deleted_object_call)
10856 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010857 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010858 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010859 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10861 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010862 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010863 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010864
Douglas Gregorff331c12010-07-25 18:17:45 +000010865 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010866 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010867
John McCall5acb0c92011-10-17 18:40:02 +000010868 UnbridgedCasts.restore();
10869
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010870 if (Best->Function == 0) {
10871 // Since there is no function declaration, this is one of the
10872 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010873 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010874 = cast<CXXConversionDecl>(
10875 Best->Conversions[0].UserDefined.ConversionFunction);
10876
John Wiegley429bb272011-04-08 18:41:53 +000010877 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010878 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010879
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010880 // We selected one of the surrogate functions that converts the
10881 // object parameter to a function pointer. Perform the conversion
10882 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010883
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010884 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010885 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010886 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10887 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010888 if (Call.isInvalid())
10889 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010890 // Record usage of conversion in an implicit cast.
10891 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10892 CK_UserDefinedConversion,
10893 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010894
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010895 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010896 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010897 }
10898
Eli Friedman5f2987c2012-02-02 03:46:19 +000010899 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010900 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010901 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010902
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010903 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10904 // that calls this method, using Object for the implicit object
10905 // parameter and passing along the remaining arguments.
10906 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010907 const FunctionProtoType *Proto =
10908 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010909
10910 unsigned NumArgsInProto = Proto->getNumArgs();
10911 unsigned NumArgsToCheck = NumArgs;
10912
10913 // Build the full argument list for the method call (the
10914 // implicit object parameter is placed at the beginning of the
10915 // list).
10916 Expr **MethodArgs;
10917 if (NumArgs < NumArgsInProto) {
10918 NumArgsToCheck = NumArgsInProto;
10919 MethodArgs = new Expr*[NumArgsInProto + 1];
10920 } else {
10921 MethodArgs = new Expr*[NumArgs + 1];
10922 }
John Wiegley429bb272011-04-08 18:41:53 +000010923 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010924 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10925 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010926
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010927 DeclarationNameInfo OpLocInfo(
10928 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10929 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010930 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010931 HadMultipleCandidates,
10932 OpLocInfo.getLoc(),
10933 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010934 if (NewFn.isInvalid())
10935 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010936
10937 // Once we've built TheCall, all of the expressions are properly
10938 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010939 QualType ResultTy = Method->getResultType();
10940 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10941 ResultTy = ResultTy.getNonLValueExprType(Context);
10942
John McCall9ae2f072010-08-23 23:25:46 +000010943 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010944 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010945 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010946 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010947 delete [] MethodArgs;
10948
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010949 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010950 Method))
10951 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010952
Douglas Gregor518fda12009-01-13 05:10:00 +000010953 // We may have default arguments. If so, we need to allocate more
10954 // slots in the call for them.
10955 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010956 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010957 else if (NumArgs > NumArgsInProto)
10958 NumArgsToCheck = NumArgsInProto;
10959
Chris Lattner312531a2009-04-12 08:11:20 +000010960 bool IsError = false;
10961
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010962 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010963 ExprResult ObjRes =
10964 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10965 Best->FoundDecl, Method);
10966 if (ObjRes.isInvalid())
10967 IsError = true;
10968 else
10969 Object = move(ObjRes);
10970 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010971
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010972 // Check the argument types.
10973 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010974 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010975 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010976 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010977
Douglas Gregor518fda12009-01-13 05:10:00 +000010978 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010979
John McCall60d7b3a2010-08-24 06:29:42 +000010980 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010981 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010982 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010983 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010984 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010985
Anders Carlsson3faa4862010-01-29 18:43:53 +000010986 IsError |= InputInit.isInvalid();
10987 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010988 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010989 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010990 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10991 if (DefArg.isInvalid()) {
10992 IsError = true;
10993 break;
10994 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010995
Douglas Gregord47c47d2009-11-09 19:27:57 +000010996 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010997 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010998
10999 TheCall->setArg(i + 1, Arg);
11000 }
11001
11002 // If this is a variadic call, handle args passed through "...".
11003 if (Proto->isVariadic()) {
11004 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011005 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011006 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11007 IsError |= Arg.isInvalid();
11008 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011009 }
11010 }
11011
Chris Lattner312531a2009-04-12 08:11:20 +000011012 if (IsError) return true;
11013
Eli Friedmane61eb042012-02-18 04:48:30 +000011014 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11015
Richard Smith831421f2012-06-25 20:30:08 +000011016 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011017 return true;
11018
John McCall182f7092010-08-24 06:09:16 +000011019 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011020}
11021
Douglas Gregor8ba10742008-11-20 16:27:02 +000011022/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011023/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011024/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011025ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011026Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011027 assert(Base->getType()->isRecordType() &&
11028 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011029
John McCall5acb0c92011-10-17 18:40:02 +000011030 if (checkPlaceholderForOverload(*this, Base))
11031 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011032
John McCall5769d612010-02-08 23:07:23 +000011033 SourceLocation Loc = Base->getExprLoc();
11034
Douglas Gregor8ba10742008-11-20 16:27:02 +000011035 // C++ [over.ref]p1:
11036 //
11037 // [...] An expression x->m is interpreted as (x.operator->())->m
11038 // for a class object x of type T if T::operator->() exists and if
11039 // the operator is selected as the best match function by the
11040 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011041 DeclarationName OpName =
11042 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011043 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011044 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011045
John McCall5769d612010-02-08 23:07:23 +000011046 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011047 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011048 return ExprError();
11049
John McCalla24dc2e2009-11-17 02:14:36 +000011050 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11051 LookupQualifiedName(R, BaseRecord->getDecl());
11052 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011053
11054 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011055 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011056 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11057 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011058 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011059
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011060 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11061
Douglas Gregor8ba10742008-11-20 16:27:02 +000011062 // Perform overload resolution.
11063 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011064 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011065 case OR_Success:
11066 // Overload resolution succeeded; we'll build the call below.
11067 break;
11068
11069 case OR_No_Viable_Function:
11070 if (CandidateSet.empty())
11071 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011072 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011073 else
11074 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011075 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011076 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011077 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011078
11079 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011080 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11081 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011082 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011083 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011084
11085 case OR_Deleted:
11086 Diag(OpLoc, diag::err_ovl_deleted_oper)
11087 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011088 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011089 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011090 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011091 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011092 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011093 }
11094
Eli Friedman5f2987c2012-02-02 03:46:19 +000011095 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011096 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011097 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011098
Douglas Gregor8ba10742008-11-20 16:27:02 +000011099 // Convert the object parameter.
11100 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011101 ExprResult BaseResult =
11102 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11103 Best->FoundDecl, Method);
11104 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011105 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011106 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011107
Douglas Gregor8ba10742008-11-20 16:27:02 +000011108 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011109 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011110 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011111 if (FnExpr.isInvalid())
11112 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011113
John McCallf89e55a2010-11-18 06:31:45 +000011114 QualType ResultTy = Method->getResultType();
11115 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11116 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011117 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011118 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000011119 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011120
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011121 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011122 Method))
11123 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011124
11125 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011126}
11127
Richard Smith36f5cfe2012-03-09 08:00:36 +000011128/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11129/// a literal operator described by the provided lookup results.
11130ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11131 DeclarationNameInfo &SuffixInfo,
11132 ArrayRef<Expr*> Args,
11133 SourceLocation LitEndLoc,
11134 TemplateArgumentListInfo *TemplateArgs) {
11135 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011136
Richard Smith36f5cfe2012-03-09 08:00:36 +000011137 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11138 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11139 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011140
Richard Smith36f5cfe2012-03-09 08:00:36 +000011141 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11142
Richard Smith36f5cfe2012-03-09 08:00:36 +000011143 // Perform overload resolution. This will usually be trivial, but might need
11144 // to perform substitutions for a literal operator template.
11145 OverloadCandidateSet::iterator Best;
11146 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11147 case OR_Success:
11148 case OR_Deleted:
11149 break;
11150
11151 case OR_No_Viable_Function:
11152 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11153 << R.getLookupName();
11154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11155 return ExprError();
11156
11157 case OR_Ambiguous:
11158 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11159 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11160 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011161 }
11162
Richard Smith36f5cfe2012-03-09 08:00:36 +000011163 FunctionDecl *FD = Best->Function;
11164 MarkFunctionReferenced(UDSuffixLoc, FD);
11165 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011166
Richard Smith36f5cfe2012-03-09 08:00:36 +000011167 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11168 SuffixInfo.getLoc(),
11169 SuffixInfo.getInfo());
11170 if (Fn.isInvalid())
11171 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011172
11173 // Check the argument types. This should almost always be a no-op, except
11174 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011175 Expr *ConvArgs[2];
11176 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11177 ExprResult InputInit = PerformCopyInitialization(
11178 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11179 SourceLocation(), Args[ArgIdx]);
11180 if (InputInit.isInvalid())
11181 return true;
11182 ConvArgs[ArgIdx] = InputInit.take();
11183 }
11184
Richard Smith9fcce652012-03-07 08:35:16 +000011185 QualType ResultTy = FD->getResultType();
11186 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11187 ResultTy = ResultTy.getNonLValueExprType(Context);
11188
Richard Smith9fcce652012-03-07 08:35:16 +000011189 UserDefinedLiteral *UDL =
11190 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11191 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11192
11193 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11194 return ExprError();
11195
Richard Smith831421f2012-06-25 20:30:08 +000011196 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011197 return ExprError();
11198
11199 return MaybeBindToTemporary(UDL);
11200}
11201
Douglas Gregor904eed32008-11-10 20:40:00 +000011202/// FixOverloadedFunctionReference - E is an expression that refers to
11203/// a C++ overloaded function (possibly with some parentheses and
11204/// perhaps a '&' around it). We have resolved the overloaded function
11205/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011206/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011207Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011208 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011209 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011210 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11211 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011212 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011213 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011214
Douglas Gregor699ee522009-11-20 19:42:02 +000011215 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011216 }
11217
Douglas Gregor699ee522009-11-20 19:42:02 +000011218 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011219 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11220 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011221 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011222 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011223 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011224 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011225 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011226 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011227
11228 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011229 ICE->getCastKind(),
11230 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011231 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011232 }
11233
Douglas Gregor699ee522009-11-20 19:42:02 +000011234 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011235 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011236 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11238 if (Method->isStatic()) {
11239 // Do nothing: static member functions aren't any different
11240 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011241 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011242 // Fix the sub expression, which really has to be an
11243 // UnresolvedLookupExpr holding an overloaded member function
11244 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011245 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11246 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011247 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011248 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011249
John McCallba135432009-11-21 08:51:07 +000011250 assert(isa<DeclRefExpr>(SubExpr)
11251 && "fixed to something other than a decl ref");
11252 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11253 && "fixed to a member ref with no nested name qualifier");
11254
11255 // We have taken the address of a pointer to member
11256 // function. Perform the computation here so that we get the
11257 // appropriate pointer to member type.
11258 QualType ClassType
11259 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11260 QualType MemPtrType
11261 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11262
John McCallf89e55a2010-11-18 06:31:45 +000011263 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11264 VK_RValue, OK_Ordinary,
11265 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011266 }
11267 }
John McCall6bb80172010-03-30 21:47:33 +000011268 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11269 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011270 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011271 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011272
John McCall2de56d12010-08-25 11:45:40 +000011273 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011274 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011275 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011276 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011277 }
John McCallba135432009-11-21 08:51:07 +000011278
11279 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011280 // FIXME: avoid copy.
11281 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011282 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011283 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11284 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011285 }
11286
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011287 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11288 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011289 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011290 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011291 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011292 ULE->getNameLoc(),
11293 Fn->getType(),
11294 VK_LValue,
11295 Found.getDecl(),
11296 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011297 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011298 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11299 return DRE;
John McCallba135432009-11-21 08:51:07 +000011300 }
11301
John McCall129e2df2009-11-30 22:42:35 +000011302 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011303 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011304 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11305 if (MemExpr->hasExplicitTemplateArgs()) {
11306 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11307 TemplateArgs = &TemplateArgsBuffer;
11308 }
John McCalld5532b62009-11-23 01:53:49 +000011309
John McCallaa81e162009-12-01 22:10:20 +000011310 Expr *Base;
11311
John McCallf89e55a2010-11-18 06:31:45 +000011312 // If we're filling in a static method where we used to have an
11313 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011314 if (MemExpr->isImplicitAccess()) {
11315 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011316 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11317 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011318 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011319 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011320 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011321 MemExpr->getMemberLoc(),
11322 Fn->getType(),
11323 VK_LValue,
11324 Found.getDecl(),
11325 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011326 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011327 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11328 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011329 } else {
11330 SourceLocation Loc = MemExpr->getMemberLoc();
11331 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011332 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011333 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011334 Base = new (Context) CXXThisExpr(Loc,
11335 MemExpr->getBaseType(),
11336 /*isImplicit=*/true);
11337 }
John McCallaa81e162009-12-01 22:10:20 +000011338 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011339 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011340
John McCallf5307512011-04-27 00:36:17 +000011341 ExprValueKind valueKind;
11342 QualType type;
11343 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11344 valueKind = VK_LValue;
11345 type = Fn->getType();
11346 } else {
11347 valueKind = VK_RValue;
11348 type = Context.BoundMemberTy;
11349 }
11350
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011351 MemberExpr *ME = MemberExpr::Create(Context, Base,
11352 MemExpr->isArrow(),
11353 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011354 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011355 Fn,
11356 Found,
11357 MemExpr->getMemberNameInfo(),
11358 TemplateArgs,
11359 type, valueKind, OK_Ordinary);
11360 ME->setHadMultipleCandidates(true);
11361 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011363
John McCall3fa5cae2010-10-26 07:05:15 +000011364 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011365}
11366
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011367ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011368 DeclAccessPair Found,
11369 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011370 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011371}
11372
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011373} // end namespace clang