blob: 9420b73d8b8f54e4a775f583194863de1db624df [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.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002503/// If the parameters are different, ArgPos will have the the parameter index
2504/// 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
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002565 if (!IsCStyleOrFunctionalCast &&
2566 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2567 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2568 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002569 PDiag(diag::warn_impcast_bool_to_null_pointer)
2570 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002571
John McCall1d9b3b22011-09-09 05:25:32 +00002572 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2573 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002574 QualType FromPointeeType = FromPtrType->getPointeeType(),
2575 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002576
Douglas Gregor5fccd362010-03-03 23:55:11 +00002577 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2578 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002579 // We must have a derived-to-base conversion. Check an
2580 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002581 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2582 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002583 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002584 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002585 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002586
Anders Carlsson61faec12009-09-12 04:46:44 +00002587 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002588 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002589 }
2590 }
John McCall1d9b3b22011-09-09 05:25:32 +00002591 } else if (const ObjCObjectPointerType *ToPtrType =
2592 ToType->getAs<ObjCObjectPointerType>()) {
2593 if (const ObjCObjectPointerType *FromPtrType =
2594 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002595 // Objective-C++ conversions are always okay.
2596 // FIXME: We should have a different class of conversions for the
2597 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002598 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002599 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002600 } else if (FromType->isBlockPointerType()) {
2601 Kind = CK_BlockPointerToObjCPointerCast;
2602 } else {
2603 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002604 }
John McCall1d9b3b22011-09-09 05:25:32 +00002605 } else if (ToType->isBlockPointerType()) {
2606 if (!FromType->isBlockPointerType())
2607 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002608 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002609
2610 // We shouldn't fall into this case unless it's valid for other
2611 // reasons.
2612 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2613 Kind = CK_NullToPointer;
2614
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002615 return false;
2616}
2617
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002618/// IsMemberPointerConversion - Determines whether the conversion of the
2619/// expression From, which has the (possibly adjusted) type FromType, can be
2620/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2621/// If so, returns true and places the converted type (that might differ from
2622/// ToType in its cv-qualifiers at some level) into ConvertedType.
2623bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002624 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002625 bool InOverloadResolution,
2626 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002627 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002628 if (!ToTypePtr)
2629 return false;
2630
2631 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002632 if (From->isNullPointerConstant(Context,
2633 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2634 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002635 ConvertedType = ToType;
2636 return true;
2637 }
2638
2639 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002640 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002641 if (!FromTypePtr)
2642 return false;
2643
2644 // A pointer to member of B can be converted to a pointer to member of D,
2645 // where D is derived from B (C++ 4.11p2).
2646 QualType FromClass(FromTypePtr->getClass(), 0);
2647 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002648
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002649 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002650 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002651 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002652 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2653 ToClass.getTypePtr());
2654 return true;
2655 }
2656
2657 return false;
2658}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002659
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002660/// CheckMemberPointerConversion - Check the member pointer conversion from the
2661/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002662/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002663/// for which IsMemberPointerConversion has already returned true. It returns
2664/// true and produces a diagnostic if there was an error, or returns false
2665/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002666bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002667 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002668 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002669 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002670 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002671 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002672 if (!FromPtrType) {
2673 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002674 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002675 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002676 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002677 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002678 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002679 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002680
Ted Kremenek6217b802009-07-29 21:53:49 +00002681 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002682 assert(ToPtrType && "No member pointer cast has a target type "
2683 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002684
Sebastian Redl21593ac2009-01-28 18:33:18 +00002685 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2686 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002687
Sebastian Redl21593ac2009-01-28 18:33:18 +00002688 // FIXME: What about dependent types?
2689 assert(FromClass->isRecordType() && "Pointer into non-class.");
2690 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002691
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002692 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002693 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002694 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2695 assert(DerivationOkay &&
2696 "Should not have been called if derivation isn't OK.");
2697 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002698
Sebastian Redl21593ac2009-01-28 18:33:18 +00002699 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2700 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002701 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2702 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2703 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2704 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002705 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002706
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002707 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002708 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2709 << FromClass << ToClass << QualType(VBase, 0)
2710 << From->getSourceRange();
2711 return true;
2712 }
2713
John McCall6b2accb2010-02-10 09:31:12 +00002714 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002715 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2716 Paths.front(),
2717 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002718
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002719 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002720 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002721 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002722 return false;
2723}
2724
Douglas Gregor98cd5992008-10-21 23:43:52 +00002725/// IsQualificationConversion - Determines whether the conversion from
2726/// an rvalue of type FromType to ToType is a qualification conversion
2727/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002728///
2729/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2730/// when the qualification conversion involves a change in the Objective-C
2731/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002732bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002733Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002734 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002735 FromType = Context.getCanonicalType(FromType);
2736 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002737 ObjCLifetimeConversion = false;
2738
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 // If FromType and ToType are the same type, this is not a
2740 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002741 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002742 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002743
Douglas Gregor98cd5992008-10-21 23:43:52 +00002744 // (C++ 4.4p4):
2745 // A conversion can add cv-qualifiers at levels other than the first
2746 // in multi-level pointers, subject to the following rules: [...]
2747 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002748 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002749 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002750 // Within each iteration of the loop, we check the qualifiers to
2751 // determine if this still looks like a qualification
2752 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002753 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002754 // until there are no more pointers or pointers-to-members left to
2755 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002756 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002757
Douglas Gregor621c92a2011-04-25 18:40:17 +00002758 Qualifiers FromQuals = FromType.getQualifiers();
2759 Qualifiers ToQuals = ToType.getQualifiers();
2760
John McCallf85e1932011-06-15 23:02:42 +00002761 // Objective-C ARC:
2762 // Check Objective-C lifetime conversions.
2763 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2764 UnwrappedAnyPointer) {
2765 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2766 ObjCLifetimeConversion = true;
2767 FromQuals.removeObjCLifetime();
2768 ToQuals.removeObjCLifetime();
2769 } else {
2770 // Qualification conversions cannot cast between different
2771 // Objective-C lifetime qualifiers.
2772 return false;
2773 }
2774 }
2775
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002776 // Allow addition/removal of GC attributes but not changing GC attributes.
2777 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2778 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2779 FromQuals.removeObjCGCAttr();
2780 ToQuals.removeObjCGCAttr();
2781 }
2782
Douglas Gregor98cd5992008-10-21 23:43:52 +00002783 // -- for every j > 0, if const is in cv 1,j then const is in cv
2784 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002785 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002786 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Douglas Gregor98cd5992008-10-21 23:43:52 +00002788 // -- if the cv 1,j and cv 2,j are different, then const is in
2789 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002790 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002791 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002792 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Douglas Gregor98cd5992008-10-21 23:43:52 +00002794 // Keep track of whether all prior cv-qualifiers in the "to" type
2795 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002796 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002797 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002798 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799
2800 // We are left with FromType and ToType being the pointee types
2801 // after unwrapping the original FromType and ToType the same number
2802 // of types. If we unwrapped any pointers, and if FromType and
2803 // ToType have the same unqualified type (since we checked
2804 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002805 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002806}
2807
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002808/// \brief - Determine whether this is a conversion from a scalar type to an
2809/// atomic type.
2810///
2811/// If successful, updates \c SCS's second and third steps in the conversion
2812/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002813static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2814 bool InOverloadResolution,
2815 StandardConversionSequence &SCS,
2816 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002817 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2818 if (!ToAtomic)
2819 return false;
2820
2821 StandardConversionSequence InnerSCS;
2822 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2823 InOverloadResolution, InnerSCS,
2824 CStyle, /*AllowObjCWritebackConversion=*/false))
2825 return false;
2826
2827 SCS.Second = InnerSCS.Second;
2828 SCS.setToType(1, InnerSCS.getToType(1));
2829 SCS.Third = InnerSCS.Third;
2830 SCS.QualificationIncludesObjCLifetime
2831 = InnerSCS.QualificationIncludesObjCLifetime;
2832 SCS.setToType(2, InnerSCS.getToType(2));
2833 return true;
2834}
2835
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002836static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2837 CXXConstructorDecl *Constructor,
2838 QualType Type) {
2839 const FunctionProtoType *CtorType =
2840 Constructor->getType()->getAs<FunctionProtoType>();
2841 if (CtorType->getNumArgs() > 0) {
2842 QualType FirstArg = CtorType->getArgType(0);
2843 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2844 return true;
2845 }
2846 return false;
2847}
2848
Sebastian Redl56a04282012-02-11 23:51:08 +00002849static OverloadingResult
2850IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2851 CXXRecordDecl *To,
2852 UserDefinedConversionSequence &User,
2853 OverloadCandidateSet &CandidateSet,
2854 bool AllowExplicit) {
2855 DeclContext::lookup_iterator Con, ConEnd;
2856 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2857 Con != ConEnd; ++Con) {
2858 NamedDecl *D = *Con;
2859 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2860
2861 // Find the constructor (which may be a template).
2862 CXXConstructorDecl *Constructor = 0;
2863 FunctionTemplateDecl *ConstructorTmpl
2864 = dyn_cast<FunctionTemplateDecl>(D);
2865 if (ConstructorTmpl)
2866 Constructor
2867 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2868 else
2869 Constructor = cast<CXXConstructorDecl>(D);
2870
2871 bool Usable = !Constructor->isInvalidDecl() &&
2872 S.isInitListConstructor(Constructor) &&
2873 (AllowExplicit || !Constructor->isExplicit());
2874 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002875 // If the first argument is (a reference to) the target type,
2876 // suppress conversions.
2877 bool SuppressUserConversions =
2878 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002879 if (ConstructorTmpl)
2880 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2881 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002882 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002883 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002884 else
2885 S.AddOverloadCandidate(Constructor, FoundDecl,
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 }
2889 }
2890
2891 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2892
2893 OverloadCandidateSet::iterator Best;
2894 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2895 case OR_Success: {
2896 // Record the standard conversion we used and the conversion function.
2897 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2898 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2899
2900 QualType ThisType = Constructor->getThisType(S.Context);
2901 // Initializer lists don't have conversions as such.
2902 User.Before.setAsIdentityConversion();
2903 User.HadMultipleCandidates = HadMultipleCandidates;
2904 User.ConversionFunction = Constructor;
2905 User.FoundConversionFunction = Best->FoundDecl;
2906 User.After.setAsIdentityConversion();
2907 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2908 User.After.setAllToTypes(ToType);
2909 return OR_Success;
2910 }
2911
2912 case OR_No_Viable_Function:
2913 return OR_No_Viable_Function;
2914 case OR_Deleted:
2915 return OR_Deleted;
2916 case OR_Ambiguous:
2917 return OR_Ambiguous;
2918 }
2919
2920 llvm_unreachable("Invalid OverloadResult!");
2921}
2922
Douglas Gregor734d9862009-01-30 23:27:23 +00002923/// Determines whether there is a user-defined conversion sequence
2924/// (C++ [over.ics.user]) that converts expression From to the type
2925/// ToType. If such a conversion exists, User will contain the
2926/// user-defined conversion sequence that performs such a conversion
2927/// and this routine will return true. Otherwise, this routine returns
2928/// false and User is unspecified.
2929///
Douglas Gregor734d9862009-01-30 23:27:23 +00002930/// \param AllowExplicit true if the conversion should consider C++0x
2931/// "explicit" conversion functions as well as non-explicit conversion
2932/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002933static OverloadingResult
2934IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002935 UserDefinedConversionSequence &User,
2936 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002937 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002938 // Whether we will only visit constructors.
2939 bool ConstructorsOnly = false;
2940
2941 // If the type we are conversion to is a class type, enumerate its
2942 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002943 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002944 // C++ [over.match.ctor]p1:
2945 // When objects of class type are direct-initialized (8.5), or
2946 // copy-initialized from an expression of the same or a
2947 // derived class type (8.5), overload resolution selects the
2948 // constructor. [...] For copy-initialization, the candidate
2949 // functions are all the converting constructors (12.3.1) of
2950 // that class. The argument list is the expression-list within
2951 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002952 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002953 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002954 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002955 ConstructorsOnly = true;
2956
Douglas Gregord10099e2012-05-04 16:32:21 +00002957 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002958 // RequireCompleteType may have returned true due to some invalid decl
2959 // during template instantiation, but ToType may be complete enough now
2960 // to try to recover.
2961 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002962 // We're not going to find any constructors.
2963 } else if (CXXRecordDecl *ToRecordDecl
2964 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002965
2966 Expr **Args = &From;
2967 unsigned NumArgs = 1;
2968 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002969 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002970 // But first, see if there is an init-list-contructor that will work.
2971 OverloadingResult Result = IsInitializerListConstructorConversion(
2972 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2973 if (Result != OR_No_Viable_Function)
2974 return Result;
2975 // Never mind.
2976 CandidateSet.clear();
2977
2978 // If we're list-initializing, we pass the individual elements as
2979 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002980 Args = InitList->getInits();
2981 NumArgs = InitList->getNumInits();
2982 ListInitializing = true;
2983 }
2984
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002985 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002986 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002987 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002988 NamedDecl *D = *Con;
2989 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2990
Douglas Gregordec06662009-08-21 18:42:58 +00002991 // Find the constructor (which may be a template).
2992 CXXConstructorDecl *Constructor = 0;
2993 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002994 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002995 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002996 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002997 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2998 else
John McCall9aa472c2010-03-19 07:35:19 +00002999 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003000
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003001 bool Usable = !Constructor->isInvalidDecl();
3002 if (ListInitializing)
3003 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3004 else
3005 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3006 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003007 bool SuppressUserConversions = !ConstructorsOnly;
3008 if (SuppressUserConversions && ListInitializing) {
3009 SuppressUserConversions = false;
3010 if (NumArgs == 1) {
3011 // If the first argument is (a reference to) the target type,
3012 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003013 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3014 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003015 }
3016 }
Douglas Gregordec06662009-08-21 18:42:58 +00003017 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003018 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3019 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003020 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003021 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003022 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003023 // Allow one user-defined conversion when user specifies a
3024 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003025 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003026 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003027 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003028 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003029 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003030 }
3031 }
3032
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003033 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003034 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003035 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003036 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003037 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003038 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003039 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003040 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3041 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003042 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003043 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003044 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003045 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003046 DeclAccessPair FoundDecl = I.getPair();
3047 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003048 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3049 if (isa<UsingShadowDecl>(D))
3050 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3051
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003052 CXXConversionDecl *Conv;
3053 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003054 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3055 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003056 else
John McCall32daa422010-03-31 01:36:47 +00003057 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003058
3059 if (AllowExplicit || !Conv->isExplicit()) {
3060 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003061 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3062 ActingContext, From, ToType,
3063 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003064 else
John McCall120d63c2010-08-24 20:38:10 +00003065 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3066 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003067 }
3068 }
3069 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003070 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003071
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003072 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3073
Douglas Gregor60d62c22008-10-31 16:23:19 +00003074 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003075 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003076 case OR_Success:
3077 // Record the standard conversion we used and the conversion function.
3078 if (CXXConstructorDecl *Constructor
3079 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003080 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003081
John McCall120d63c2010-08-24 20:38:10 +00003082 // C++ [over.ics.user]p1:
3083 // If the user-defined conversion is specified by a
3084 // constructor (12.3.1), the initial standard conversion
3085 // sequence converts the source type to the type required by
3086 // the argument of the constructor.
3087 //
3088 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003089 if (isa<InitListExpr>(From)) {
3090 // Initializer lists don't have conversions as such.
3091 User.Before.setAsIdentityConversion();
3092 } else {
3093 if (Best->Conversions[0].isEllipsis())
3094 User.EllipsisConversion = true;
3095 else {
3096 User.Before = Best->Conversions[0].Standard;
3097 User.EllipsisConversion = false;
3098 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003099 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003100 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003101 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003102 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003103 User.After.setAsIdentityConversion();
3104 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3105 User.After.setAllToTypes(ToType);
3106 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003107 }
3108 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003109 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003110 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003111
John McCall120d63c2010-08-24 20:38:10 +00003112 // C++ [over.ics.user]p1:
3113 //
3114 // [...] If the user-defined conversion is specified by a
3115 // conversion function (12.3.2), the initial standard
3116 // conversion sequence converts the source type to the
3117 // implicit object parameter of the conversion function.
3118 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003119 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003120 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003121 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003122 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003123
John McCall120d63c2010-08-24 20:38:10 +00003124 // C++ [over.ics.user]p2:
3125 // The second standard conversion sequence converts the
3126 // result of the user-defined conversion to the target type
3127 // for the sequence. Since an implicit conversion sequence
3128 // is an initialization, the special rules for
3129 // initialization by user-defined conversion apply when
3130 // selecting the best user-defined conversion for a
3131 // user-defined conversion sequence (see 13.3.3 and
3132 // 13.3.3.1).
3133 User.After = Best->FinalConversion;
3134 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003135 }
David Blaikie7530c032012-01-17 06:56:22 +00003136 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003137
John McCall120d63c2010-08-24 20:38:10 +00003138 case OR_No_Viable_Function:
3139 return OR_No_Viable_Function;
3140 case OR_Deleted:
3141 // No conversion here! We're done.
3142 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003143
John McCall120d63c2010-08-24 20:38:10 +00003144 case OR_Ambiguous:
3145 return OR_Ambiguous;
3146 }
3147
David Blaikie7530c032012-01-17 06:56:22 +00003148 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003149}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003151bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003152Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003153 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003154 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003155 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003156 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003157 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003158 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003159 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003160 diag::err_typecheck_ambiguous_condition)
3161 << From->getType() << ToType << From->getSourceRange();
3162 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003163 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003164 diag::err_typecheck_nonviable_condition)
3165 << From->getType() << ToType << From->getSourceRange();
3166 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003167 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003168 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003169 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003170}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003171
Douglas Gregorb734e242012-02-22 17:32:19 +00003172/// \brief Compare the user-defined conversion functions or constructors
3173/// of two user-defined conversion sequences to determine whether any ordering
3174/// is possible.
3175static ImplicitConversionSequence::CompareKind
3176compareConversionFunctions(Sema &S,
3177 FunctionDecl *Function1,
3178 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003179 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003180 return ImplicitConversionSequence::Indistinguishable;
3181
3182 // Objective-C++:
3183 // If both conversion functions are implicitly-declared conversions from
3184 // a lambda closure type to a function pointer and a block pointer,
3185 // respectively, always prefer the conversion to a function pointer,
3186 // because the function pointer is more lightweight and is more likely
3187 // to keep code working.
3188 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3189 if (!Conv1)
3190 return ImplicitConversionSequence::Indistinguishable;
3191
3192 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3193 if (!Conv2)
3194 return ImplicitConversionSequence::Indistinguishable;
3195
3196 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3197 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3198 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3199 if (Block1 != Block2)
3200 return Block1? ImplicitConversionSequence::Worse
3201 : ImplicitConversionSequence::Better;
3202 }
3203
3204 return ImplicitConversionSequence::Indistinguishable;
3205}
3206
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003207/// CompareImplicitConversionSequences - Compare two implicit
3208/// conversion sequences to determine whether one is better than the
3209/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003210static ImplicitConversionSequence::CompareKind
3211CompareImplicitConversionSequences(Sema &S,
3212 const ImplicitConversionSequence& ICS1,
3213 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003214{
3215 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3216 // conversion sequences (as defined in 13.3.3.1)
3217 // -- a standard conversion sequence (13.3.3.1.1) is a better
3218 // conversion sequence than a user-defined conversion sequence or
3219 // an ellipsis conversion sequence, and
3220 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3221 // conversion sequence than an ellipsis conversion sequence
3222 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003223 //
John McCall1d318332010-01-12 00:44:57 +00003224 // C++0x [over.best.ics]p10:
3225 // For the purpose of ranking implicit conversion sequences as
3226 // described in 13.3.3.2, the ambiguous conversion sequence is
3227 // treated as a user-defined sequence that is indistinguishable
3228 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003229 if (ICS1.getKindRank() < ICS2.getKindRank())
3230 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003231 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003232 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003233
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003234 // The following checks require both conversion sequences to be of
3235 // the same kind.
3236 if (ICS1.getKind() != ICS2.getKind())
3237 return ImplicitConversionSequence::Indistinguishable;
3238
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003239 ImplicitConversionSequence::CompareKind Result =
3240 ImplicitConversionSequence::Indistinguishable;
3241
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003242 // Two implicit conversion sequences of the same form are
3243 // indistinguishable conversion sequences unless one of the
3244 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003245 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003246 Result = CompareStandardConversionSequences(S,
3247 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003248 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003249 // User-defined conversion sequence U1 is a better conversion
3250 // sequence than another user-defined conversion sequence U2 if
3251 // they contain the same user-defined conversion function or
3252 // constructor and if the second standard conversion sequence of
3253 // U1 is better than the second standard conversion sequence of
3254 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003255 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003256 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003257 Result = CompareStandardConversionSequences(S,
3258 ICS1.UserDefined.After,
3259 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003260 else
3261 Result = compareConversionFunctions(S,
3262 ICS1.UserDefined.ConversionFunction,
3263 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003264 }
3265
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003266 // List-initialization sequence L1 is a better conversion sequence than
3267 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3268 // for some X and L2 does not.
3269 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003270 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003271 ICS1.isListInitializationSequence() &&
3272 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003273 if (ICS1.isStdInitializerListElement() &&
3274 !ICS2.isStdInitializerListElement())
3275 return ImplicitConversionSequence::Better;
3276 if (!ICS1.isStdInitializerListElement() &&
3277 ICS2.isStdInitializerListElement())
3278 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003279 }
3280
3281 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003282}
3283
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003284static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3285 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3286 Qualifiers Quals;
3287 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003289 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003291 return Context.hasSameUnqualifiedType(T1, T2);
3292}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003293
Douglas Gregorad323a82010-01-27 03:51:04 +00003294// Per 13.3.3.2p3, compare the given standard conversion sequences to
3295// determine if one is a proper subset of the other.
3296static ImplicitConversionSequence::CompareKind
3297compareStandardConversionSubsets(ASTContext &Context,
3298 const StandardConversionSequence& SCS1,
3299 const StandardConversionSequence& SCS2) {
3300 ImplicitConversionSequence::CompareKind Result
3301 = ImplicitConversionSequence::Indistinguishable;
3302
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003304 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003305 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3306 return ImplicitConversionSequence::Better;
3307 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3308 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003309
Douglas Gregorad323a82010-01-27 03:51:04 +00003310 if (SCS1.Second != SCS2.Second) {
3311 if (SCS1.Second == ICK_Identity)
3312 Result = ImplicitConversionSequence::Better;
3313 else if (SCS2.Second == ICK_Identity)
3314 Result = ImplicitConversionSequence::Worse;
3315 else
3316 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003317 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003318 return ImplicitConversionSequence::Indistinguishable;
3319
3320 if (SCS1.Third == SCS2.Third) {
3321 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3322 : ImplicitConversionSequence::Indistinguishable;
3323 }
3324
3325 if (SCS1.Third == ICK_Identity)
3326 return Result == ImplicitConversionSequence::Worse
3327 ? ImplicitConversionSequence::Indistinguishable
3328 : ImplicitConversionSequence::Better;
3329
3330 if (SCS2.Third == ICK_Identity)
3331 return Result == ImplicitConversionSequence::Better
3332 ? ImplicitConversionSequence::Indistinguishable
3333 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334
Douglas Gregorad323a82010-01-27 03:51:04 +00003335 return ImplicitConversionSequence::Indistinguishable;
3336}
3337
Douglas Gregor440a4832011-01-26 14:52:12 +00003338/// \brief Determine whether one of the given reference bindings is better
3339/// than the other based on what kind of bindings they are.
3340static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3341 const StandardConversionSequence &SCS2) {
3342 // C++0x [over.ics.rank]p3b4:
3343 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3344 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003345 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003346 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003348 // reference*.
3349 //
3350 // FIXME: Rvalue references. We're going rogue with the above edits,
3351 // because the semantics in the current C++0x working paper (N3225 at the
3352 // time of this writing) break the standard definition of std::forward
3353 // and std::reference_wrapper when dealing with references to functions.
3354 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003355 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3356 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3357 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358
Douglas Gregor440a4832011-01-26 14:52:12 +00003359 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3360 SCS2.IsLvalueReference) ||
3361 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3362 !SCS2.IsLvalueReference);
3363}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003365/// CompareStandardConversionSequences - Compare two standard
3366/// conversion sequences to determine whether one is better than the
3367/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003368static ImplicitConversionSequence::CompareKind
3369CompareStandardConversionSequences(Sema &S,
3370 const StandardConversionSequence& SCS1,
3371 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003372{
3373 // Standard conversion sequence S1 is a better conversion sequence
3374 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3375
3376 // -- S1 is a proper subsequence of S2 (comparing the conversion
3377 // sequences in the canonical form defined by 13.3.3.1.1,
3378 // excluding any Lvalue Transformation; the identity conversion
3379 // sequence is considered to be a subsequence of any
3380 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003381 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003382 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003383 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003384
3385 // -- the rank of S1 is better than the rank of S2 (by the rules
3386 // defined below), or, if not that,
3387 ImplicitConversionRank Rank1 = SCS1.getRank();
3388 ImplicitConversionRank Rank2 = SCS2.getRank();
3389 if (Rank1 < Rank2)
3390 return ImplicitConversionSequence::Better;
3391 else if (Rank2 < Rank1)
3392 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003393
Douglas Gregor57373262008-10-22 14:17:15 +00003394 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3395 // are indistinguishable unless one of the following rules
3396 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Douglas Gregor57373262008-10-22 14:17:15 +00003398 // A conversion that is not a conversion of a pointer, or
3399 // pointer to member, to bool is better than another conversion
3400 // that is such a conversion.
3401 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3402 return SCS2.isPointerConversionToBool()
3403 ? ImplicitConversionSequence::Better
3404 : ImplicitConversionSequence::Worse;
3405
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003406 // C++ [over.ics.rank]p4b2:
3407 //
3408 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003409 // conversion of B* to A* is better than conversion of B* to
3410 // void*, and conversion of A* to void* is better than conversion
3411 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003412 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003413 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003414 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003415 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003416 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3417 // Exactly one of the conversion sequences is a conversion to
3418 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003419 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3420 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003421 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3422 // Neither conversion sequence converts to a void pointer; compare
3423 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003424 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003425 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003426 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003427 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3428 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003429 // Both conversion sequences are conversions to void
3430 // pointers. Compare the source types to determine if there's an
3431 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003432 QualType FromType1 = SCS1.getFromType();
3433 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003434
3435 // Adjust the types we're converting from via the array-to-pointer
3436 // conversion, if we need to.
3437 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003438 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003439 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003440 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003441
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003442 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3443 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003444
John McCall120d63c2010-08-24 20:38:10 +00003445 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003446 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003447 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003448 return ImplicitConversionSequence::Worse;
3449
3450 // Objective-C++: If one interface is more specific than the
3451 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003452 const ObjCObjectPointerType* FromObjCPtr1
3453 = FromType1->getAs<ObjCObjectPointerType>();
3454 const ObjCObjectPointerType* FromObjCPtr2
3455 = FromType2->getAs<ObjCObjectPointerType>();
3456 if (FromObjCPtr1 && FromObjCPtr2) {
3457 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3458 FromObjCPtr2);
3459 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3460 FromObjCPtr1);
3461 if (AssignLeft != AssignRight) {
3462 return AssignLeft? ImplicitConversionSequence::Better
3463 : ImplicitConversionSequence::Worse;
3464 }
Douglas Gregor01919692009-12-13 21:37:05 +00003465 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003466 }
Douglas Gregor57373262008-10-22 14:17:15 +00003467
3468 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3469 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003470 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003471 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003472 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003473
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003474 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003475 // Check for a better reference binding based on the kind of bindings.
3476 if (isBetterReferenceBindingKind(SCS1, SCS2))
3477 return ImplicitConversionSequence::Better;
3478 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3479 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003480
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003481 // C++ [over.ics.rank]p3b4:
3482 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3483 // which the references refer are the same type except for
3484 // top-level cv-qualifiers, and the type to which the reference
3485 // initialized by S2 refers is more cv-qualified than the type
3486 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003487 QualType T1 = SCS1.getToType(2);
3488 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003489 T1 = S.Context.getCanonicalType(T1);
3490 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003491 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003492 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3493 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003494 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003495 // Objective-C++ ARC: If the references refer to objects with different
3496 // lifetimes, prefer bindings that don't change lifetime.
3497 if (SCS1.ObjCLifetimeConversionBinding !=
3498 SCS2.ObjCLifetimeConversionBinding) {
3499 return SCS1.ObjCLifetimeConversionBinding
3500 ? ImplicitConversionSequence::Worse
3501 : ImplicitConversionSequence::Better;
3502 }
3503
Chandler Carruth6df868e2010-12-12 08:17:55 +00003504 // If the type is an array type, promote the element qualifiers to the
3505 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003506 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003507 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003508 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003509 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003510 if (T2.isMoreQualifiedThan(T1))
3511 return ImplicitConversionSequence::Better;
3512 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003513 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003514 }
3515 }
Douglas Gregor57373262008-10-22 14:17:15 +00003516
Francois Pichet1c98d622011-09-18 21:37:37 +00003517 // In Microsoft mode, prefer an integral conversion to a
3518 // floating-to-integral conversion if the integral conversion
3519 // is between types of the same size.
3520 // For example:
3521 // void f(float);
3522 // void f(int);
3523 // int main {
3524 // long a;
3525 // f(a);
3526 // }
3527 // Here, MSVC will call f(int) instead of generating a compile error
3528 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003529 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003530 SCS1.Second == ICK_Integral_Conversion &&
3531 SCS2.Second == ICK_Floating_Integral &&
3532 S.Context.getTypeSize(SCS1.getFromType()) ==
3533 S.Context.getTypeSize(SCS1.getToType(2)))
3534 return ImplicitConversionSequence::Better;
3535
Douglas Gregor57373262008-10-22 14:17:15 +00003536 return ImplicitConversionSequence::Indistinguishable;
3537}
3538
3539/// CompareQualificationConversions - Compares two standard conversion
3540/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003541/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3542ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003543CompareQualificationConversions(Sema &S,
3544 const StandardConversionSequence& SCS1,
3545 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003546 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003547 // -- S1 and S2 differ only in their qualification conversion and
3548 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3549 // cv-qualification signature of type T1 is a proper subset of
3550 // the cv-qualification signature of type T2, and S1 is not the
3551 // deprecated string literal array-to-pointer conversion (4.2).
3552 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3553 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3554 return ImplicitConversionSequence::Indistinguishable;
3555
3556 // FIXME: the example in the standard doesn't use a qualification
3557 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003558 QualType T1 = SCS1.getToType(2);
3559 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003560 T1 = S.Context.getCanonicalType(T1);
3561 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003562 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003563 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3564 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003565
3566 // If the types are the same, we won't learn anything by unwrapped
3567 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003568 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003569 return ImplicitConversionSequence::Indistinguishable;
3570
Chandler Carruth28e318c2009-12-29 07:16:59 +00003571 // If the type is an array type, promote the element qualifiers to the type
3572 // for comparison.
3573 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003574 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003575 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003576 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003577
Mike Stump1eb44332009-09-09 15:08:12 +00003578 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003579 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003580
3581 // Objective-C++ ARC:
3582 // Prefer qualification conversions not involving a change in lifetime
3583 // to qualification conversions that do not change lifetime.
3584 if (SCS1.QualificationIncludesObjCLifetime !=
3585 SCS2.QualificationIncludesObjCLifetime) {
3586 Result = SCS1.QualificationIncludesObjCLifetime
3587 ? ImplicitConversionSequence::Worse
3588 : ImplicitConversionSequence::Better;
3589 }
3590
John McCall120d63c2010-08-24 20:38:10 +00003591 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003592 // Within each iteration of the loop, we check the qualifiers to
3593 // determine if this still looks like a qualification
3594 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003595 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003596 // until there are no more pointers or pointers-to-members left
3597 // to unwrap. This essentially mimics what
3598 // IsQualificationConversion does, but here we're checking for a
3599 // strict subset of qualifiers.
3600 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3601 // The qualifiers are the same, so this doesn't tell us anything
3602 // about how the sequences rank.
3603 ;
3604 else if (T2.isMoreQualifiedThan(T1)) {
3605 // T1 has fewer qualifiers, so it could be the better sequence.
3606 if (Result == ImplicitConversionSequence::Worse)
3607 // Neither has qualifiers that are a subset of the other's
3608 // qualifiers.
3609 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Douglas Gregor57373262008-10-22 14:17:15 +00003611 Result = ImplicitConversionSequence::Better;
3612 } else if (T1.isMoreQualifiedThan(T2)) {
3613 // T2 has fewer qualifiers, so it could be the better sequence.
3614 if (Result == ImplicitConversionSequence::Better)
3615 // Neither has qualifiers that are a subset of the other's
3616 // qualifiers.
3617 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Douglas Gregor57373262008-10-22 14:17:15 +00003619 Result = ImplicitConversionSequence::Worse;
3620 } else {
3621 // Qualifiers are disjoint.
3622 return ImplicitConversionSequence::Indistinguishable;
3623 }
3624
3625 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003626 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003627 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003628 }
3629
Douglas Gregor57373262008-10-22 14:17:15 +00003630 // Check that the winning standard conversion sequence isn't using
3631 // the deprecated string literal array to pointer conversion.
3632 switch (Result) {
3633 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003634 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003635 Result = ImplicitConversionSequence::Indistinguishable;
3636 break;
3637
3638 case ImplicitConversionSequence::Indistinguishable:
3639 break;
3640
3641 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003642 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003643 Result = ImplicitConversionSequence::Indistinguishable;
3644 break;
3645 }
3646
3647 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003648}
3649
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003650/// CompareDerivedToBaseConversions - Compares two standard conversion
3651/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003652/// various kinds of derived-to-base conversions (C++
3653/// [over.ics.rank]p4b3). As part of these checks, we also look at
3654/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003655ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003656CompareDerivedToBaseConversions(Sema &S,
3657 const StandardConversionSequence& SCS1,
3658 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003659 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003660 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003661 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003662 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003663
3664 // Adjust the types we're converting from via the array-to-pointer
3665 // conversion, if we need to.
3666 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003667 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003668 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003669 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003670
3671 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003672 FromType1 = S.Context.getCanonicalType(FromType1);
3673 ToType1 = S.Context.getCanonicalType(ToType1);
3674 FromType2 = S.Context.getCanonicalType(FromType2);
3675 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003676
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003677 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003678 //
3679 // If class B is derived directly or indirectly from class A and
3680 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003681 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003682 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003683 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003684 SCS2.Second == ICK_Pointer_Conversion &&
3685 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3686 FromType1->isPointerType() && FromType2->isPointerType() &&
3687 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003688 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003689 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003690 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003691 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003692 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003693 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003694 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003695 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003696
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003697 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003698 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003699 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003700 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003701 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003702 return ImplicitConversionSequence::Worse;
3703 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003704
3705 // -- conversion of B* to A* is better than conversion of C* to A*,
3706 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003707 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003708 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003709 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003710 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003711 }
3712 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3713 SCS2.Second == ICK_Pointer_Conversion) {
3714 const ObjCObjectPointerType *FromPtr1
3715 = FromType1->getAs<ObjCObjectPointerType>();
3716 const ObjCObjectPointerType *FromPtr2
3717 = FromType2->getAs<ObjCObjectPointerType>();
3718 const ObjCObjectPointerType *ToPtr1
3719 = ToType1->getAs<ObjCObjectPointerType>();
3720 const ObjCObjectPointerType *ToPtr2
3721 = ToType2->getAs<ObjCObjectPointerType>();
3722
3723 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3724 // Apply the same conversion ranking rules for Objective-C pointer types
3725 // that we do for C++ pointers to class types. However, we employ the
3726 // Objective-C pseudo-subtyping relationship used for assignment of
3727 // Objective-C pointer types.
3728 bool FromAssignLeft
3729 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3730 bool FromAssignRight
3731 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3732 bool ToAssignLeft
3733 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3734 bool ToAssignRight
3735 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3736
3737 // A conversion to an a non-id object pointer type or qualified 'id'
3738 // type is better than a conversion to 'id'.
3739 if (ToPtr1->isObjCIdType() &&
3740 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3741 return ImplicitConversionSequence::Worse;
3742 if (ToPtr2->isObjCIdType() &&
3743 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3744 return ImplicitConversionSequence::Better;
3745
3746 // A conversion to a non-id object pointer type is better than a
3747 // conversion to a qualified 'id' type
3748 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3749 return ImplicitConversionSequence::Worse;
3750 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3751 return ImplicitConversionSequence::Better;
3752
3753 // A conversion to an a non-Class object pointer type or qualified 'Class'
3754 // type is better than a conversion to 'Class'.
3755 if (ToPtr1->isObjCClassType() &&
3756 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3757 return ImplicitConversionSequence::Worse;
3758 if (ToPtr2->isObjCClassType() &&
3759 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3760 return ImplicitConversionSequence::Better;
3761
3762 // A conversion to a non-Class object pointer type is better than a
3763 // conversion to a qualified 'Class' type.
3764 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3765 return ImplicitConversionSequence::Worse;
3766 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3767 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Douglas Gregor395cc372011-01-31 18:51:41 +00003769 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3770 if (S.Context.hasSameType(FromType1, FromType2) &&
3771 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3772 (ToAssignLeft != ToAssignRight))
3773 return ToAssignLeft? ImplicitConversionSequence::Worse
3774 : ImplicitConversionSequence::Better;
3775
3776 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3777 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3778 (FromAssignLeft != FromAssignRight))
3779 return FromAssignLeft? ImplicitConversionSequence::Better
3780 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003781 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003782 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003783
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003784 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003785 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3786 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3787 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003789 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003791 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003793 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003794 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003795 ToType2->getAs<MemberPointerType>();
3796 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3797 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3798 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3799 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3800 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3801 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3802 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3803 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003804 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003805 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003806 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003807 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003808 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003809 return ImplicitConversionSequence::Better;
3810 }
3811 // conversion of B::* to C::* is better than conversion of A::* to C::*
3812 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003813 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003814 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003815 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003816 return ImplicitConversionSequence::Worse;
3817 }
3818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003820 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003821 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003822 // -- binding of an expression of type C to a reference of type
3823 // B& is better than binding an expression of type C to a
3824 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003825 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3826 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3827 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003828 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003829 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003830 return ImplicitConversionSequence::Worse;
3831 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003832
Douglas Gregor225c41e2008-11-03 19:09:14 +00003833 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003834 // -- binding of an expression of type B to a reference of type
3835 // A& is better than binding an expression of type C to a
3836 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003837 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3838 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3839 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003840 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003841 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003842 return ImplicitConversionSequence::Worse;
3843 }
3844 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003845
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003846 return ImplicitConversionSequence::Indistinguishable;
3847}
3848
Douglas Gregorabe183d2010-04-13 16:31:36 +00003849/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3850/// determine whether they are reference-related,
3851/// reference-compatible, reference-compatible with added
3852/// qualification, or incompatible, for use in C++ initialization by
3853/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3854/// type, and the first type (T1) is the pointee type of the reference
3855/// type being initialized.
3856Sema::ReferenceCompareResult
3857Sema::CompareReferenceRelationship(SourceLocation Loc,
3858 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003859 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003860 bool &ObjCConversion,
3861 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003862 assert(!OrigT1->isReferenceType() &&
3863 "T1 must be the pointee type of the reference type");
3864 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3865
3866 QualType T1 = Context.getCanonicalType(OrigT1);
3867 QualType T2 = Context.getCanonicalType(OrigT2);
3868 Qualifiers T1Quals, T2Quals;
3869 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3870 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3871
3872 // C++ [dcl.init.ref]p4:
3873 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3874 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3875 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003876 DerivedToBase = false;
3877 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003878 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003879 if (UnqualT1 == UnqualT2) {
3880 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003881 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003882 IsDerivedFrom(UnqualT2, UnqualT1))
3883 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003884 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3885 UnqualT2->isObjCObjectOrInterfaceType() &&
3886 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3887 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003888 else
3889 return Ref_Incompatible;
3890
3891 // At this point, we know that T1 and T2 are reference-related (at
3892 // least).
3893
3894 // If the type is an array type, promote the element qualifiers to the type
3895 // for comparison.
3896 if (isa<ArrayType>(T1) && T1Quals)
3897 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3898 if (isa<ArrayType>(T2) && T2Quals)
3899 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3900
3901 // C++ [dcl.init.ref]p4:
3902 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3903 // reference-related to T2 and cv1 is the same cv-qualification
3904 // as, or greater cv-qualification than, cv2. For purposes of
3905 // overload resolution, cases for which cv1 is greater
3906 // cv-qualification than cv2 are identified as
3907 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003908 //
3909 // Note that we also require equivalence of Objective-C GC and address-space
3910 // qualifiers when performing these computations, so that e.g., an int in
3911 // address space 1 is not reference-compatible with an int in address
3912 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003913 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3914 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3915 T1Quals.removeObjCLifetime();
3916 T2Quals.removeObjCLifetime();
3917 ObjCLifetimeConversion = true;
3918 }
3919
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003920 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003921 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003922 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003923 return Ref_Compatible_With_Added_Qualification;
3924 else
3925 return Ref_Related;
3926}
3927
Douglas Gregor604eb652010-08-11 02:15:33 +00003928/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003929/// with DeclType. Return true if something definite is found.
3930static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003931FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3932 QualType DeclType, SourceLocation DeclLoc,
3933 Expr *Init, QualType T2, bool AllowRvalues,
3934 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003935 assert(T2->isRecordType() && "Can only find conversions of record types.");
3936 CXXRecordDecl *T2RecordDecl
3937 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3938
3939 OverloadCandidateSet CandidateSet(DeclLoc);
3940 const UnresolvedSetImpl *Conversions
3941 = T2RecordDecl->getVisibleConversionFunctions();
3942 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3943 E = Conversions->end(); I != E; ++I) {
3944 NamedDecl *D = *I;
3945 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3946 if (isa<UsingShadowDecl>(D))
3947 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3948
3949 FunctionTemplateDecl *ConvTemplate
3950 = dyn_cast<FunctionTemplateDecl>(D);
3951 CXXConversionDecl *Conv;
3952 if (ConvTemplate)
3953 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3954 else
3955 Conv = cast<CXXConversionDecl>(D);
3956
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003957 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003958 // explicit conversions, skip it.
3959 if (!AllowExplicit && Conv->isExplicit())
3960 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961
Douglas Gregor604eb652010-08-11 02:15:33 +00003962 if (AllowRvalues) {
3963 bool DerivedToBase = false;
3964 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003965 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003966
3967 // If we are initializing an rvalue reference, don't permit conversion
3968 // functions that return lvalues.
3969 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3970 const ReferenceType *RefType
3971 = Conv->getConversionType()->getAs<LValueReferenceType>();
3972 if (RefType && !RefType->getPointeeType()->isFunctionType())
3973 continue;
3974 }
3975
Douglas Gregor604eb652010-08-11 02:15:33 +00003976 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003977 S.CompareReferenceRelationship(
3978 DeclLoc,
3979 Conv->getConversionType().getNonReferenceType()
3980 .getUnqualifiedType(),
3981 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003982 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003983 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003984 continue;
3985 } else {
3986 // If the conversion function doesn't return a reference type,
3987 // it can't be considered for this conversion. An rvalue reference
3988 // is only acceptable if its referencee is a function type.
3989
3990 const ReferenceType *RefType =
3991 Conv->getConversionType()->getAs<ReferenceType>();
3992 if (!RefType ||
3993 (!RefType->isLValueReferenceType() &&
3994 !RefType->getPointeeType()->isFunctionType()))
3995 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997
Douglas Gregor604eb652010-08-11 02:15:33 +00003998 if (ConvTemplate)
3999 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004000 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004001 else
4002 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004003 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004004 }
4005
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004006 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4007
Sebastian Redl4680bf22010-06-30 18:13:39 +00004008 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004009 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004010 case OR_Success:
4011 // C++ [over.ics.ref]p1:
4012 //
4013 // [...] If the parameter binds directly to the result of
4014 // applying a conversion function to the argument
4015 // expression, the implicit conversion sequence is a
4016 // user-defined conversion sequence (13.3.3.1.2), with the
4017 // second standard conversion sequence either an identity
4018 // conversion or, if the conversion function returns an
4019 // entity of a type that is a derived class of the parameter
4020 // type, a derived-to-base Conversion.
4021 if (!Best->FinalConversion.DirectBinding)
4022 return false;
4023
Chandler Carruth25ca4212011-02-25 19:41:05 +00004024 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004025 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004026 ICS.setUserDefined();
4027 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4028 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004029 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004030 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004031 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004032 ICS.UserDefined.EllipsisConversion = false;
4033 assert(ICS.UserDefined.After.ReferenceBinding &&
4034 ICS.UserDefined.After.DirectBinding &&
4035 "Expected a direct reference binding!");
4036 return true;
4037
4038 case OR_Ambiguous:
4039 ICS.setAmbiguous();
4040 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4041 Cand != CandidateSet.end(); ++Cand)
4042 if (Cand->Viable)
4043 ICS.Ambiguous.addConversion(Cand->Function);
4044 return true;
4045
4046 case OR_No_Viable_Function:
4047 case OR_Deleted:
4048 // There was no suitable conversion, or we found a deleted
4049 // conversion; continue with other checks.
4050 return false;
4051 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004052
David Blaikie7530c032012-01-17 06:56:22 +00004053 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004054}
4055
Douglas Gregorabe183d2010-04-13 16:31:36 +00004056/// \brief Compute an implicit conversion sequence for reference
4057/// initialization.
4058static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004059TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004060 SourceLocation DeclLoc,
4061 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004062 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004063 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4064
4065 // Most paths end in a failed conversion.
4066 ImplicitConversionSequence ICS;
4067 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4068
4069 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4070 QualType T2 = Init->getType();
4071
4072 // If the initializer is the address of an overloaded function, try
4073 // to resolve the overloaded function. If all goes well, T2 is the
4074 // type of the resulting function.
4075 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4076 DeclAccessPair Found;
4077 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4078 false, Found))
4079 T2 = Fn->getType();
4080 }
4081
4082 // Compute some basic properties of the types and the initializer.
4083 bool isRValRef = DeclType->isRValueReferenceType();
4084 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004085 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004086 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004087 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004088 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004089 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004090 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004091
Douglas Gregorabe183d2010-04-13 16:31:36 +00004092
Sebastian Redl4680bf22010-06-30 18:13:39 +00004093 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004094 // A reference to type "cv1 T1" is initialized by an expression
4095 // of type "cv2 T2" as follows:
4096
Sebastian Redl4680bf22010-06-30 18:13:39 +00004097 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004098 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004099 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4100 // reference-compatible with "cv2 T2," or
4101 //
4102 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4103 if (InitCategory.isLValue() &&
4104 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004105 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004106 // When a parameter of reference type binds directly (8.5.3)
4107 // to an argument expression, the implicit conversion sequence
4108 // is the identity conversion, unless the argument expression
4109 // has a type that is a derived class of the parameter type,
4110 // in which case the implicit conversion sequence is a
4111 // derived-to-base Conversion (13.3.3.1).
4112 ICS.setStandard();
4113 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004114 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4115 : ObjCConversion? ICK_Compatible_Conversion
4116 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117 ICS.Standard.Third = ICK_Identity;
4118 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4119 ICS.Standard.setToType(0, T2);
4120 ICS.Standard.setToType(1, T1);
4121 ICS.Standard.setToType(2, T1);
4122 ICS.Standard.ReferenceBinding = true;
4123 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004124 ICS.Standard.IsLvalueReference = !isRValRef;
4125 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4126 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004127 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004128 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004129 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004130
Sebastian Redl4680bf22010-06-30 18:13:39 +00004131 // Nothing more to do: the inaccessibility/ambiguity check for
4132 // derived-to-base conversions is suppressed when we're
4133 // computing the implicit conversion sequence (C++
4134 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004135 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004136 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004137
Sebastian Redl4680bf22010-06-30 18:13:39 +00004138 // -- has a class type (i.e., T2 is a class type), where T1 is
4139 // not reference-related to T2, and can be implicitly
4140 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4141 // is reference-compatible with "cv3 T3" 92) (this
4142 // conversion is selected by enumerating the applicable
4143 // conversion functions (13.3.1.6) and choosing the best
4144 // one through overload resolution (13.3)),
4145 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004147 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004148 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4149 Init, T2, /*AllowRvalues=*/false,
4150 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004151 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004152 }
4153 }
4154
Sebastian Redl4680bf22010-06-30 18:13:39 +00004155 // -- Otherwise, the reference shall be an lvalue reference to a
4156 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004157 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004158 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004159 // We actually handle one oddity of C++ [over.ics.ref] at this
4160 // point, which is that, due to p2 (which short-circuits reference
4161 // binding by only attempting a simple conversion for non-direct
4162 // bindings) and p3's strange wording, we allow a const volatile
4163 // reference to bind to an rvalue. Hence the check for the presence
4164 // of "const" rather than checking for "const" being the only
4165 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004166 // This is also the point where rvalue references and lvalue inits no longer
4167 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004168 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004169 return ICS;
4170
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004171 // -- If the initializer expression
4172 //
4173 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004174 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004175 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4176 (InitCategory.isXValue() ||
4177 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4178 (InitCategory.isLValue() && T2->isFunctionType()))) {
4179 ICS.setStandard();
4180 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004181 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004182 : ObjCConversion? ICK_Compatible_Conversion
4183 : ICK_Identity;
4184 ICS.Standard.Third = ICK_Identity;
4185 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4186 ICS.Standard.setToType(0, T2);
4187 ICS.Standard.setToType(1, T1);
4188 ICS.Standard.setToType(2, T1);
4189 ICS.Standard.ReferenceBinding = true;
4190 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4191 // binding unless we're binding to a class prvalue.
4192 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4193 // allow the use of rvalue references in C++98/03 for the benefit of
4194 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004195 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004196 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004197 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004198 ICS.Standard.IsLvalueReference = !isRValRef;
4199 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004200 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004201 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004202 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004203 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004205 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004207 // -- has a class type (i.e., T2 is a class type), where T1 is not
4208 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209 // an xvalue, class prvalue, or function lvalue of type
4210 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004211 // "cv3 T3",
4212 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004213 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004214 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004216 // class subobject).
4217 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004218 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004219 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4220 Init, T2, /*AllowRvalues=*/true,
4221 AllowExplicit)) {
4222 // In the second case, if the reference is an rvalue reference
4223 // and the second standard conversion sequence of the
4224 // user-defined conversion sequence includes an lvalue-to-rvalue
4225 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004227 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4228 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4229
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004230 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232
Douglas Gregorabe183d2010-04-13 16:31:36 +00004233 // -- Otherwise, a temporary of type "cv1 T1" is created and
4234 // initialized from the initializer expression using the
4235 // rules for a non-reference copy initialization (8.5). The
4236 // reference is then bound to the temporary. If T1 is
4237 // reference-related to T2, cv1 must be the same
4238 // cv-qualification as, or greater cv-qualification than,
4239 // cv2; otherwise, the program is ill-formed.
4240 if (RefRelationship == Sema::Ref_Related) {
4241 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4242 // we would be reference-compatible or reference-compatible with
4243 // added qualification. But that wasn't the case, so the reference
4244 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004245 //
4246 // Note that we only want to check address spaces and cvr-qualifiers here.
4247 // ObjC GC and lifetime qualifiers aren't important.
4248 Qualifiers T1Quals = T1.getQualifiers();
4249 Qualifiers T2Quals = T2.getQualifiers();
4250 T1Quals.removeObjCGCAttr();
4251 T1Quals.removeObjCLifetime();
4252 T2Quals.removeObjCGCAttr();
4253 T2Quals.removeObjCLifetime();
4254 if (!T1Quals.compatiblyIncludes(T2Quals))
4255 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004256 }
4257
4258 // If at least one of the types is a class type, the types are not
4259 // related, and we aren't allowed any user conversions, the
4260 // reference binding fails. This case is important for breaking
4261 // recursion, since TryImplicitConversion below will attempt to
4262 // create a temporary through the use of a copy constructor.
4263 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4264 (T1->isRecordType() || T2->isRecordType()))
4265 return ICS;
4266
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004267 // If T1 is reference-related to T2 and the reference is an rvalue
4268 // reference, the initializer expression shall not be an lvalue.
4269 if (RefRelationship >= Sema::Ref_Related &&
4270 isRValRef && Init->Classify(S.Context).isLValue())
4271 return ICS;
4272
Douglas Gregorabe183d2010-04-13 16:31:36 +00004273 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004274 // When a parameter of reference type is not bound directly to
4275 // an argument expression, the conversion sequence is the one
4276 // required to convert the argument expression to the
4277 // underlying type of the reference according to
4278 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4279 // to copy-initializing a temporary of the underlying type with
4280 // the argument expression. Any difference in top-level
4281 // cv-qualification is subsumed by the initialization itself
4282 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004283 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4284 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004285 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004286 /*CStyle=*/false,
4287 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004288
4289 // Of course, that's still a reference binding.
4290 if (ICS.isStandard()) {
4291 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004292 ICS.Standard.IsLvalueReference = !isRValRef;
4293 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4294 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004295 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004296 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004297 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004298 // Don't allow rvalue references to bind to lvalues.
4299 if (DeclType->isRValueReferenceType()) {
4300 if (const ReferenceType *RefType
4301 = ICS.UserDefined.ConversionFunction->getResultType()
4302 ->getAs<LValueReferenceType>()) {
4303 if (!RefType->getPointeeType()->isFunctionType()) {
4304 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4305 DeclType);
4306 return ICS;
4307 }
4308 }
4309 }
4310
Douglas Gregorabe183d2010-04-13 16:31:36 +00004311 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004312 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4313 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4314 ICS.UserDefined.After.BindsToRvalue = true;
4315 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4316 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004317 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004318
Douglas Gregorabe183d2010-04-13 16:31:36 +00004319 return ICS;
4320}
4321
Sebastian Redl5405b812011-10-16 18:19:34 +00004322static ImplicitConversionSequence
4323TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4324 bool SuppressUserConversions,
4325 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004326 bool AllowObjCWritebackConversion,
4327 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004328
4329/// TryListConversion - Try to copy-initialize a value of type ToType from the
4330/// initializer list From.
4331static ImplicitConversionSequence
4332TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4333 bool SuppressUserConversions,
4334 bool InOverloadResolution,
4335 bool AllowObjCWritebackConversion) {
4336 // C++11 [over.ics.list]p1:
4337 // When an argument is an initializer list, it is not an expression and
4338 // special rules apply for converting it to a parameter type.
4339
4340 ImplicitConversionSequence Result;
4341 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004342 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004343
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004344 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004345 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004346 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004347 return Result;
4348
Sebastian Redl5405b812011-10-16 18:19:34 +00004349 // C++11 [over.ics.list]p2:
4350 // If the parameter type is std::initializer_list<X> or "array of X" and
4351 // all the elements can be implicitly converted to X, the implicit
4352 // conversion sequence is the worst conversion necessary to convert an
4353 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004354 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004355 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004356 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004357 X = S.Context.getBaseElementType(ToType);
4358 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004359 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004360 if (!X.isNull()) {
4361 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4362 Expr *Init = From->getInit(i);
4363 ImplicitConversionSequence ICS =
4364 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4365 InOverloadResolution,
4366 AllowObjCWritebackConversion);
4367 // If a single element isn't convertible, fail.
4368 if (ICS.isBad()) {
4369 Result = ICS;
4370 break;
4371 }
4372 // Otherwise, look for the worst conversion.
4373 if (Result.isBad() ||
4374 CompareImplicitConversionSequences(S, ICS, Result) ==
4375 ImplicitConversionSequence::Worse)
4376 Result = ICS;
4377 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004378
4379 // For an empty list, we won't have computed any conversion sequence.
4380 // Introduce the identity conversion sequence.
4381 if (From->getNumInits() == 0) {
4382 Result.setStandard();
4383 Result.Standard.setAsIdentityConversion();
4384 Result.Standard.setFromType(ToType);
4385 Result.Standard.setAllToTypes(ToType);
4386 }
4387
Sebastian Redlfe592282012-01-17 22:49:48 +00004388 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004389 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004390 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004391 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004392
4393 // C++11 [over.ics.list]p3:
4394 // Otherwise, if the parameter is a non-aggregate class X and overload
4395 // resolution chooses a single best constructor [...] the implicit
4396 // conversion sequence is a user-defined conversion sequence. If multiple
4397 // constructors are viable but none is better than the others, the
4398 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004399 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4400 // This function can deal with initializer lists.
4401 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4402 /*AllowExplicit=*/false,
4403 InOverloadResolution, /*CStyle=*/false,
4404 AllowObjCWritebackConversion);
4405 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004406 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004407 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004408
4409 // C++11 [over.ics.list]p4:
4410 // Otherwise, if the parameter has an aggregate type which can be
4411 // initialized from the initializer list [...] the implicit conversion
4412 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004413 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004414 // Type is an aggregate, argument is an init list. At this point it comes
4415 // down to checking whether the initialization works.
4416 // FIXME: Find out whether this parameter is consumed or not.
4417 InitializedEntity Entity =
4418 InitializedEntity::InitializeParameter(S.Context, ToType,
4419 /*Consumed=*/false);
4420 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4421 Result.setUserDefined();
4422 Result.UserDefined.Before.setAsIdentityConversion();
4423 // Initializer lists don't have a type.
4424 Result.UserDefined.Before.setFromType(QualType());
4425 Result.UserDefined.Before.setAllToTypes(QualType());
4426
4427 Result.UserDefined.After.setAsIdentityConversion();
4428 Result.UserDefined.After.setFromType(ToType);
4429 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004430 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004431 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004432 return Result;
4433 }
4434
4435 // C++11 [over.ics.list]p5:
4436 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004437 if (ToType->isReferenceType()) {
4438 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4439 // mention initializer lists in any way. So we go by what list-
4440 // initialization would do and try to extrapolate from that.
4441
4442 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4443
4444 // If the initializer list has a single element that is reference-related
4445 // to the parameter type, we initialize the reference from that.
4446 if (From->getNumInits() == 1) {
4447 Expr *Init = From->getInit(0);
4448
4449 QualType T2 = Init->getType();
4450
4451 // If the initializer is the address of an overloaded function, try
4452 // to resolve the overloaded function. If all goes well, T2 is the
4453 // type of the resulting function.
4454 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4455 DeclAccessPair Found;
4456 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4457 Init, ToType, false, Found))
4458 T2 = Fn->getType();
4459 }
4460
4461 // Compute some basic properties of the types and the initializer.
4462 bool dummy1 = false;
4463 bool dummy2 = false;
4464 bool dummy3 = false;
4465 Sema::ReferenceCompareResult RefRelationship
4466 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4467 dummy2, dummy3);
4468
4469 if (RefRelationship >= Sema::Ref_Related)
4470 return TryReferenceInit(S, Init, ToType,
4471 /*FIXME:*/From->getLocStart(),
4472 SuppressUserConversions,
4473 /*AllowExplicit=*/false);
4474 }
4475
4476 // Otherwise, we bind the reference to a temporary created from the
4477 // initializer list.
4478 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4479 InOverloadResolution,
4480 AllowObjCWritebackConversion);
4481 if (Result.isFailure())
4482 return Result;
4483 assert(!Result.isEllipsis() &&
4484 "Sub-initialization cannot result in ellipsis conversion.");
4485
4486 // Can we even bind to a temporary?
4487 if (ToType->isRValueReferenceType() ||
4488 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4489 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4490 Result.UserDefined.After;
4491 SCS.ReferenceBinding = true;
4492 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4493 SCS.BindsToRvalue = true;
4494 SCS.BindsToFunctionLvalue = false;
4495 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4496 SCS.ObjCLifetimeConversionBinding = false;
4497 } else
4498 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4499 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004500 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004501 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004502
4503 // C++11 [over.ics.list]p6:
4504 // Otherwise, if the parameter type is not a class:
4505 if (!ToType->isRecordType()) {
4506 // - if the initializer list has one element, the implicit conversion
4507 // sequence is the one required to convert the element to the
4508 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004509 unsigned NumInits = From->getNumInits();
4510 if (NumInits == 1)
4511 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4512 SuppressUserConversions,
4513 InOverloadResolution,
4514 AllowObjCWritebackConversion);
4515 // - if the initializer list has no elements, the implicit conversion
4516 // sequence is the identity conversion.
4517 else if (NumInits == 0) {
4518 Result.setStandard();
4519 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004520 Result.Standard.setFromType(ToType);
4521 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004522 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004523 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004524 return Result;
4525 }
4526
4527 // C++11 [over.ics.list]p7:
4528 // In all cases other than those enumerated above, no conversion is possible
4529 return Result;
4530}
4531
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004532/// TryCopyInitialization - Try to copy-initialize a value of type
4533/// ToType from the expression From. Return the implicit conversion
4534/// sequence required to pass this argument, which may be a bad
4535/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004536/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004537/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004538static ImplicitConversionSequence
4539TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004541 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004542 bool AllowObjCWritebackConversion,
4543 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004544 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4545 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4546 InOverloadResolution,AllowObjCWritebackConversion);
4547
Douglas Gregorabe183d2010-04-13 16:31:36 +00004548 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004549 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004550 /*FIXME:*/From->getLocStart(),
4551 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004552 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004553
John McCall120d63c2010-08-24 20:38:10 +00004554 return TryImplicitConversion(S, From, ToType,
4555 SuppressUserConversions,
4556 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004557 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004558 /*CStyle=*/false,
4559 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004560}
4561
Anna Zaksf3546ee2011-07-28 19:46:48 +00004562static bool TryCopyInitialization(const CanQualType FromQTy,
4563 const CanQualType ToQTy,
4564 Sema &S,
4565 SourceLocation Loc,
4566 ExprValueKind FromVK) {
4567 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4568 ImplicitConversionSequence ICS =
4569 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4570
4571 return !ICS.isBad();
4572}
4573
Douglas Gregor96176b32008-11-18 23:14:02 +00004574/// TryObjectArgumentInitialization - Try to initialize the object
4575/// parameter of the given member function (@c Method) from the
4576/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004577static ImplicitConversionSequence
4578TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004579 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004580 CXXMethodDecl *Method,
4581 CXXRecordDecl *ActingContext) {
4582 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004583 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4584 // const volatile object.
4585 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4586 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004587 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004588
4589 // Set up the conversion sequence as a "bad" conversion, to allow us
4590 // to exit early.
4591 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004592
4593 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004594 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004595 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004596 FromType = PT->getPointeeType();
4597
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004598 // When we had a pointer, it's implicitly dereferenced, so we
4599 // better have an lvalue.
4600 assert(FromClassification.isLValue());
4601 }
4602
Anders Carlssona552f7c2009-05-01 18:34:30 +00004603 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004604
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004605 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004606 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004607 // parameter is
4608 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004609 // - "lvalue reference to cv X" for functions declared without a
4610 // ref-qualifier or with the & ref-qualifier
4611 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004612 // ref-qualifier
4613 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004614 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004615 // cv-qualification on the member function declaration.
4616 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004617 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004618 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004619 // (C++ [over.match.funcs]p5). We perform a simplified version of
4620 // reference binding here, that allows class rvalues to bind to
4621 // non-constant references.
4622
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004623 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004624 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004625 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004626 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004627 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004628 ICS.setBad(BadConversionSequence::bad_qualifiers,
4629 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004630 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004631 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004632
4633 // Check that we have either the same type or a derived type. It
4634 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004635 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004636 ImplicitConversionKind SecondKind;
4637 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4638 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004639 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004640 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004641 else {
John McCallb1bdc622010-02-25 01:37:24 +00004642 ICS.setBad(BadConversionSequence::unrelated_class,
4643 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004644 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004645 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004646
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004647 // Check the ref-qualifier.
4648 switch (Method->getRefQualifier()) {
4649 case RQ_None:
4650 // Do nothing; we don't care about lvalueness or rvalueness.
4651 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004653 case RQ_LValue:
4654 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4655 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004656 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004657 ImplicitParamType);
4658 return ICS;
4659 }
4660 break;
4661
4662 case RQ_RValue:
4663 if (!FromClassification.isRValue()) {
4664 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004665 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004666 ImplicitParamType);
4667 return ICS;
4668 }
4669 break;
4670 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004671
Douglas Gregor96176b32008-11-18 23:14:02 +00004672 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004673 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004674 ICS.Standard.setAsIdentityConversion();
4675 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004676 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004677 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004678 ICS.Standard.ReferenceBinding = true;
4679 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004681 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004682 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4683 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4684 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004685 return ICS;
4686}
4687
4688/// PerformObjectArgumentInitialization - Perform initialization of
4689/// the implicit object parameter for the given Method with the given
4690/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004691ExprResult
4692Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004693 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004694 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004695 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004696 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004697 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004698 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004700 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004701 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004702 FromRecordType = PT->getPointeeType();
4703 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004705 } else {
4706 FromRecordType = From->getType();
4707 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004708 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004709 }
4710
John McCall701c89e2009-12-03 04:06:58 +00004711 // Note that we always use the true parent context when performing
4712 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004713 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004714 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4715 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004716 if (ICS.isBad()) {
4717 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4718 Qualifiers FromQs = FromRecordType.getQualifiers();
4719 Qualifiers ToQs = DestType.getQualifiers();
4720 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4721 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004722 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004723 diag::err_member_function_call_bad_cvr)
4724 << Method->getDeclName() << FromRecordType << (CVR - 1)
4725 << From->getSourceRange();
4726 Diag(Method->getLocation(), diag::note_previous_decl)
4727 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004728 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004729 }
4730 }
4731
Daniel Dunbar96a00142012-03-09 18:35:03 +00004732 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004733 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004734 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004735 }
Mike Stump1eb44332009-09-09 15:08:12 +00004736
John Wiegley429bb272011-04-08 18:41:53 +00004737 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4738 ExprResult FromRes =
4739 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4740 if (FromRes.isInvalid())
4741 return ExprError();
4742 From = FromRes.take();
4743 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004744
Douglas Gregor5fccd362010-03-03 23:55:11 +00004745 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004746 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004747 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004748 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004749}
4750
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004751/// TryContextuallyConvertToBool - Attempt to contextually convert the
4752/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004753static ImplicitConversionSequence
4754TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004755 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004756 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004757 // FIXME: Are these flags correct?
4758 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004759 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004760 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004761 /*CStyle=*/false,
4762 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004763}
4764
4765/// PerformContextuallyConvertToBool - Perform a contextual conversion
4766/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004767ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004768 if (checkPlaceholderForOverload(*this, From))
4769 return ExprError();
4770
John McCall120d63c2010-08-24 20:38:10 +00004771 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004772 if (!ICS.isBad())
4773 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004774
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004775 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004776 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004777 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004778 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004779 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004780}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004781
Richard Smith8ef7b202012-01-18 23:55:52 +00004782/// Check that the specified conversion is permitted in a converted constant
4783/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4784/// is acceptable.
4785static bool CheckConvertedConstantConversions(Sema &S,
4786 StandardConversionSequence &SCS) {
4787 // Since we know that the target type is an integral or unscoped enumeration
4788 // type, most conversion kinds are impossible. All possible First and Third
4789 // conversions are fine.
4790 switch (SCS.Second) {
4791 case ICK_Identity:
4792 case ICK_Integral_Promotion:
4793 case ICK_Integral_Conversion:
4794 return true;
4795
4796 case ICK_Boolean_Conversion:
4797 // Conversion from an integral or unscoped enumeration type to bool is
4798 // classified as ICK_Boolean_Conversion, but it's also an integral
4799 // conversion, so it's permitted in a converted constant expression.
4800 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4801 SCS.getToType(2)->isBooleanType();
4802
4803 case ICK_Floating_Integral:
4804 case ICK_Complex_Real:
4805 return false;
4806
4807 case ICK_Lvalue_To_Rvalue:
4808 case ICK_Array_To_Pointer:
4809 case ICK_Function_To_Pointer:
4810 case ICK_NoReturn_Adjustment:
4811 case ICK_Qualification:
4812 case ICK_Compatible_Conversion:
4813 case ICK_Vector_Conversion:
4814 case ICK_Vector_Splat:
4815 case ICK_Derived_To_Base:
4816 case ICK_Pointer_Conversion:
4817 case ICK_Pointer_Member:
4818 case ICK_Block_Pointer_Conversion:
4819 case ICK_Writeback_Conversion:
4820 case ICK_Floating_Promotion:
4821 case ICK_Complex_Promotion:
4822 case ICK_Complex_Conversion:
4823 case ICK_Floating_Conversion:
4824 case ICK_TransparentUnionConversion:
4825 llvm_unreachable("unexpected second conversion kind");
4826
4827 case ICK_Num_Conversion_Kinds:
4828 break;
4829 }
4830
4831 llvm_unreachable("unknown conversion kind");
4832}
4833
4834/// CheckConvertedConstantExpression - Check that the expression From is a
4835/// converted constant expression of type T, perform the conversion and produce
4836/// the converted expression, per C++11 [expr.const]p3.
4837ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4838 llvm::APSInt &Value,
4839 CCEKind CCE) {
4840 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4841 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4842
4843 if (checkPlaceholderForOverload(*this, From))
4844 return ExprError();
4845
4846 // C++11 [expr.const]p3 with proposed wording fixes:
4847 // A converted constant expression of type T is a core constant expression,
4848 // implicitly converted to a prvalue of type T, where the converted
4849 // expression is a literal constant expression and the implicit conversion
4850 // sequence contains only user-defined conversions, lvalue-to-rvalue
4851 // conversions, integral promotions, and integral conversions other than
4852 // narrowing conversions.
4853 ImplicitConversionSequence ICS =
4854 TryImplicitConversion(From, T,
4855 /*SuppressUserConversions=*/false,
4856 /*AllowExplicit=*/false,
4857 /*InOverloadResolution=*/false,
4858 /*CStyle=*/false,
4859 /*AllowObjcWritebackConversion=*/false);
4860 StandardConversionSequence *SCS = 0;
4861 switch (ICS.getKind()) {
4862 case ImplicitConversionSequence::StandardConversion:
4863 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004864 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004865 diag::err_typecheck_converted_constant_expression_disallowed)
4866 << From->getType() << From->getSourceRange() << T;
4867 SCS = &ICS.Standard;
4868 break;
4869 case ImplicitConversionSequence::UserDefinedConversion:
4870 // We are converting from class type to an integral or enumeration type, so
4871 // the Before sequence must be trivial.
4872 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004873 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004874 diag::err_typecheck_converted_constant_expression_disallowed)
4875 << From->getType() << From->getSourceRange() << T;
4876 SCS = &ICS.UserDefined.After;
4877 break;
4878 case ImplicitConversionSequence::AmbiguousConversion:
4879 case ImplicitConversionSequence::BadConversion:
4880 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004881 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004882 diag::err_typecheck_converted_constant_expression)
4883 << From->getType() << From->getSourceRange() << T;
4884 return ExprError();
4885
4886 case ImplicitConversionSequence::EllipsisConversion:
4887 llvm_unreachable("ellipsis conversion in converted constant expression");
4888 }
4889
4890 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4891 if (Result.isInvalid())
4892 return Result;
4893
4894 // Check for a narrowing implicit conversion.
4895 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004896 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004897 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4898 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004899 case NK_Variable_Narrowing:
4900 // Implicit conversion to a narrower type, and the value is not a constant
4901 // expression. We'll diagnose this in a moment.
4902 case NK_Not_Narrowing:
4903 break;
4904
4905 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004906 Diag(From->getLocStart(),
4907 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4908 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004909 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004910 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004911 break;
4912
4913 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004914 Diag(From->getLocStart(),
4915 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4916 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004917 << CCE << /*Constant*/0 << From->getType() << T;
4918 break;
4919 }
4920
4921 // Check the expression is a constant expression.
4922 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4923 Expr::EvalResult Eval;
4924 Eval.Diag = &Notes;
4925
4926 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4927 // The expression can't be folded, so we can't keep it at this position in
4928 // the AST.
4929 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004930 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004931 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004932
4933 if (Notes.empty()) {
4934 // It's a constant expression.
4935 return Result;
4936 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004937 }
4938
4939 // It's not a constant expression. Produce an appropriate diagnostic.
4940 if (Notes.size() == 1 &&
4941 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4942 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4943 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004944 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004945 << CCE << From->getSourceRange();
4946 for (unsigned I = 0; I < Notes.size(); ++I)
4947 Diag(Notes[I].first, Notes[I].second);
4948 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004949 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004950}
4951
John McCall0bcc9bc2011-09-09 06:11:02 +00004952/// dropPointerConversions - If the given standard conversion sequence
4953/// involves any pointer conversions, remove them. This may change
4954/// the result type of the conversion sequence.
4955static void dropPointerConversion(StandardConversionSequence &SCS) {
4956 if (SCS.Second == ICK_Pointer_Conversion) {
4957 SCS.Second = ICK_Identity;
4958 SCS.Third = ICK_Identity;
4959 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4960 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004961}
John McCall120d63c2010-08-24 20:38:10 +00004962
John McCall0bcc9bc2011-09-09 06:11:02 +00004963/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4964/// convert the expression From to an Objective-C pointer type.
4965static ImplicitConversionSequence
4966TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4967 // Do an implicit conversion to 'id'.
4968 QualType Ty = S.Context.getObjCIdType();
4969 ImplicitConversionSequence ICS
4970 = TryImplicitConversion(S, From, Ty,
4971 // FIXME: Are these flags correct?
4972 /*SuppressUserConversions=*/false,
4973 /*AllowExplicit=*/true,
4974 /*InOverloadResolution=*/false,
4975 /*CStyle=*/false,
4976 /*AllowObjCWritebackConversion=*/false);
4977
4978 // Strip off any final conversions to 'id'.
4979 switch (ICS.getKind()) {
4980 case ImplicitConversionSequence::BadConversion:
4981 case ImplicitConversionSequence::AmbiguousConversion:
4982 case ImplicitConversionSequence::EllipsisConversion:
4983 break;
4984
4985 case ImplicitConversionSequence::UserDefinedConversion:
4986 dropPointerConversion(ICS.UserDefined.After);
4987 break;
4988
4989 case ImplicitConversionSequence::StandardConversion:
4990 dropPointerConversion(ICS.Standard);
4991 break;
4992 }
4993
4994 return ICS;
4995}
4996
4997/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4998/// conversion of the expression From to an Objective-C pointer type.
4999ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005000 if (checkPlaceholderForOverload(*this, From))
5001 return ExprError();
5002
John McCallc12c5bb2010-05-15 11:32:37 +00005003 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005004 ImplicitConversionSequence ICS =
5005 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005006 if (!ICS.isBad())
5007 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005008 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005009}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005010
Richard Smithf39aec12012-02-04 07:07:42 +00005011/// Determine whether the provided type is an integral type, or an enumeration
5012/// type of a permitted flavor.
5013static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5014 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5015 : T->isIntegralOrUnscopedEnumerationType();
5016}
5017
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005018/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005019/// enumeration type.
5020///
5021/// This routine will attempt to convert an expression of class type to an
5022/// integral or enumeration type, if that class type only has a single
5023/// conversion to an integral or enumeration type.
5024///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005025/// \param Loc The source location of the construct that requires the
5026/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005027///
James Dennett40ae6662012-06-22 08:52:37 +00005028/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005029///
James Dennett40ae6662012-06-22 08:52:37 +00005030/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005031///
Richard Smithf39aec12012-02-04 07:07:42 +00005032/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5033/// enumerations should be considered.
5034///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005035/// \returns The expression, converted to an integral or enumeration type if
5036/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005037ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005038Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005039 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005040 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005041 // We can't perform any more checking for type-dependent expressions.
5042 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005043 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005044
Eli Friedmanceccab92012-01-26 00:26:18 +00005045 // Process placeholders immediately.
5046 if (From->hasPlaceholderType()) {
5047 ExprResult result = CheckPlaceholderExpr(From);
5048 if (result.isInvalid()) return result;
5049 From = result.take();
5050 }
5051
Douglas Gregorc30614b2010-06-29 23:17:37 +00005052 // If the expression already has integral or enumeration type, we're golden.
5053 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005054 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005055 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005056
5057 // FIXME: Check for missing '()' if T is a function type?
5058
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059 // 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 +00005060 // expression of integral or enumeration type.
5061 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005062 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005063 if (!Diagnoser.Suppress)
5064 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005065 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005066 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
Douglas Gregorc30614b2010-06-29 23:17:37 +00005068 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005069 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005070 ICEConvertDiagnoser &Diagnoser;
5071 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005072
Douglas Gregorab41fe92012-05-04 22:38:52 +00005073 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5074 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005075
5076 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005077 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005078 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005079 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005080
5081 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005082 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005083
Douglas Gregorc30614b2010-06-29 23:17:37 +00005084 // Look for a conversion to an integral or enumeration type.
5085 UnresolvedSet<4> ViableConversions;
5086 UnresolvedSet<4> ExplicitConversions;
5087 const UnresolvedSetImpl *Conversions
5088 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005090 bool HadMultipleCandidates = (Conversions->size() > 1);
5091
Douglas Gregorc30614b2010-06-29 23:17:37 +00005092 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005093 E = Conversions->end();
5094 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005095 ++I) {
5096 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005097 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5098 if (isIntegralOrEnumerationType(
5099 Conversion->getConversionType().getNonReferenceType(),
5100 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005101 if (Conversion->isExplicit())
5102 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5103 else
5104 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5105 }
Richard Smithf39aec12012-02-04 07:07:42 +00005106 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005108
Douglas Gregorc30614b2010-06-29 23:17:37 +00005109 switch (ViableConversions.size()) {
5110 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005111 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005112 DeclAccessPair Found = ExplicitConversions[0];
5113 CXXConversionDecl *Conversion
5114 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005115
Douglas Gregorc30614b2010-06-29 23:17:37 +00005116 // The user probably meant to invoke the given explicit
5117 // conversion; use it.
5118 QualType ConvTy
5119 = Conversion->getConversionType().getNonReferenceType();
5120 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005121 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Douglas Gregorab41fe92012-05-04 22:38:52 +00005123 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005124 << FixItHint::CreateInsertion(From->getLocStart(),
5125 "static_cast<" + TypeStr + ">(")
5126 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5127 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005128 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129
5130 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005131 // explicit conversion function.
5132 if (isSFINAEContext())
5133 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005136 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5137 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005138 if (Result.isInvalid())
5139 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005140 // Record usage of conversion in an implicit cast.
5141 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5142 CK_UserDefinedConversion,
5143 Result.get(), 0,
5144 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005146
Douglas Gregorc30614b2010-06-29 23:17:37 +00005147 // We'll complain below about a non-integral condition type.
5148 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005149
Douglas Gregorc30614b2010-06-29 23:17:37 +00005150 case 1: {
5151 // Apply this conversion.
5152 DeclAccessPair Found = ViableConversions[0];
5153 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005154
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005155 CXXConversionDecl *Conversion
5156 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5157 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005158 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005159 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005160 if (isSFINAEContext())
5161 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005162
Douglas Gregorab41fe92012-05-04 22:38:52 +00005163 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5164 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005165 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005166
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005167 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5168 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005169 if (Result.isInvalid())
5170 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005171 // Record usage of conversion in an implicit cast.
5172 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5173 CK_UserDefinedConversion,
5174 Result.get(), 0,
5175 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005176 break;
5177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005178
Douglas Gregorc30614b2010-06-29 23:17:37 +00005179 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005180 if (Diagnoser.Suppress)
5181 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005182
Douglas Gregorab41fe92012-05-04 22:38:52 +00005183 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005184 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5185 CXXConversionDecl *Conv
5186 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5187 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005188 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005189 }
John McCall9ae2f072010-08-23 23:25:46 +00005190 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005192
Richard Smith282e7e62012-02-04 09:53:13 +00005193 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005194 !Diagnoser.Suppress) {
5195 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5196 << From->getSourceRange();
5197 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005198
Eli Friedmanceccab92012-01-26 00:26:18 +00005199 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005200}
5201
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005202/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005203/// candidate functions, using the given function call arguments. If
5204/// @p SuppressUserConversions, then don't allow user-defined
5205/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005206///
James Dennett699c9042012-06-15 07:13:21 +00005207/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005208/// based on an incomplete set of function arguments. This feature is used by
5209/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005210void
5211Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005212 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005213 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005214 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005215 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005216 bool PartialOverloading,
5217 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005218 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005219 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005220 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005221 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005222 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Douglas Gregor88a35142008-12-22 05:46:06 +00005224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005225 if (!isa<CXXConstructorDecl>(Method)) {
5226 // If we get here, it's because we're calling a member function
5227 // that is named without a member access expression (e.g.,
5228 // "this->f") that was either written explicitly or created
5229 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005230 // function, e.g., X::f(). We use an empty type for the implied
5231 // object argument (C++ [over.call.func]p3), and the acting context
5232 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005233 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005234 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005235 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005236 return;
5237 }
5238 // We treat a constructor like a non-member function, since its object
5239 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005240 }
5241
Douglas Gregorfd476482009-11-13 23:59:09 +00005242 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005243 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005244
Douglas Gregor7edfb692009-11-23 12:27:39 +00005245 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005246 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005247
Douglas Gregor66724ea2009-11-14 01:20:54 +00005248 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5249 // C++ [class.copy]p3:
5250 // A member function template is never instantiated to perform the copy
5251 // of a class object to an object of its class type.
5252 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005253 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005254 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005255 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5256 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005257 return;
5258 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005259
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005260 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005261 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005262 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005263 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005264 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005265 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005266 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005267 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005268
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005269 unsigned NumArgsInProto = Proto->getNumArgs();
5270
5271 // (C++ 13.3.2p2): A candidate function having fewer than m
5272 // parameters is viable only if it has an ellipsis in its parameter
5273 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005274 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005275 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005276 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005277 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005278 return;
5279 }
5280
5281 // (C++ 13.3.2p2): A candidate function having more than m parameters
5282 // is viable only if the (m+1)st parameter has a default argument
5283 // (8.3.6). For the purposes of overload resolution, the
5284 // parameter list is truncated on the right, so that there are
5285 // exactly m parameters.
5286 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005287 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005288 // Not enough arguments.
5289 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005290 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005291 return;
5292 }
5293
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005294 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005295 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005296 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5297 if (CheckCUDATarget(Caller, Function)) {
5298 Candidate.Viable = false;
5299 Candidate.FailureKind = ovl_fail_bad_target;
5300 return;
5301 }
5302
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005303 // Determine the implicit conversion sequences for each of the
5304 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005305 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005306 if (ArgIdx < NumArgsInProto) {
5307 // (C++ 13.3.2p3): for F to be a viable function, there shall
5308 // exist for each argument an implicit conversion sequence
5309 // (13.3.3.1) that converts that argument to the corresponding
5310 // parameter of F.
5311 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005312 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005313 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005314 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005315 /*InOverloadResolution=*/true,
5316 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005317 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005318 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005319 if (Candidate.Conversions[ArgIdx].isBad()) {
5320 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005321 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005322 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005323 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005324 } else {
5325 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5326 // argument for which there is no corresponding parameter is
5327 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005328 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005329 }
5330 }
5331}
5332
Douglas Gregor063daf62009-03-13 18:40:31 +00005333/// \brief Add all of the function declarations in the given function set to
5334/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005335void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005337 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005338 bool SuppressUserConversions,
5339 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005340 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005341 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5342 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005343 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005344 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005345 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005346 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005347 Args.slice(1), CandidateSet,
5348 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005349 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005350 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005351 SuppressUserConversions);
5352 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005353 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005354 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5355 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005356 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005357 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005358 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005360 Args[0]->Classify(Context), Args.slice(1),
5361 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005362 else
John McCall9aa472c2010-03-19 07:35:19 +00005363 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005364 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005365 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005366 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005367 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005368}
5369
John McCall314be4e2009-11-17 07:50:12 +00005370/// AddMethodCandidate - Adds a named decl (which is some kind of
5371/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005372void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005373 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005374 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005375 Expr **Args, unsigned NumArgs,
5376 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005377 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005378 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005379 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005380
5381 if (isa<UsingShadowDecl>(Decl))
5382 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005383
John McCall314be4e2009-11-17 07:50:12 +00005384 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5385 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5386 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005387 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5388 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005389 ObjectType, ObjectClassification,
5390 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005391 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005392 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005393 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005394 ObjectType, ObjectClassification,
5395 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005396 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005397 }
5398}
5399
Douglas Gregor96176b32008-11-18 23:14:02 +00005400/// AddMethodCandidate - Adds the given C++ member function to the set
5401/// of candidate functions, using the given function call arguments
5402/// and the object argument (@c Object). For example, in a call
5403/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5404/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5405/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005406/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005407void
John McCall9aa472c2010-03-19 07:35:19 +00005408Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005409 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005410 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005411 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005412 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005413 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005414 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005415 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005416 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005417 assert(!isa<CXXConstructorDecl>(Method) &&
5418 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005419
Douglas Gregor3f396022009-09-28 04:47:19 +00005420 if (!CandidateSet.isNewCandidate(Method))
5421 return;
5422
Douglas Gregor7edfb692009-11-23 12:27:39 +00005423 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005424 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005425
Douglas Gregor96176b32008-11-18 23:14:02 +00005426 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005427 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005428 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005429 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005430 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005431 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005432 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005433
5434 unsigned NumArgsInProto = Proto->getNumArgs();
5435
5436 // (C++ 13.3.2p2): A candidate function having fewer than m
5437 // parameters is viable only if it has an ellipsis in its parameter
5438 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005439 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005440 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005441 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005442 return;
5443 }
5444
5445 // (C++ 13.3.2p2): A candidate function having more than m parameters
5446 // is viable only if the (m+1)st parameter has a default argument
5447 // (8.3.6). For the purposes of overload resolution, the
5448 // parameter list is truncated on the right, so that there are
5449 // exactly m parameters.
5450 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005451 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005452 // Not enough arguments.
5453 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005454 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005455 return;
5456 }
5457
5458 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005459
John McCall701c89e2009-12-03 04:06:58 +00005460 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005461 // The implicit object argument is ignored.
5462 Candidate.IgnoreObjectArgument = true;
5463 else {
5464 // Determine the implicit conversion sequence for the object
5465 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005466 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005467 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5468 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005469 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005470 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005471 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005472 return;
5473 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005474 }
5475
5476 // Determine the implicit conversion sequences for each of the
5477 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005478 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005479 if (ArgIdx < NumArgsInProto) {
5480 // (C++ 13.3.2p3): for F to be a viable function, there shall
5481 // exist for each argument an implicit conversion sequence
5482 // (13.3.3.1) that converts that argument to the corresponding
5483 // parameter of F.
5484 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005485 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005486 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005488 /*InOverloadResolution=*/true,
5489 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005490 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005491 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005492 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005493 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005494 break;
5495 }
5496 } else {
5497 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5498 // argument for which there is no corresponding parameter is
5499 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005500 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005501 }
5502 }
5503}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005504
Douglas Gregor6b906862009-08-21 00:16:32 +00005505/// \brief Add a C++ member function template as a candidate to the candidate
5506/// set, using template argument deduction to produce an appropriate member
5507/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005508void
Douglas Gregor6b906862009-08-21 00:16:32 +00005509Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005510 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005511 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005512 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005513 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005514 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005515 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005516 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005517 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005518 if (!CandidateSet.isNewCandidate(MethodTmpl))
5519 return;
5520
Douglas Gregor6b906862009-08-21 00:16:32 +00005521 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005522 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005523 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005524 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005525 // candidate functions in the usual way.113) A given name can refer to one
5526 // or more function templates and also to a set of overloaded non-template
5527 // functions. In such a case, the candidate functions generated from each
5528 // function template are combined with the set of non-template candidate
5529 // functions.
John McCall5769d612010-02-08 23:07:23 +00005530 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005531 FunctionDecl *Specialization = 0;
5532 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005533 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5534 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005535 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005536 Candidate.FoundDecl = FoundDecl;
5537 Candidate.Function = MethodTmpl->getTemplatedDecl();
5538 Candidate.Viable = false;
5539 Candidate.FailureKind = ovl_fail_bad_deduction;
5540 Candidate.IsSurrogate = false;
5541 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005542 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005543 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005544 Info);
5545 return;
5546 }
Mike Stump1eb44332009-09-09 15:08:12 +00005547
Douglas Gregor6b906862009-08-21 00:16:32 +00005548 // Add the function template specialization produced by template argument
5549 // deduction as a candidate.
5550 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005551 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005552 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005553 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005554 ActingContext, ObjectType, ObjectClassification, Args,
5555 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005556}
5557
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005558/// \brief Add a C++ function template specialization as a candidate
5559/// in the candidate set, using template argument deduction to produce
5560/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005561void
Douglas Gregore53060f2009-06-25 22:08:12 +00005562Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005563 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005564 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005565 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005566 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005567 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005568 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5569 return;
5570
Douglas Gregore53060f2009-06-25 22:08:12 +00005571 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005572 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005573 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005574 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005575 // candidate functions in the usual way.113) A given name can refer to one
5576 // or more function templates and also to a set of overloaded non-template
5577 // functions. In such a case, the candidate functions generated from each
5578 // function template are combined with the set of non-template candidate
5579 // functions.
John McCall5769d612010-02-08 23:07:23 +00005580 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005581 FunctionDecl *Specialization = 0;
5582 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005583 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5584 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005585 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005586 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005587 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5588 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005589 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005590 Candidate.IsSurrogate = false;
5591 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005592 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005593 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005594 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005595 return;
5596 }
Mike Stump1eb44332009-09-09 15:08:12 +00005597
Douglas Gregore53060f2009-06-25 22:08:12 +00005598 // Add the function template specialization produced by template argument
5599 // deduction as a candidate.
5600 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005601 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005602 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005603}
Mike Stump1eb44332009-09-09 15:08:12 +00005604
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005605/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005606/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005607/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005608/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005609/// (which may or may not be the same type as the type that the
5610/// conversion function produces).
5611void
5612Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005613 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005614 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005615 Expr *From, QualType ToType,
5616 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005617 assert(!Conversion->getDescribedFunctionTemplate() &&
5618 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005619 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005620 if (!CandidateSet.isNewCandidate(Conversion))
5621 return;
5622
Douglas Gregor7edfb692009-11-23 12:27:39 +00005623 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005625
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005626 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005627 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005628 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005629 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005630 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005631 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005632 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005633 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005634 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005635 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005636 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005637
Douglas Gregorbca39322010-08-19 15:37:02 +00005638 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639 // For conversion functions, the function is considered to be a member of
5640 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005641 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005642 //
5643 // Determine the implicit conversion sequence for the implicit
5644 // object parameter.
5645 QualType ImplicitParamType = From->getType();
5646 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5647 ImplicitParamType = FromPtrType->getPointeeType();
5648 CXXRecordDecl *ConversionContext
5649 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005650
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005651 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005652 = TryObjectArgumentInitialization(*this, From->getType(),
5653 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005654 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005655
John McCall1d318332010-01-12 00:44:57 +00005656 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005657 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005658 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005659 return;
5660 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005661
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005662 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005663 // derived to base as such conversions are given Conversion Rank. They only
5664 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5665 QualType FromCanon
5666 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5667 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5668 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5669 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005670 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005671 return;
5672 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005673
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005674 // To determine what the conversion from the result of calling the
5675 // conversion function to the type we're eventually trying to
5676 // convert to (ToType), we need to synthesize a call to the
5677 // conversion function and attempt copy initialization from it. This
5678 // makes sure that we get the right semantics with respect to
5679 // lvalues/rvalues and the type. Fortunately, we can allocate this
5680 // call on the stack and we don't need its arguments to be
5681 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005682 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005683 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005684 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5685 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005686 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005687 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Richard Smith87c1f1f2011-07-13 22:53:21 +00005689 QualType ConversionType = Conversion->getConversionType();
5690 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005691 Candidate.Viable = false;
5692 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5693 return;
5694 }
5695
Richard Smith87c1f1f2011-07-13 22:53:21 +00005696 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005697
Mike Stump1eb44332009-09-09 15:08:12 +00005698 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005699 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5700 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005701 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005702 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005703 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005704 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005705 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005706 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005707 /*InOverloadResolution=*/false,
5708 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005709
John McCall1d318332010-01-12 00:44:57 +00005710 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005711 case ImplicitConversionSequence::StandardConversion:
5712 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005713
Douglas Gregorc520c842010-04-12 23:42:09 +00005714 // C++ [over.ics.user]p3:
5715 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005716 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005717 // shall have exact match rank.
5718 if (Conversion->getPrimaryTemplate() &&
5719 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5720 Candidate.Viable = false;
5721 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005723
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005724 // C++0x [dcl.init.ref]p5:
5725 // In the second case, if the reference is an rvalue reference and
5726 // the second standard conversion sequence of the user-defined
5727 // conversion sequence includes an lvalue-to-rvalue conversion, the
5728 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005729 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005730 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5731 Candidate.Viable = false;
5732 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5733 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005734 break;
5735
5736 case ImplicitConversionSequence::BadConversion:
5737 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005738 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005739 break;
5740
5741 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005742 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005743 "Can only end up with a standard conversion sequence or failure");
5744 }
5745}
5746
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005747/// \brief Adds a conversion function template specialization
5748/// candidate to the overload set, using template argument deduction
5749/// to deduce the template arguments of the conversion function
5750/// template from the type that we are converting to (C++
5751/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005752void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005753Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005754 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005755 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005756 Expr *From, QualType ToType,
5757 OverloadCandidateSet &CandidateSet) {
5758 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5759 "Only conversion function templates permitted here");
5760
Douglas Gregor3f396022009-09-28 04:47:19 +00005761 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5762 return;
5763
John McCall5769d612010-02-08 23:07:23 +00005764 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005765 CXXConversionDecl *Specialization = 0;
5766 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005767 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005768 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005769 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005770 Candidate.FoundDecl = FoundDecl;
5771 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5772 Candidate.Viable = false;
5773 Candidate.FailureKind = ovl_fail_bad_deduction;
5774 Candidate.IsSurrogate = false;
5775 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005776 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005777 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005778 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005779 return;
5780 }
Mike Stump1eb44332009-09-09 15:08:12 +00005781
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005782 // Add the conversion function template specialization produced by
5783 // template argument deduction as a candidate.
5784 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005785 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005786 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005787}
5788
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005789/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5790/// converts the given @c Object to a function pointer via the
5791/// conversion function @c Conversion, and then attempts to call it
5792/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5793/// the type of function that we'll eventually be calling.
5794void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005795 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005796 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005797 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005798 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005799 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005800 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005801 if (!CandidateSet.isNewCandidate(Conversion))
5802 return;
5803
Douglas Gregor7edfb692009-11-23 12:27:39 +00005804 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005805 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005806
Ahmed Charles13a140c2012-02-25 11:00:22 +00005807 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005808 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005809 Candidate.Function = 0;
5810 Candidate.Surrogate = Conversion;
5811 Candidate.Viable = true;
5812 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005813 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005814 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005815
5816 // Determine the implicit conversion sequence for the implicit
5817 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005818 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005819 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005820 Object->Classify(Context),
5821 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005822 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005823 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005824 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005825 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005826 return;
5827 }
5828
5829 // The first conversion is actually a user-defined conversion whose
5830 // first conversion is ObjectInit's standard conversion (which is
5831 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005832 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005833 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005834 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005835 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005836 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005837 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005838 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005839 = Candidate.Conversions[0].UserDefined.Before;
5840 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5841
Mike Stump1eb44332009-09-09 15:08:12 +00005842 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005843 unsigned NumArgsInProto = Proto->getNumArgs();
5844
5845 // (C++ 13.3.2p2): A candidate function having fewer than m
5846 // parameters is viable only if it has an ellipsis in its parameter
5847 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005848 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005849 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005850 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005851 return;
5852 }
5853
5854 // Function types don't have any default arguments, so just check if
5855 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005856 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005857 // Not enough arguments.
5858 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005859 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005860 return;
5861 }
5862
5863 // Determine the implicit conversion sequences for each of the
5864 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005865 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005866 if (ArgIdx < NumArgsInProto) {
5867 // (C++ 13.3.2p3): for F to be a viable function, there shall
5868 // exist for each argument an implicit conversion sequence
5869 // (13.3.3.1) that converts that argument to the corresponding
5870 // parameter of F.
5871 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005872 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005873 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005874 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005875 /*InOverloadResolution=*/false,
5876 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005877 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005878 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005879 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005880 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005881 break;
5882 }
5883 } else {
5884 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5885 // argument for which there is no corresponding parameter is
5886 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005887 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005888 }
5889 }
5890}
5891
Douglas Gregor063daf62009-03-13 18:40:31 +00005892/// \brief Add overload candidates for overloaded operators that are
5893/// member functions.
5894///
5895/// Add the overloaded operator candidates that are member functions
5896/// for the operator Op that was used in an operator expression such
5897/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5898/// CandidateSet will store the added overload candidates. (C++
5899/// [over.match.oper]).
5900void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5901 SourceLocation OpLoc,
5902 Expr **Args, unsigned NumArgs,
5903 OverloadCandidateSet& CandidateSet,
5904 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005905 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5906
5907 // C++ [over.match.oper]p3:
5908 // For a unary operator @ with an operand of a type whose
5909 // cv-unqualified version is T1, and for a binary operator @ with
5910 // a left operand of a type whose cv-unqualified version is T1 and
5911 // a right operand of a type whose cv-unqualified version is T2,
5912 // three sets of candidate functions, designated member
5913 // candidates, non-member candidates and built-in candidates, are
5914 // constructed as follows:
5915 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005916
5917 // -- If T1 is a class type, the set of member candidates is the
5918 // result of the qualified lookup of T1::operator@
5919 // (13.3.1.1.1); otherwise, the set of member candidates is
5920 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005921 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005922 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005923 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005924 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005925
John McCalla24dc2e2009-11-17 02:14:36 +00005926 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5927 LookupQualifiedName(Operators, T1Rec->getDecl());
5928 Operators.suppressDiagnostics();
5929
Mike Stump1eb44332009-09-09 15:08:12 +00005930 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005931 OperEnd = Operators.end();
5932 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005933 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005934 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005935 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005936 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005937 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005938 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005939}
5940
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005941/// AddBuiltinCandidate - Add a candidate for a built-in
5942/// operator. ResultTy and ParamTys are the result and parameter types
5943/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005944/// arguments being passed to the candidate. IsAssignmentOperator
5945/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005946/// operator. NumContextualBoolArguments is the number of arguments
5947/// (at the beginning of the argument list) that will be contextually
5948/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005949void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005950 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005951 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005952 bool IsAssignmentOperator,
5953 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005954 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005955 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005956
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005957 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005958 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005959 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005960 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005961 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005962 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005963 Candidate.BuiltinTypes.ResultTy = ResultTy;
5964 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5965 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5966
5967 // Determine the implicit conversion sequences for each of the
5968 // arguments.
5969 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005970 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005971 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005972 // C++ [over.match.oper]p4:
5973 // For the built-in assignment operators, conversions of the
5974 // left operand are restricted as follows:
5975 // -- no temporaries are introduced to hold the left operand, and
5976 // -- no user-defined conversions are applied to the left
5977 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005978 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005979 //
5980 // We block these conversions by turning off user-defined
5981 // conversions, since that is the only way that initialization of
5982 // a reference to a non-class type can occur from something that
5983 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005984 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005985 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005986 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005987 Candidate.Conversions[ArgIdx]
5988 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005989 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005990 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005991 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005992 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005993 /*InOverloadResolution=*/false,
5994 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005995 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005996 }
John McCall1d318332010-01-12 00:44:57 +00005997 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005998 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005999 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006000 break;
6001 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006002 }
6003}
6004
6005/// BuiltinCandidateTypeSet - A set of types that will be used for the
6006/// candidate operator functions for built-in operators (C++
6007/// [over.built]). The types are separated into pointer types and
6008/// enumeration types.
6009class BuiltinCandidateTypeSet {
6010 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006011 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006012
6013 /// PointerTypes - The set of pointer types that will be used in the
6014 /// built-in candidates.
6015 TypeSet PointerTypes;
6016
Sebastian Redl78eb8742009-04-19 21:53:20 +00006017 /// MemberPointerTypes - The set of member pointer types that will be
6018 /// used in the built-in candidates.
6019 TypeSet MemberPointerTypes;
6020
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006021 /// EnumerationTypes - The set of enumeration types that will be
6022 /// used in the built-in candidates.
6023 TypeSet EnumerationTypes;
6024
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006025 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006026 /// candidates.
6027 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006028
6029 /// \brief A flag indicating non-record types are viable candidates
6030 bool HasNonRecordTypes;
6031
6032 /// \brief A flag indicating whether either arithmetic or enumeration types
6033 /// were present in the candidate set.
6034 bool HasArithmeticOrEnumeralTypes;
6035
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006036 /// \brief A flag indicating whether the nullptr type was present in the
6037 /// candidate set.
6038 bool HasNullPtrType;
6039
Douglas Gregor5842ba92009-08-24 15:23:48 +00006040 /// Sema - The semantic analysis instance where we are building the
6041 /// candidate type set.
6042 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006043
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006044 /// Context - The AST context in which we will build the type sets.
6045 ASTContext &Context;
6046
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006047 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6048 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006049 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006050
6051public:
6052 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006053 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006054
Mike Stump1eb44332009-09-09 15:08:12 +00006055 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006056 : HasNonRecordTypes(false),
6057 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006058 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006059 SemaRef(SemaRef),
6060 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006062 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006063 SourceLocation Loc,
6064 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006065 bool AllowExplicitConversions,
6066 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006067
6068 /// pointer_begin - First pointer type found;
6069 iterator pointer_begin() { return PointerTypes.begin(); }
6070
Sebastian Redl78eb8742009-04-19 21:53:20 +00006071 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 iterator pointer_end() { return PointerTypes.end(); }
6073
Sebastian Redl78eb8742009-04-19 21:53:20 +00006074 /// member_pointer_begin - First member pointer type found;
6075 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6076
6077 /// member_pointer_end - Past the last member pointer type found;
6078 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6079
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006080 /// enumeration_begin - First enumeration type found;
6081 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6082
Sebastian Redl78eb8742009-04-19 21:53:20 +00006083 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006084 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006085
Douglas Gregor26bcf672010-05-19 03:21:00 +00006086 iterator vector_begin() { return VectorTypes.begin(); }
6087 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006088
6089 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6090 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006091 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006092};
6093
Sebastian Redl78eb8742009-04-19 21:53:20 +00006094/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095/// the set of pointer types along with any more-qualified variants of
6096/// that type. For example, if @p Ty is "int const *", this routine
6097/// will add "int const *", "int const volatile *", "int const
6098/// restrict *", and "int const volatile restrict *" to the set of
6099/// pointer types. Returns true if the add of @p Ty itself succeeded,
6100/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006101///
6102/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006103bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006104BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6105 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006106
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006107 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006108 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006109 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006110
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006111 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006112 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006113 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006114 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006115 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6116 PointeeTy = PTy->getPointeeType();
6117 buildObjCPtr = true;
6118 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006119 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006120 }
6121
Sebastian Redla9efada2009-11-18 20:39:26 +00006122 // Don't add qualified variants of arrays. For one, they're not allowed
6123 // (the qualifier would sink to the element type), and for another, the
6124 // only overload situation where it matters is subscript or pointer +- int,
6125 // and those shouldn't have qualifier variants anyway.
6126 if (PointeeTy->isArrayType())
6127 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006128
John McCall0953e762009-09-24 19:53:00 +00006129 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006130 bool hasVolatile = VisibleQuals.hasVolatile();
6131 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006132
John McCall0953e762009-09-24 19:53:00 +00006133 // Iterate through all strict supersets of BaseCVR.
6134 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6135 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006136 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006137 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006138
6139 // Skip over restrict if no restrict found anywhere in the types, or if
6140 // the type cannot be restrict-qualified.
6141 if ((CVR & Qualifiers::Restrict) &&
6142 (!hasRestrict ||
6143 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6144 continue;
6145
6146 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006147 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006148
6149 // Build qualified pointer type.
6150 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006151 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006152 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006153 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006154 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6155
6156 // Insert qualified pointer type.
6157 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158 }
6159
6160 return true;
6161}
6162
Sebastian Redl78eb8742009-04-19 21:53:20 +00006163/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6164/// to the set of pointer types along with any more-qualified variants of
6165/// that type. For example, if @p Ty is "int const *", this routine
6166/// will add "int const *", "int const volatile *", "int const
6167/// restrict *", and "int const volatile restrict *" to the set of
6168/// pointer types. Returns true if the add of @p Ty itself succeeded,
6169/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006170///
6171/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006172bool
6173BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6174 QualType Ty) {
6175 // Insert this type.
6176 if (!MemberPointerTypes.insert(Ty))
6177 return false;
6178
John McCall0953e762009-09-24 19:53:00 +00006179 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6180 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006181
John McCall0953e762009-09-24 19:53:00 +00006182 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006183 // Don't add qualified variants of arrays. For one, they're not allowed
6184 // (the qualifier would sink to the element type), and for another, the
6185 // only overload situation where it matters is subscript or pointer +- int,
6186 // and those shouldn't have qualifier variants anyway.
6187 if (PointeeTy->isArrayType())
6188 return true;
John McCall0953e762009-09-24 19:53:00 +00006189 const Type *ClassTy = PointerTy->getClass();
6190
6191 // Iterate through all strict supersets of the pointee type's CVR
6192 // qualifiers.
6193 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6194 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6195 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006196
John McCall0953e762009-09-24 19:53:00 +00006197 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006198 MemberPointerTypes.insert(
6199 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006200 }
6201
6202 return true;
6203}
6204
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006205/// AddTypesConvertedFrom - Add each of the types to which the type @p
6206/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006207/// primarily interested in pointer types and enumeration types. We also
6208/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006209/// AllowUserConversions is true if we should look at the conversion
6210/// functions of a class type, and AllowExplicitConversions if we
6211/// should also include the explicit conversion functions of a class
6212/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006213void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006214BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006215 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006216 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006217 bool AllowExplicitConversions,
6218 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006219 // Only deal with canonical types.
6220 Ty = Context.getCanonicalType(Ty);
6221
6222 // Look through reference types; they aren't part of the type of an
6223 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006224 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006225 Ty = RefTy->getPointeeType();
6226
John McCall3b657512011-01-19 10:06:00 +00006227 // If we're dealing with an array type, decay to the pointer.
6228 if (Ty->isArrayType())
6229 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6230
6231 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006232 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233
Chandler Carruth6a577462010-12-13 01:44:01 +00006234 // Flag if we ever add a non-record type.
6235 const RecordType *TyRec = Ty->getAs<RecordType>();
6236 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6237
Chandler Carruth6a577462010-12-13 01:44:01 +00006238 // Flag if we encounter an arithmetic type.
6239 HasArithmeticOrEnumeralTypes =
6240 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6241
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006242 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6243 PointerTypes.insert(Ty);
6244 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006245 // Insert our type, and its more-qualified variants, into the set
6246 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006247 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006248 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006249 } else if (Ty->isMemberPointerType()) {
6250 // Member pointers are far easier, since the pointee can't be converted.
6251 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6252 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006253 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006254 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006255 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006256 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006257 // We treat vector types as arithmetic types in many contexts as an
6258 // extension.
6259 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006260 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006261 } else if (Ty->isNullPtrType()) {
6262 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006263 } else if (AllowUserConversions && TyRec) {
6264 // No conversion functions in incomplete types.
6265 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6266 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006267
Chandler Carruth6a577462010-12-13 01:44:01 +00006268 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6269 const UnresolvedSetImpl *Conversions
6270 = ClassDecl->getVisibleConversionFunctions();
6271 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6272 E = Conversions->end(); I != E; ++I) {
6273 NamedDecl *D = I.getDecl();
6274 if (isa<UsingShadowDecl>(D))
6275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006276
Chandler Carruth6a577462010-12-13 01:44:01 +00006277 // Skip conversion function templates; they don't tell us anything
6278 // about which builtin types we can convert to.
6279 if (isa<FunctionTemplateDecl>(D))
6280 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006281
Chandler Carruth6a577462010-12-13 01:44:01 +00006282 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6283 if (AllowExplicitConversions || !Conv->isExplicit()) {
6284 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6285 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006286 }
6287 }
6288 }
6289}
6290
Douglas Gregor19b7b152009-08-24 13:43:27 +00006291/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6292/// the volatile- and non-volatile-qualified assignment operators for the
6293/// given type to the candidate set.
6294static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6295 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006296 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006297 unsigned NumArgs,
6298 OverloadCandidateSet &CandidateSet) {
6299 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006300
Douglas Gregor19b7b152009-08-24 13:43:27 +00006301 // T& operator=(T&, T)
6302 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6303 ParamTypes[1] = T;
6304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6305 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006306
Douglas Gregor19b7b152009-08-24 13:43:27 +00006307 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6308 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006309 ParamTypes[0]
6310 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006311 ParamTypes[1] = T;
6312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006313 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006314 }
6315}
Mike Stump1eb44332009-09-09 15:08:12 +00006316
Sebastian Redl9994a342009-10-25 17:03:50 +00006317/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6318/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006319static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6320 Qualifiers VRQuals;
6321 const RecordType *TyRec;
6322 if (const MemberPointerType *RHSMPType =
6323 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006324 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006325 else
6326 TyRec = ArgExpr->getType()->getAs<RecordType>();
6327 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006328 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006329 VRQuals.addVolatile();
6330 VRQuals.addRestrict();
6331 return VRQuals;
6332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006333
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006334 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006335 if (!ClassDecl->hasDefinition())
6336 return VRQuals;
6337
John McCalleec51cf2010-01-20 00:46:10 +00006338 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006339 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006340
John McCalleec51cf2010-01-20 00:46:10 +00006341 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006342 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006343 NamedDecl *D = I.getDecl();
6344 if (isa<UsingShadowDecl>(D))
6345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6346 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006347 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6348 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6349 CanTy = ResTypeRef->getPointeeType();
6350 // Need to go down the pointer/mempointer chain and add qualifiers
6351 // as see them.
6352 bool done = false;
6353 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006354 if (CanTy.isRestrictQualified())
6355 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006356 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6357 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006358 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006359 CanTy->getAs<MemberPointerType>())
6360 CanTy = ResTypeMPtr->getPointeeType();
6361 else
6362 done = true;
6363 if (CanTy.isVolatileQualified())
6364 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006365 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6366 return VRQuals;
6367 }
6368 }
6369 }
6370 return VRQuals;
6371}
John McCall00071ec2010-11-13 05:51:15 +00006372
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006373namespace {
John McCall00071ec2010-11-13 05:51:15 +00006374
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006375/// \brief Helper class to manage the addition of builtin operator overload
6376/// candidates. It provides shared state and utility methods used throughout
6377/// the process, as well as a helper method to add each group of builtin
6378/// operator overloads from the standard to a candidate set.
6379class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006380 // Common instance state available to all overload candidate addition methods.
6381 Sema &S;
6382 Expr **Args;
6383 unsigned NumArgs;
6384 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006385 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006386 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006387 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006388
Chandler Carruth6d695582010-12-12 10:35:00 +00006389 // Define some constants used to index and iterate over the arithemetic types
6390 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006391 // The "promoted arithmetic types" are the arithmetic
6392 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006393 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006394 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006395 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006396 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006397 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006398 LastPromotedArithmeticType = 11;
6399 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006400
Chandler Carruth6d695582010-12-12 10:35:00 +00006401 /// \brief Get the canonical type for a given arithmetic type index.
6402 CanQualType getArithmeticType(unsigned index) {
6403 assert(index < NumArithmeticTypes);
6404 static CanQualType ASTContext::* const
6405 ArithmeticTypes[NumArithmeticTypes] = {
6406 // Start of promoted types.
6407 &ASTContext::FloatTy,
6408 &ASTContext::DoubleTy,
6409 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006410
Chandler Carruth6d695582010-12-12 10:35:00 +00006411 // Start of integral types.
6412 &ASTContext::IntTy,
6413 &ASTContext::LongTy,
6414 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006415 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006416 &ASTContext::UnsignedIntTy,
6417 &ASTContext::UnsignedLongTy,
6418 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006419 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006420 // End of promoted types.
6421
6422 &ASTContext::BoolTy,
6423 &ASTContext::CharTy,
6424 &ASTContext::WCharTy,
6425 &ASTContext::Char16Ty,
6426 &ASTContext::Char32Ty,
6427 &ASTContext::SignedCharTy,
6428 &ASTContext::ShortTy,
6429 &ASTContext::UnsignedCharTy,
6430 &ASTContext::UnsignedShortTy,
6431 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006432 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006433 };
6434 return S.Context.*ArithmeticTypes[index];
6435 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006436
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006437 /// \brief Gets the canonical type resulting from the usual arithemetic
6438 /// converions for the given arithmetic types.
6439 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6440 // Accelerator table for performing the usual arithmetic conversions.
6441 // The rules are basically:
6442 // - if either is floating-point, use the wider floating-point
6443 // - if same signedness, use the higher rank
6444 // - if same size, use unsigned of the higher rank
6445 // - use the larger type
6446 // These rules, together with the axiom that higher ranks are
6447 // never smaller, are sufficient to precompute all of these results
6448 // *except* when dealing with signed types of higher rank.
6449 // (we could precompute SLL x UI for all known platforms, but it's
6450 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006451 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006452 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006453 Dep=-1,
6454 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006455 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006456 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006457 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006458/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6459/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6460/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6461/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6462/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6463/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6464/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6465/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6466/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6467/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6468/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006469 };
6470
6471 assert(L < LastPromotedArithmeticType);
6472 assert(R < LastPromotedArithmeticType);
6473 int Idx = ConversionsTable[L][R];
6474
6475 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006476 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006477
6478 // Slow path: we need to compare widths.
6479 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006480 CanQualType LT = getArithmeticType(L),
6481 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006482 unsigned LW = S.Context.getIntWidth(LT),
6483 RW = S.Context.getIntWidth(RT);
6484
6485 // If they're different widths, use the signed type.
6486 if (LW > RW) return LT;
6487 else if (LW < RW) return RT;
6488
6489 // Otherwise, use the unsigned type of the signed type's rank.
6490 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6491 assert(L == SLL || R == SLL);
6492 return S.Context.UnsignedLongLongTy;
6493 }
6494
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006495 /// \brief Helper method to factor out the common pattern of adding overloads
6496 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006497 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006498 bool HasVolatile,
6499 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006500 QualType ParamTypes[2] = {
6501 S.Context.getLValueReferenceType(CandidateTy),
6502 S.Context.IntTy
6503 };
6504
6505 // Non-volatile version.
6506 if (NumArgs == 1)
6507 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6508 else
6509 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6510
6511 // Use a heuristic to reduce number of builtin candidates in the set:
6512 // add volatile version only if there are conversions to a volatile type.
6513 if (HasVolatile) {
6514 ParamTypes[0] =
6515 S.Context.getLValueReferenceType(
6516 S.Context.getVolatileType(CandidateTy));
6517 if (NumArgs == 1)
6518 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6519 else
6520 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6521 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006522
6523 // Add restrict version only if there are conversions to a restrict type
6524 // and our candidate type is a non-restrict-qualified pointer.
6525 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6526 !CandidateTy.isRestrictQualified()) {
6527 ParamTypes[0]
6528 = S.Context.getLValueReferenceType(
6529 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6530 if (NumArgs == 1)
6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6532 else
6533 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6534
6535 if (HasVolatile) {
6536 ParamTypes[0]
6537 = S.Context.getLValueReferenceType(
6538 S.Context.getCVRQualifiedType(CandidateTy,
6539 (Qualifiers::Volatile |
6540 Qualifiers::Restrict)));
6541 if (NumArgs == 1)
6542 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6543 CandidateSet);
6544 else
6545 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6546 }
6547 }
6548
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006549 }
6550
6551public:
6552 BuiltinOperatorOverloadBuilder(
6553 Sema &S, Expr **Args, unsigned NumArgs,
6554 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006555 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006556 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006557 OverloadCandidateSet &CandidateSet)
6558 : S(S), Args(Args), NumArgs(NumArgs),
6559 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006560 HasArithmeticOrEnumeralCandidateType(
6561 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006562 CandidateTypes(CandidateTypes),
6563 CandidateSet(CandidateSet) {
6564 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006565 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006566 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006567 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006568 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006569 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006570 assert(getArithmeticType(FirstPromotedArithmeticType)
6571 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006572 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006573 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006574 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006575 "Invalid last promoted arithmetic type");
6576 }
6577
6578 // C++ [over.built]p3:
6579 //
6580 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6581 // is either volatile or empty, there exist candidate operator
6582 // functions of the form
6583 //
6584 // VQ T& operator++(VQ T&);
6585 // T operator++(VQ T&, int);
6586 //
6587 // C++ [over.built]p4:
6588 //
6589 // For every pair (T, VQ), where T is an arithmetic type other
6590 // than bool, and VQ is either volatile or empty, there exist
6591 // candidate operator functions of the form
6592 //
6593 // VQ T& operator--(VQ T&);
6594 // T operator--(VQ T&, int);
6595 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006596 if (!HasArithmeticOrEnumeralCandidateType)
6597 return;
6598
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6600 Arith < NumArithmeticTypes; ++Arith) {
6601 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006602 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006603 VisibleTypeConversionsQuals.hasVolatile(),
6604 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006605 }
6606 }
6607
6608 // C++ [over.built]p5:
6609 //
6610 // For every pair (T, VQ), where T is a cv-qualified or
6611 // cv-unqualified object type, and VQ is either volatile or
6612 // empty, there exist candidate operator functions of the form
6613 //
6614 // T*VQ& operator++(T*VQ&);
6615 // T*VQ& operator--(T*VQ&);
6616 // T* operator++(T*VQ&, int);
6617 // T* operator--(T*VQ&, int);
6618 void addPlusPlusMinusMinusPointerOverloads() {
6619 for (BuiltinCandidateTypeSet::iterator
6620 Ptr = CandidateTypes[0].pointer_begin(),
6621 PtrEnd = CandidateTypes[0].pointer_end();
6622 Ptr != PtrEnd; ++Ptr) {
6623 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006624 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006625 continue;
6626
6627 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006628 (!(*Ptr).isVolatileQualified() &&
6629 VisibleTypeConversionsQuals.hasVolatile()),
6630 (!(*Ptr).isRestrictQualified() &&
6631 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006632 }
6633 }
6634
6635 // C++ [over.built]p6:
6636 // For every cv-qualified or cv-unqualified object type T, there
6637 // exist candidate operator functions of the form
6638 //
6639 // T& operator*(T*);
6640 //
6641 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006642 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006643 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006644 // T& operator*(T*);
6645 void addUnaryStarPointerOverloads() {
6646 for (BuiltinCandidateTypeSet::iterator
6647 Ptr = CandidateTypes[0].pointer_begin(),
6648 PtrEnd = CandidateTypes[0].pointer_end();
6649 Ptr != PtrEnd; ++Ptr) {
6650 QualType ParamTy = *Ptr;
6651 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006652 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6653 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006654
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006655 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6656 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6657 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006658
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006659 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6660 &ParamTy, Args, 1, CandidateSet);
6661 }
6662 }
6663
6664 // C++ [over.built]p9:
6665 // For every promoted arithmetic type T, there exist candidate
6666 // operator functions of the form
6667 //
6668 // T operator+(T);
6669 // T operator-(T);
6670 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006671 if (!HasArithmeticOrEnumeralCandidateType)
6672 return;
6673
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006674 for (unsigned Arith = FirstPromotedArithmeticType;
6675 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006676 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006677 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6678 }
6679
6680 // Extension: We also add these operators for vector types.
6681 for (BuiltinCandidateTypeSet::iterator
6682 Vec = CandidateTypes[0].vector_begin(),
6683 VecEnd = CandidateTypes[0].vector_end();
6684 Vec != VecEnd; ++Vec) {
6685 QualType VecTy = *Vec;
6686 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6687 }
6688 }
6689
6690 // C++ [over.built]p8:
6691 // For every type T, there exist candidate operator functions of
6692 // the form
6693 //
6694 // T* operator+(T*);
6695 void addUnaryPlusPointerOverloads() {
6696 for (BuiltinCandidateTypeSet::iterator
6697 Ptr = CandidateTypes[0].pointer_begin(),
6698 PtrEnd = CandidateTypes[0].pointer_end();
6699 Ptr != PtrEnd; ++Ptr) {
6700 QualType ParamTy = *Ptr;
6701 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6702 }
6703 }
6704
6705 // C++ [over.built]p10:
6706 // For every promoted integral type T, there exist candidate
6707 // operator functions of the form
6708 //
6709 // T operator~(T);
6710 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006711 if (!HasArithmeticOrEnumeralCandidateType)
6712 return;
6713
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006714 for (unsigned Int = FirstPromotedIntegralType;
6715 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006716 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006717 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6718 }
6719
6720 // Extension: We also add this operator for vector types.
6721 for (BuiltinCandidateTypeSet::iterator
6722 Vec = CandidateTypes[0].vector_begin(),
6723 VecEnd = CandidateTypes[0].vector_end();
6724 Vec != VecEnd; ++Vec) {
6725 QualType VecTy = *Vec;
6726 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6727 }
6728 }
6729
6730 // C++ [over.match.oper]p16:
6731 // For every pointer to member type T, there exist candidate operator
6732 // functions of the form
6733 //
6734 // bool operator==(T,T);
6735 // bool operator!=(T,T);
6736 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6737 /// Set of (canonical) types that we've already handled.
6738 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6739
6740 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6741 for (BuiltinCandidateTypeSet::iterator
6742 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6743 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6744 MemPtr != MemPtrEnd;
6745 ++MemPtr) {
6746 // Don't add the same builtin candidate twice.
6747 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6748 continue;
6749
6750 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6751 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6752 CandidateSet);
6753 }
6754 }
6755 }
6756
6757 // C++ [over.built]p15:
6758 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006759 // For every T, where T is an enumeration type, a pointer type, or
6760 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006761 //
6762 // bool operator<(T, T);
6763 // bool operator>(T, T);
6764 // bool operator<=(T, T);
6765 // bool operator>=(T, T);
6766 // bool operator==(T, T);
6767 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006768 void addRelationalPointerOrEnumeralOverloads() {
6769 // C++ [over.built]p1:
6770 // If there is a user-written candidate with the same name and parameter
6771 // types as a built-in candidate operator function, the built-in operator
6772 // function is hidden and is not included in the set of candidate
6773 // functions.
6774 //
6775 // The text is actually in a note, but if we don't implement it then we end
6776 // up with ambiguities when the user provides an overloaded operator for
6777 // an enumeration type. Note that only enumeration types have this problem,
6778 // so we track which enumeration types we've seen operators for. Also, the
6779 // only other overloaded operator with enumeration argumenst, operator=,
6780 // cannot be overloaded for enumeration types, so this is the only place
6781 // where we must suppress candidates like this.
6782 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6783 UserDefinedBinaryOperators;
6784
6785 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6786 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6787 CandidateTypes[ArgIdx].enumeration_end()) {
6788 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6789 CEnd = CandidateSet.end();
6790 C != CEnd; ++C) {
6791 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6792 continue;
6793
6794 QualType FirstParamType =
6795 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6796 QualType SecondParamType =
6797 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6798
6799 // Skip if either parameter isn't of enumeral type.
6800 if (!FirstParamType->isEnumeralType() ||
6801 !SecondParamType->isEnumeralType())
6802 continue;
6803
6804 // Add this operator to the set of known user-defined operators.
6805 UserDefinedBinaryOperators.insert(
6806 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6807 S.Context.getCanonicalType(SecondParamType)));
6808 }
6809 }
6810 }
6811
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006812 /// Set of (canonical) types that we've already handled.
6813 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6814
6815 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6816 for (BuiltinCandidateTypeSet::iterator
6817 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6818 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6819 Ptr != PtrEnd; ++Ptr) {
6820 // Don't add the same builtin candidate twice.
6821 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6822 continue;
6823
6824 QualType ParamTypes[2] = { *Ptr, *Ptr };
6825 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6826 CandidateSet);
6827 }
6828 for (BuiltinCandidateTypeSet::iterator
6829 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6830 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6831 Enum != EnumEnd; ++Enum) {
6832 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6833
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006834 // Don't add the same builtin candidate twice, or if a user defined
6835 // candidate exists.
6836 if (!AddedTypes.insert(CanonType) ||
6837 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6838 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006839 continue;
6840
6841 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006842 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6843 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006844 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006845
6846 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6847 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6848 if (AddedTypes.insert(NullPtrTy) &&
6849 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6850 NullPtrTy))) {
6851 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6852 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6853 CandidateSet);
6854 }
6855 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006856 }
6857 }
6858
6859 // C++ [over.built]p13:
6860 //
6861 // For every cv-qualified or cv-unqualified object type T
6862 // there exist candidate operator functions of the form
6863 //
6864 // T* operator+(T*, ptrdiff_t);
6865 // T& operator[](T*, ptrdiff_t); [BELOW]
6866 // T* operator-(T*, ptrdiff_t);
6867 // T* operator+(ptrdiff_t, T*);
6868 // T& operator[](ptrdiff_t, T*); [BELOW]
6869 //
6870 // C++ [over.built]p14:
6871 //
6872 // For every T, where T is a pointer to object type, there
6873 // exist candidate operator functions of the form
6874 //
6875 // ptrdiff_t operator-(T, T);
6876 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6877 /// Set of (canonical) types that we've already handled.
6878 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6879
6880 for (int Arg = 0; Arg < 2; ++Arg) {
6881 QualType AsymetricParamTypes[2] = {
6882 S.Context.getPointerDiffType(),
6883 S.Context.getPointerDiffType(),
6884 };
6885 for (BuiltinCandidateTypeSet::iterator
6886 Ptr = CandidateTypes[Arg].pointer_begin(),
6887 PtrEnd = CandidateTypes[Arg].pointer_end();
6888 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006889 QualType PointeeTy = (*Ptr)->getPointeeType();
6890 if (!PointeeTy->isObjectType())
6891 continue;
6892
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006893 AsymetricParamTypes[Arg] = *Ptr;
6894 if (Arg == 0 || Op == OO_Plus) {
6895 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6896 // T* operator+(ptrdiff_t, T*);
6897 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6898 CandidateSet);
6899 }
6900 if (Op == OO_Minus) {
6901 // ptrdiff_t operator-(T, T);
6902 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6903 continue;
6904
6905 QualType ParamTypes[2] = { *Ptr, *Ptr };
6906 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6907 Args, 2, CandidateSet);
6908 }
6909 }
6910 }
6911 }
6912
6913 // C++ [over.built]p12:
6914 //
6915 // For every pair of promoted arithmetic types L and R, there
6916 // exist candidate operator functions of the form
6917 //
6918 // LR operator*(L, R);
6919 // LR operator/(L, R);
6920 // LR operator+(L, R);
6921 // LR operator-(L, R);
6922 // bool operator<(L, R);
6923 // bool operator>(L, R);
6924 // bool operator<=(L, R);
6925 // bool operator>=(L, R);
6926 // bool operator==(L, R);
6927 // bool operator!=(L, R);
6928 //
6929 // where LR is the result of the usual arithmetic conversions
6930 // between types L and R.
6931 //
6932 // C++ [over.built]p24:
6933 //
6934 // For every pair of promoted arithmetic types L and R, there exist
6935 // candidate operator functions of the form
6936 //
6937 // LR operator?(bool, L, R);
6938 //
6939 // where LR is the result of the usual arithmetic conversions
6940 // between types L and R.
6941 // Our candidates ignore the first parameter.
6942 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006943 if (!HasArithmeticOrEnumeralCandidateType)
6944 return;
6945
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006946 for (unsigned Left = FirstPromotedArithmeticType;
6947 Left < LastPromotedArithmeticType; ++Left) {
6948 for (unsigned Right = FirstPromotedArithmeticType;
6949 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006950 QualType LandR[2] = { getArithmeticType(Left),
6951 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006952 QualType Result =
6953 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006954 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006955 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6956 }
6957 }
6958
6959 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6960 // conditional operator for vector types.
6961 for (BuiltinCandidateTypeSet::iterator
6962 Vec1 = CandidateTypes[0].vector_begin(),
6963 Vec1End = CandidateTypes[0].vector_end();
6964 Vec1 != Vec1End; ++Vec1) {
6965 for (BuiltinCandidateTypeSet::iterator
6966 Vec2 = CandidateTypes[1].vector_begin(),
6967 Vec2End = CandidateTypes[1].vector_end();
6968 Vec2 != Vec2End; ++Vec2) {
6969 QualType LandR[2] = { *Vec1, *Vec2 };
6970 QualType Result = S.Context.BoolTy;
6971 if (!isComparison) {
6972 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6973 Result = *Vec1;
6974 else
6975 Result = *Vec2;
6976 }
6977
6978 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6979 }
6980 }
6981 }
6982
6983 // C++ [over.built]p17:
6984 //
6985 // For every pair of promoted integral types L and R, there
6986 // exist candidate operator functions of the form
6987 //
6988 // LR operator%(L, R);
6989 // LR operator&(L, R);
6990 // LR operator^(L, R);
6991 // LR operator|(L, R);
6992 // L operator<<(L, R);
6993 // L operator>>(L, R);
6994 //
6995 // where LR is the result of the usual arithmetic conversions
6996 // between types L and R.
6997 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006998 if (!HasArithmeticOrEnumeralCandidateType)
6999 return;
7000
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007001 for (unsigned Left = FirstPromotedIntegralType;
7002 Left < LastPromotedIntegralType; ++Left) {
7003 for (unsigned Right = FirstPromotedIntegralType;
7004 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007005 QualType LandR[2] = { getArithmeticType(Left),
7006 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007007 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7008 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007009 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007010 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7011 }
7012 }
7013 }
7014
7015 // C++ [over.built]p20:
7016 //
7017 // For every pair (T, VQ), where T is an enumeration or
7018 // pointer to member type and VQ is either volatile or
7019 // empty, there exist candidate operator functions of the form
7020 //
7021 // VQ T& operator=(VQ T&, T);
7022 void addAssignmentMemberPointerOrEnumeralOverloads() {
7023 /// Set of (canonical) types that we've already handled.
7024 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7025
7026 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7027 for (BuiltinCandidateTypeSet::iterator
7028 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7029 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7030 Enum != EnumEnd; ++Enum) {
7031 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7032 continue;
7033
7034 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7035 CandidateSet);
7036 }
7037
7038 for (BuiltinCandidateTypeSet::iterator
7039 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7040 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7041 MemPtr != MemPtrEnd; ++MemPtr) {
7042 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7043 continue;
7044
7045 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7046 CandidateSet);
7047 }
7048 }
7049 }
7050
7051 // C++ [over.built]p19:
7052 //
7053 // For every pair (T, VQ), where T is any type and VQ is either
7054 // volatile or empty, there exist candidate operator functions
7055 // of the form
7056 //
7057 // T*VQ& operator=(T*VQ&, T*);
7058 //
7059 // C++ [over.built]p21:
7060 //
7061 // For every pair (T, VQ), where T is a cv-qualified or
7062 // cv-unqualified object type and VQ is either volatile or
7063 // empty, there exist candidate operator functions of the form
7064 //
7065 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7066 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7067 void addAssignmentPointerOverloads(bool isEqualOp) {
7068 /// Set of (canonical) types that we've already handled.
7069 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7070
7071 for (BuiltinCandidateTypeSet::iterator
7072 Ptr = CandidateTypes[0].pointer_begin(),
7073 PtrEnd = CandidateTypes[0].pointer_end();
7074 Ptr != PtrEnd; ++Ptr) {
7075 // If this is operator=, keep track of the builtin candidates we added.
7076 if (isEqualOp)
7077 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007078 else if (!(*Ptr)->getPointeeType()->isObjectType())
7079 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007080
7081 // non-volatile version
7082 QualType ParamTypes[2] = {
7083 S.Context.getLValueReferenceType(*Ptr),
7084 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7085 };
7086 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7087 /*IsAssigmentOperator=*/ isEqualOp);
7088
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007089 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7090 VisibleTypeConversionsQuals.hasVolatile();
7091 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007092 // volatile version
7093 ParamTypes[0] =
7094 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7096 /*IsAssigmentOperator=*/isEqualOp);
7097 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007098
7099 if (!(*Ptr).isRestrictQualified() &&
7100 VisibleTypeConversionsQuals.hasRestrict()) {
7101 // restrict version
7102 ParamTypes[0]
7103 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7104 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7105 /*IsAssigmentOperator=*/isEqualOp);
7106
7107 if (NeedVolatile) {
7108 // volatile restrict version
7109 ParamTypes[0]
7110 = S.Context.getLValueReferenceType(
7111 S.Context.getCVRQualifiedType(*Ptr,
7112 (Qualifiers::Volatile |
7113 Qualifiers::Restrict)));
7114 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7115 CandidateSet,
7116 /*IsAssigmentOperator=*/isEqualOp);
7117 }
7118 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007119 }
7120
7121 if (isEqualOp) {
7122 for (BuiltinCandidateTypeSet::iterator
7123 Ptr = CandidateTypes[1].pointer_begin(),
7124 PtrEnd = CandidateTypes[1].pointer_end();
7125 Ptr != PtrEnd; ++Ptr) {
7126 // Make sure we don't add the same candidate twice.
7127 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7128 continue;
7129
Chandler Carruth6df868e2010-12-12 08:17:55 +00007130 QualType ParamTypes[2] = {
7131 S.Context.getLValueReferenceType(*Ptr),
7132 *Ptr,
7133 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007134
7135 // non-volatile version
7136 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7137 /*IsAssigmentOperator=*/true);
7138
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007139 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7140 VisibleTypeConversionsQuals.hasVolatile();
7141 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007142 // volatile version
7143 ParamTypes[0] =
7144 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007145 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7146 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007147 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007148
7149 if (!(*Ptr).isRestrictQualified() &&
7150 VisibleTypeConversionsQuals.hasRestrict()) {
7151 // restrict version
7152 ParamTypes[0]
7153 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7155 CandidateSet, /*IsAssigmentOperator=*/true);
7156
7157 if (NeedVolatile) {
7158 // volatile restrict version
7159 ParamTypes[0]
7160 = S.Context.getLValueReferenceType(
7161 S.Context.getCVRQualifiedType(*Ptr,
7162 (Qualifiers::Volatile |
7163 Qualifiers::Restrict)));
7164 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7165 CandidateSet, /*IsAssigmentOperator=*/true);
7166
7167 }
7168 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007169 }
7170 }
7171 }
7172
7173 // C++ [over.built]p18:
7174 //
7175 // For every triple (L, VQ, R), where L is an arithmetic type,
7176 // VQ is either volatile or empty, and R is a promoted
7177 // arithmetic type, there exist candidate operator functions of
7178 // the form
7179 //
7180 // VQ L& operator=(VQ L&, R);
7181 // VQ L& operator*=(VQ L&, R);
7182 // VQ L& operator/=(VQ L&, R);
7183 // VQ L& operator+=(VQ L&, R);
7184 // VQ L& operator-=(VQ L&, R);
7185 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007186 if (!HasArithmeticOrEnumeralCandidateType)
7187 return;
7188
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007189 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7190 for (unsigned Right = FirstPromotedArithmeticType;
7191 Right < LastPromotedArithmeticType; ++Right) {
7192 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007193 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007194
7195 // Add this built-in operator as a candidate (VQ is empty).
7196 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007197 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7199 /*IsAssigmentOperator=*/isEqualOp);
7200
7201 // Add this built-in operator as a candidate (VQ is 'volatile').
7202 if (VisibleTypeConversionsQuals.hasVolatile()) {
7203 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007204 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007205 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7207 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007208 /*IsAssigmentOperator=*/isEqualOp);
7209 }
7210 }
7211 }
7212
7213 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7214 for (BuiltinCandidateTypeSet::iterator
7215 Vec1 = CandidateTypes[0].vector_begin(),
7216 Vec1End = CandidateTypes[0].vector_end();
7217 Vec1 != Vec1End; ++Vec1) {
7218 for (BuiltinCandidateTypeSet::iterator
7219 Vec2 = CandidateTypes[1].vector_begin(),
7220 Vec2End = CandidateTypes[1].vector_end();
7221 Vec2 != Vec2End; ++Vec2) {
7222 QualType ParamTypes[2];
7223 ParamTypes[1] = *Vec2;
7224 // Add this built-in operator as a candidate (VQ is empty).
7225 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7226 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7227 /*IsAssigmentOperator=*/isEqualOp);
7228
7229 // Add this built-in operator as a candidate (VQ is 'volatile').
7230 if (VisibleTypeConversionsQuals.hasVolatile()) {
7231 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7232 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007233 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7234 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007235 /*IsAssigmentOperator=*/isEqualOp);
7236 }
7237 }
7238 }
7239 }
7240
7241 // C++ [over.built]p22:
7242 //
7243 // For every triple (L, VQ, R), where L is an integral type, VQ
7244 // is either volatile or empty, and R is a promoted integral
7245 // type, there exist candidate operator functions of the form
7246 //
7247 // VQ L& operator%=(VQ L&, R);
7248 // VQ L& operator<<=(VQ L&, R);
7249 // VQ L& operator>>=(VQ L&, R);
7250 // VQ L& operator&=(VQ L&, R);
7251 // VQ L& operator^=(VQ L&, R);
7252 // VQ L& operator|=(VQ L&, R);
7253 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007254 if (!HasArithmeticOrEnumeralCandidateType)
7255 return;
7256
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007257 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7258 for (unsigned Right = FirstPromotedIntegralType;
7259 Right < LastPromotedIntegralType; ++Right) {
7260 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007261 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007262
7263 // Add this built-in operator as a candidate (VQ is empty).
7264 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007265 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7267 if (VisibleTypeConversionsQuals.hasVolatile()) {
7268 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007269 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007270 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7271 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7272 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7273 CandidateSet);
7274 }
7275 }
7276 }
7277 }
7278
7279 // C++ [over.operator]p23:
7280 //
7281 // There also exist candidate operator functions of the form
7282 //
7283 // bool operator!(bool);
7284 // bool operator&&(bool, bool);
7285 // bool operator||(bool, bool);
7286 void addExclaimOverload() {
7287 QualType ParamTy = S.Context.BoolTy;
7288 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7289 /*IsAssignmentOperator=*/false,
7290 /*NumContextualBoolArguments=*/1);
7291 }
7292 void addAmpAmpOrPipePipeOverload() {
7293 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7294 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7295 /*IsAssignmentOperator=*/false,
7296 /*NumContextualBoolArguments=*/2);
7297 }
7298
7299 // C++ [over.built]p13:
7300 //
7301 // For every cv-qualified or cv-unqualified object type T there
7302 // exist candidate operator functions of the form
7303 //
7304 // T* operator+(T*, ptrdiff_t); [ABOVE]
7305 // T& operator[](T*, ptrdiff_t);
7306 // T* operator-(T*, ptrdiff_t); [ABOVE]
7307 // T* operator+(ptrdiff_t, T*); [ABOVE]
7308 // T& operator[](ptrdiff_t, T*);
7309 void addSubscriptOverloads() {
7310 for (BuiltinCandidateTypeSet::iterator
7311 Ptr = CandidateTypes[0].pointer_begin(),
7312 PtrEnd = CandidateTypes[0].pointer_end();
7313 Ptr != PtrEnd; ++Ptr) {
7314 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7315 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007316 if (!PointeeType->isObjectType())
7317 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007318
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007319 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7320
7321 // T& operator[](T*, ptrdiff_t)
7322 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7323 }
7324
7325 for (BuiltinCandidateTypeSet::iterator
7326 Ptr = CandidateTypes[1].pointer_begin(),
7327 PtrEnd = CandidateTypes[1].pointer_end();
7328 Ptr != PtrEnd; ++Ptr) {
7329 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7330 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007331 if (!PointeeType->isObjectType())
7332 continue;
7333
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007334 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7335
7336 // T& operator[](ptrdiff_t, T*)
7337 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7338 }
7339 }
7340
7341 // C++ [over.built]p11:
7342 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7343 // C1 is the same type as C2 or is a derived class of C2, T is an object
7344 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7345 // there exist candidate operator functions of the form
7346 //
7347 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7348 //
7349 // where CV12 is the union of CV1 and CV2.
7350 void addArrowStarOverloads() {
7351 for (BuiltinCandidateTypeSet::iterator
7352 Ptr = CandidateTypes[0].pointer_begin(),
7353 PtrEnd = CandidateTypes[0].pointer_end();
7354 Ptr != PtrEnd; ++Ptr) {
7355 QualType C1Ty = (*Ptr);
7356 QualType C1;
7357 QualifierCollector Q1;
7358 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7359 if (!isa<RecordType>(C1))
7360 continue;
7361 // heuristic to reduce number of builtin candidates in the set.
7362 // Add volatile/restrict version only if there are conversions to a
7363 // volatile/restrict type.
7364 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7365 continue;
7366 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7367 continue;
7368 for (BuiltinCandidateTypeSet::iterator
7369 MemPtr = CandidateTypes[1].member_pointer_begin(),
7370 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7371 MemPtr != MemPtrEnd; ++MemPtr) {
7372 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7373 QualType C2 = QualType(mptr->getClass(), 0);
7374 C2 = C2.getUnqualifiedType();
7375 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7376 break;
7377 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7378 // build CV12 T&
7379 QualType T = mptr->getPointeeType();
7380 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7381 T.isVolatileQualified())
7382 continue;
7383 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7384 T.isRestrictQualified())
7385 continue;
7386 T = Q1.apply(S.Context, T);
7387 QualType ResultTy = S.Context.getLValueReferenceType(T);
7388 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7389 }
7390 }
7391 }
7392
7393 // Note that we don't consider the first argument, since it has been
7394 // contextually converted to bool long ago. The candidates below are
7395 // therefore added as binary.
7396 //
7397 // C++ [over.built]p25:
7398 // For every type T, where T is a pointer, pointer-to-member, or scoped
7399 // enumeration type, there exist candidate operator functions of the form
7400 //
7401 // T operator?(bool, T, T);
7402 //
7403 void addConditionalOperatorOverloads() {
7404 /// Set of (canonical) types that we've already handled.
7405 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7406
7407 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7408 for (BuiltinCandidateTypeSet::iterator
7409 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7410 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7411 Ptr != PtrEnd; ++Ptr) {
7412 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7413 continue;
7414
7415 QualType ParamTypes[2] = { *Ptr, *Ptr };
7416 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7417 }
7418
7419 for (BuiltinCandidateTypeSet::iterator
7420 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7421 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7422 MemPtr != MemPtrEnd; ++MemPtr) {
7423 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7424 continue;
7425
7426 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7427 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7428 }
7429
David Blaikie4e4d0842012-03-11 07:00:24 +00007430 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007431 for (BuiltinCandidateTypeSet::iterator
7432 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7433 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7434 Enum != EnumEnd; ++Enum) {
7435 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7436 continue;
7437
7438 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7439 continue;
7440
7441 QualType ParamTypes[2] = { *Enum, *Enum };
7442 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7443 }
7444 }
7445 }
7446 }
7447};
7448
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007449} // end anonymous namespace
7450
7451/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7452/// operator overloads to the candidate set (C++ [over.built]), based
7453/// on the operator @p Op and the arguments given. For example, if the
7454/// operator is a binary '+', this routine might add "int
7455/// operator+(int, int)" to cover integer addition.
7456void
7457Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7458 SourceLocation OpLoc,
7459 Expr **Args, unsigned NumArgs,
7460 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007461 // Find all of the types that the arguments can convert to, but only
7462 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007463 // that make use of these types. Also record whether we encounter non-record
7464 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007465 Qualifiers VisibleTypeConversionsQuals;
7466 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007467 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7468 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007469
7470 bool HasNonRecordCandidateType = false;
7471 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007472 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007473 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7474 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7475 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7476 OpLoc,
7477 true,
7478 (Op == OO_Exclaim ||
7479 Op == OO_AmpAmp ||
7480 Op == OO_PipePipe),
7481 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007482 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7483 CandidateTypes[ArgIdx].hasNonRecordTypes();
7484 HasArithmeticOrEnumeralCandidateType =
7485 HasArithmeticOrEnumeralCandidateType ||
7486 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007487 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007488
Chandler Carruth6a577462010-12-13 01:44:01 +00007489 // Exit early when no non-record types have been added to the candidate set
7490 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007491 //
7492 // We can't exit early for !, ||, or &&, since there we have always have
7493 // 'bool' overloads.
7494 if (!HasNonRecordCandidateType &&
7495 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007496 return;
7497
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007498 // Setup an object to manage the common state for building overloads.
7499 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7500 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007501 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007502 CandidateTypes, CandidateSet);
7503
7504 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007505 switch (Op) {
7506 case OO_None:
7507 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007508 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007509
Chandler Carruthabb71842010-12-12 08:51:33 +00007510 case OO_New:
7511 case OO_Delete:
7512 case OO_Array_New:
7513 case OO_Array_Delete:
7514 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007515 llvm_unreachable(
7516 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007517
7518 case OO_Comma:
7519 case OO_Arrow:
7520 // C++ [over.match.oper]p3:
7521 // -- For the operator ',', the unary operator '&', or the
7522 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007523 break;
7524
7525 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007526 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007527 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007528 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007529
7530 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007531 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007532 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007533 } else {
7534 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7535 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7536 }
Douglas Gregor74253732008-11-19 15:42:04 +00007537 break;
7538
Chandler Carruthabb71842010-12-12 08:51:33 +00007539 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007540 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007541 OpBuilder.addUnaryStarPointerOverloads();
7542 else
7543 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7544 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007545
Chandler Carruthabb71842010-12-12 08:51:33 +00007546 case OO_Slash:
7547 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007548 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007549
7550 case OO_PlusPlus:
7551 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007552 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7553 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007554 break;
7555
Douglas Gregor19b7b152009-08-24 13:43:27 +00007556 case OO_EqualEqual:
7557 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007558 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007559 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007560
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007561 case OO_Less:
7562 case OO_Greater:
7563 case OO_LessEqual:
7564 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007565 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007566 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7567 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007568
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007569 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007570 case OO_Caret:
7571 case OO_Pipe:
7572 case OO_LessLess:
7573 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007574 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007575 break;
7576
Chandler Carruthabb71842010-12-12 08:51:33 +00007577 case OO_Amp: // '&' is either unary or binary
7578 if (NumArgs == 1)
7579 // C++ [over.match.oper]p3:
7580 // -- For the operator ',', the unary operator '&', or the
7581 // operator '->', the built-in candidates set is empty.
7582 break;
7583
7584 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7585 break;
7586
7587 case OO_Tilde:
7588 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7589 break;
7590
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007591 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007592 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007593 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007594
7595 case OO_PlusEqual:
7596 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007597 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007598 // Fall through.
7599
7600 case OO_StarEqual:
7601 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007602 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007603 break;
7604
7605 case OO_PercentEqual:
7606 case OO_LessLessEqual:
7607 case OO_GreaterGreaterEqual:
7608 case OO_AmpEqual:
7609 case OO_CaretEqual:
7610 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007611 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007612 break;
7613
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007614 case OO_Exclaim:
7615 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007616 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007617
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007618 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007619 case OO_PipePipe:
7620 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007621 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007622
7623 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007624 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007625 break;
7626
7627 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007628 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007630
7631 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007633 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7634 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007635 }
7636}
7637
Douglas Gregorfa047642009-02-04 00:32:51 +00007638/// \brief Add function candidates found via argument-dependent lookup
7639/// to the set of overloading candidates.
7640///
7641/// This routine performs argument-dependent name lookup based on the
7642/// given function name (which may also be an operator name) and adds
7643/// all of the overload candidates found by ADL to the overload
7644/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007645void
Douglas Gregorfa047642009-02-04 00:32:51 +00007646Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007647 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007648 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007649 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007650 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007651 bool PartialOverloading,
7652 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007653 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007654
John McCalla113e722010-01-26 06:04:06 +00007655 // FIXME: This approach for uniquing ADL results (and removing
7656 // redundant candidates from the set) relies on pointer-equality,
7657 // which means we need to key off the canonical decl. However,
7658 // always going back to the canonical decl might not get us the
7659 // right set of default arguments. What default arguments are
7660 // we supposed to consider on ADL candidates, anyway?
7661
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007662 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007663 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007664 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007665
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007666 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007667 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7668 CandEnd = CandidateSet.end();
7669 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007670 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007671 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007672 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007673 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007674 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007675
7676 // For each of the ADL candidates we found, add it to the overload
7677 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007678 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007679 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007680 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007681 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007682 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007683
Ahmed Charles13a140c2012-02-25 11:00:22 +00007684 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7685 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007686 } else
John McCall6e266892010-01-26 03:27:55 +00007687 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007688 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007689 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007690 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007691}
7692
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007693/// isBetterOverloadCandidate - Determines whether the first overload
7694/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007695bool
John McCall120d63c2010-08-24 20:38:10 +00007696isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007697 const OverloadCandidate &Cand1,
7698 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007699 SourceLocation Loc,
7700 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007701 // Define viable functions to be better candidates than non-viable
7702 // functions.
7703 if (!Cand2.Viable)
7704 return Cand1.Viable;
7705 else if (!Cand1.Viable)
7706 return false;
7707
Douglas Gregor88a35142008-12-22 05:46:06 +00007708 // C++ [over.match.best]p1:
7709 //
7710 // -- if F is a static member function, ICS1(F) is defined such
7711 // that ICS1(F) is neither better nor worse than ICS1(G) for
7712 // any function G, and, symmetrically, ICS1(G) is neither
7713 // better nor worse than ICS1(F).
7714 unsigned StartArg = 0;
7715 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7716 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007717
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007718 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007719 // A viable function F1 is defined to be a better function than another
7720 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007721 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007722 unsigned NumArgs = Cand1.NumConversions;
7723 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007724 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007725 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007726 switch (CompareImplicitConversionSequences(S,
7727 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007728 Cand2.Conversions[ArgIdx])) {
7729 case ImplicitConversionSequence::Better:
7730 // Cand1 has a better conversion sequence.
7731 HasBetterConversion = true;
7732 break;
7733
7734 case ImplicitConversionSequence::Worse:
7735 // Cand1 can't be better than Cand2.
7736 return false;
7737
7738 case ImplicitConversionSequence::Indistinguishable:
7739 // Do nothing.
7740 break;
7741 }
7742 }
7743
Mike Stump1eb44332009-09-09 15:08:12 +00007744 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007745 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007746 if (HasBetterConversion)
7747 return true;
7748
Mike Stump1eb44332009-09-09 15:08:12 +00007749 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007750 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007751 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007752 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7753 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007754
7755 // -- F1 and F2 are function template specializations, and the function
7756 // template for F1 is more specialized than the template for F2
7757 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007758 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007759 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007760 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007761 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007762 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7763 Cand2.Function->getPrimaryTemplate(),
7764 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007765 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007766 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007767 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007768 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007769 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007770
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007771 // -- the context is an initialization by user-defined conversion
7772 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7773 // from the return type of F1 to the destination type (i.e.,
7774 // the type of the entity being initialized) is a better
7775 // conversion sequence than the standard conversion sequence
7776 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007777 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007778 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007779 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007780 // First check whether we prefer one of the conversion functions over the
7781 // other. This only distinguishes the results in non-standard, extension
7782 // cases such as the conversion from a lambda closure type to a function
7783 // pointer or block.
7784 ImplicitConversionSequence::CompareKind FuncResult
7785 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7786 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7787 return FuncResult;
7788
John McCall120d63c2010-08-24 20:38:10 +00007789 switch (CompareStandardConversionSequences(S,
7790 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007791 Cand2.FinalConversion)) {
7792 case ImplicitConversionSequence::Better:
7793 // Cand1 has a better conversion sequence.
7794 return true;
7795
7796 case ImplicitConversionSequence::Worse:
7797 // Cand1 can't be better than Cand2.
7798 return false;
7799
7800 case ImplicitConversionSequence::Indistinguishable:
7801 // Do nothing
7802 break;
7803 }
7804 }
7805
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007806 return false;
7807}
7808
Mike Stump1eb44332009-09-09 15:08:12 +00007809/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007810/// within an overload candidate set.
7811///
James Dennettefce31f2012-06-22 08:10:18 +00007812/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007813/// which overload resolution occurs.
7814///
James Dennettefce31f2012-06-22 08:10:18 +00007815/// \param Best If overload resolution was successful or found a deleted
7816/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007817///
7818/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007819OverloadingResult
7820OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007821 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007822 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007823 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007824 Best = end();
7825 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7826 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007827 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007828 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007829 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007830 }
7831
7832 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007833 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007834 return OR_No_Viable_Function;
7835
7836 // Make sure that this function is better than every other viable
7837 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007838 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007839 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007840 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007841 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007842 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007843 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007844 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007845 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007846 }
Mike Stump1eb44332009-09-09 15:08:12 +00007847
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007848 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007849 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007850 (Best->Function->isDeleted() ||
7851 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007852 return OR_Deleted;
7853
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007854 return OR_Success;
7855}
7856
John McCall3c80f572010-01-12 02:15:36 +00007857namespace {
7858
7859enum OverloadCandidateKind {
7860 oc_function,
7861 oc_method,
7862 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007863 oc_function_template,
7864 oc_method_template,
7865 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007866 oc_implicit_default_constructor,
7867 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007868 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007869 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007870 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007871 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007872};
7873
John McCall220ccbf2010-01-13 00:25:19 +00007874OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7875 FunctionDecl *Fn,
7876 std::string &Description) {
7877 bool isTemplate = false;
7878
7879 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7880 isTemplate = true;
7881 Description = S.getTemplateArgumentBindingsText(
7882 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7883 }
John McCallb1622a12010-01-06 09:43:14 +00007884
7885 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007886 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007887 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007888
Sebastian Redlf677ea32011-02-05 19:23:19 +00007889 if (Ctor->getInheritedConstructor())
7890 return oc_implicit_inherited_constructor;
7891
Sean Hunt82713172011-05-25 23:16:36 +00007892 if (Ctor->isDefaultConstructor())
7893 return oc_implicit_default_constructor;
7894
7895 if (Ctor->isMoveConstructor())
7896 return oc_implicit_move_constructor;
7897
7898 assert(Ctor->isCopyConstructor() &&
7899 "unexpected sort of implicit constructor");
7900 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007901 }
7902
7903 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7904 // This actually gets spelled 'candidate function' for now, but
7905 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007906 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007907 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007908
Sean Hunt82713172011-05-25 23:16:36 +00007909 if (Meth->isMoveAssignmentOperator())
7910 return oc_implicit_move_assignment;
7911
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007912 if (Meth->isCopyAssignmentOperator())
7913 return oc_implicit_copy_assignment;
7914
7915 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7916 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007917 }
7918
John McCall220ccbf2010-01-13 00:25:19 +00007919 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007920}
7921
Sebastian Redlf677ea32011-02-05 19:23:19 +00007922void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7923 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7924 if (!Ctor) return;
7925
7926 Ctor = Ctor->getInheritedConstructor();
7927 if (!Ctor) return;
7928
7929 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7930}
7931
John McCall3c80f572010-01-12 02:15:36 +00007932} // end anonymous namespace
7933
7934// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007935void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007936 std::string FnDesc;
7937 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007938 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7939 << (unsigned) K << FnDesc;
7940 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7941 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007942 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007943}
7944
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007945//Notes the location of all overload candidates designated through
7946// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007947void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007948 assert(OverloadedExpr->getType() == Context.OverloadTy);
7949
7950 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7951 OverloadExpr *OvlExpr = Ovl.Expression;
7952
7953 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7954 IEnd = OvlExpr->decls_end();
7955 I != IEnd; ++I) {
7956 if (FunctionTemplateDecl *FunTmpl =
7957 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007958 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007959 } else if (FunctionDecl *Fun
7960 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007961 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007962 }
7963 }
7964}
7965
John McCall1d318332010-01-12 00:44:57 +00007966/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7967/// "lead" diagnostic; it will be given two arguments, the source and
7968/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007969void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7970 Sema &S,
7971 SourceLocation CaretLoc,
7972 const PartialDiagnostic &PDiag) const {
7973 S.Diag(CaretLoc, PDiag)
7974 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007975 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007976 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7977 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007978 }
John McCall81201622010-01-08 04:41:39 +00007979}
7980
John McCall1d318332010-01-12 00:44:57 +00007981namespace {
7982
John McCalladbb8f82010-01-13 09:16:55 +00007983void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7984 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7985 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007986 assert(Cand->Function && "for now, candidate must be a function");
7987 FunctionDecl *Fn = Cand->Function;
7988
7989 // There's a conversion slot for the object argument if this is a
7990 // non-constructor method. Note that 'I' corresponds the
7991 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007992 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007993 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007994 if (I == 0)
7995 isObjectArgument = true;
7996 else
7997 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007998 }
7999
John McCall220ccbf2010-01-13 00:25:19 +00008000 std::string FnDesc;
8001 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8002
John McCalladbb8f82010-01-13 09:16:55 +00008003 Expr *FromExpr = Conv.Bad.FromExpr;
8004 QualType FromTy = Conv.Bad.getFromType();
8005 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008006
John McCall5920dbb2010-02-02 02:42:52 +00008007 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008008 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008009 Expr *E = FromExpr->IgnoreParens();
8010 if (isa<UnaryOperator>(E))
8011 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008012 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008013
8014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8015 << (unsigned) FnKind << FnDesc
8016 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8017 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008018 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008019 return;
8020 }
8021
John McCall258b2032010-01-23 08:10:49 +00008022 // Do some hand-waving analysis to see if the non-viability is due
8023 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008024 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8025 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8026 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8027 CToTy = RT->getPointeeType();
8028 else {
8029 // TODO: detect and diagnose the full richness of const mismatches.
8030 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8031 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8032 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8033 }
8034
8035 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8036 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008037 Qualifiers FromQs = CFromTy.getQualifiers();
8038 Qualifiers ToQs = CToTy.getQualifiers();
8039
8040 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8041 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8042 << (unsigned) FnKind << FnDesc
8043 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8044 << FromTy
8045 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8046 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008047 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008048 return;
8049 }
8050
John McCallf85e1932011-06-15 23:02:42 +00008051 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008052 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008053 << (unsigned) FnKind << FnDesc
8054 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8055 << FromTy
8056 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8057 << (unsigned) isObjectArgument << I+1;
8058 MaybeEmitInheritedConstructorNote(S, Fn);
8059 return;
8060 }
8061
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008062 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8063 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8064 << (unsigned) FnKind << FnDesc
8065 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8066 << FromTy
8067 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8068 << (unsigned) isObjectArgument << I+1;
8069 MaybeEmitInheritedConstructorNote(S, Fn);
8070 return;
8071 }
8072
John McCall651f3ee2010-01-14 03:28:57 +00008073 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8074 assert(CVR && "unexpected qualifiers mismatch");
8075
8076 if (isObjectArgument) {
8077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8078 << (unsigned) FnKind << FnDesc
8079 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8080 << FromTy << (CVR - 1);
8081 } else {
8082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8083 << (unsigned) FnKind << FnDesc
8084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8085 << FromTy << (CVR - 1) << I+1;
8086 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008087 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008088 return;
8089 }
8090
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008091 // Special diagnostic for failure to convert an initializer list, since
8092 // telling the user that it has type void is not useful.
8093 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8095 << (unsigned) FnKind << FnDesc
8096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8097 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8098 MaybeEmitInheritedConstructorNote(S, Fn);
8099 return;
8100 }
8101
John McCall258b2032010-01-23 08:10:49 +00008102 // Diagnose references or pointers to incomplete types differently,
8103 // since it's far from impossible that the incompleteness triggered
8104 // the failure.
8105 QualType TempFromTy = FromTy.getNonReferenceType();
8106 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8107 TempFromTy = PTy->getPointeeType();
8108 if (TempFromTy->isIncompleteType()) {
8109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8110 << (unsigned) FnKind << FnDesc
8111 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8112 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008113 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008114 return;
8115 }
8116
Douglas Gregor85789812010-06-30 23:01:39 +00008117 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008118 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008119 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8120 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8121 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8122 FromPtrTy->getPointeeType()) &&
8123 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8124 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008125 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008126 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008127 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008128 }
8129 } else if (const ObjCObjectPointerType *FromPtrTy
8130 = FromTy->getAs<ObjCObjectPointerType>()) {
8131 if (const ObjCObjectPointerType *ToPtrTy
8132 = ToTy->getAs<ObjCObjectPointerType>())
8133 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8134 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8135 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8136 FromPtrTy->getPointeeType()) &&
8137 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008138 BaseToDerivedConversion = 2;
8139 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008140 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8141 !FromTy->isIncompleteType() &&
8142 !ToRefTy->getPointeeType()->isIncompleteType() &&
8143 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8144 BaseToDerivedConversion = 3;
8145 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8146 ToTy.getNonReferenceType().getCanonicalType() ==
8147 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008148 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8149 << (unsigned) FnKind << FnDesc
8150 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8151 << (unsigned) isObjectArgument << I + 1;
8152 MaybeEmitInheritedConstructorNote(S, Fn);
8153 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008154 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008156
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008157 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008158 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008159 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008160 << (unsigned) FnKind << FnDesc
8161 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008162 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008163 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008164 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008165 return;
8166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008167
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008168 if (isa<ObjCObjectPointerType>(CFromTy) &&
8169 isa<PointerType>(CToTy)) {
8170 Qualifiers FromQs = CFromTy.getQualifiers();
8171 Qualifiers ToQs = CToTy.getQualifiers();
8172 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8174 << (unsigned) FnKind << FnDesc
8175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8176 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8177 MaybeEmitInheritedConstructorNote(S, Fn);
8178 return;
8179 }
8180 }
8181
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008182 // Emit the generic diagnostic and, optionally, add the hints to it.
8183 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8184 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008186 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8187 << (unsigned) (Cand->Fix.Kind);
8188
8189 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008190 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8191 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008192 FDiag << *HI;
8193 S.Diag(Fn->getLocation(), FDiag);
8194
Sebastian Redlf677ea32011-02-05 19:23:19 +00008195 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008196}
8197
8198void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8199 unsigned NumFormalArgs) {
8200 // TODO: treat calls to a missing default constructor as a special case
8201
8202 FunctionDecl *Fn = Cand->Function;
8203 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8204
8205 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008206
Douglas Gregor439d3c32011-05-05 00:13:13 +00008207 // With invalid overloaded operators, it's possible that we think we
8208 // have an arity mismatch when it fact it looks like we have the
8209 // right number of arguments, because only overloaded operators have
8210 // the weird behavior of overloading member and non-member functions.
8211 // Just don't report anything.
8212 if (Fn->isInvalidDecl() &&
8213 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8214 return;
8215
John McCalladbb8f82010-01-13 09:16:55 +00008216 // at least / at most / exactly
8217 unsigned mode, modeCount;
8218 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008219 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8220 (Cand->FailureKind == ovl_fail_bad_deduction &&
8221 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008222 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008223 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008224 mode = 0; // "at least"
8225 else
8226 mode = 2; // "exactly"
8227 modeCount = MinParams;
8228 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008229 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8230 (Cand->FailureKind == ovl_fail_bad_deduction &&
8231 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008232 if (MinParams != FnTy->getNumArgs())
8233 mode = 1; // "at most"
8234 else
8235 mode = 2; // "exactly"
8236 modeCount = FnTy->getNumArgs();
8237 }
8238
8239 std::string Description;
8240 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8241
Richard Smithf7b80562012-05-11 05:16:41 +00008242 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8244 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8245 << Fn->getParamDecl(0) << NumFormalArgs;
8246 else
8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8249 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008250 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008251}
8252
John McCall342fec42010-02-01 18:53:26 +00008253/// Diagnose a failed template-argument deduction.
8254void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008255 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008256 FunctionDecl *Fn = Cand->Function; // pattern
8257
Douglas Gregora9333192010-05-08 17:41:32 +00008258 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008259 NamedDecl *ParamD;
8260 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8261 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8262 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008263 switch (Cand->DeductionFailure.Result) {
8264 case Sema::TDK_Success:
8265 llvm_unreachable("TDK_success while diagnosing bad deduction");
8266
8267 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008268 assert(ParamD && "no parameter found for incomplete deduction result");
8269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8270 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008271 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008272 return;
8273 }
8274
John McCall57e97782010-08-05 09:05:08 +00008275 case Sema::TDK_Underqualified: {
8276 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8277 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8278
8279 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8280
8281 // Param will have been canonicalized, but it should just be a
8282 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008283 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008284 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008285 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008286 assert(S.Context.hasSameType(Param, NonCanonParam));
8287
8288 // Arg has also been canonicalized, but there's nothing we can do
8289 // about that. It also doesn't matter as much, because it won't
8290 // have any template parameters in it (because deduction isn't
8291 // done on dependent types).
8292 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8293
8294 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8295 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008296 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008297 return;
8298 }
8299
8300 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008301 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008302 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008303 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008304 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008305 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008306 which = 1;
8307 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008308 which = 2;
8309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008310
Douglas Gregora9333192010-05-08 17:41:32 +00008311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008312 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008313 << *Cand->DeductionFailure.getFirstArg()
8314 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008315 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008316 return;
8317 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008318
Douglas Gregorf1a84452010-05-08 19:15:54 +00008319 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008320 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008321 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008322 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008323 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8324 << ParamD->getDeclName();
8325 else {
8326 int index = 0;
8327 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8328 index = TTP->getIndex();
8329 else if (NonTypeTemplateParmDecl *NTTP
8330 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8331 index = NTTP->getIndex();
8332 else
8333 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008334 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008335 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8336 << (index + 1);
8337 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008338 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008339 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008340
Douglas Gregora18592e2010-05-08 18:13:28 +00008341 case Sema::TDK_TooManyArguments:
8342 case Sema::TDK_TooFewArguments:
8343 DiagnoseArityMismatch(S, Cand, NumArgs);
8344 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008345
8346 case Sema::TDK_InstantiationDepth:
8347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008348 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008349 return;
8350
8351 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008352 // Format the template argument list into the argument string.
8353 llvm::SmallString<128> TemplateArgString;
8354 if (TemplateArgumentList *Args =
8355 Cand->DeductionFailure.getTemplateArgumentList()) {
8356 TemplateArgString = " ";
8357 TemplateArgString += S.getTemplateArgumentBindingsText(
8358 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8359 }
8360
Richard Smith4493c0a2012-05-09 05:17:00 +00008361 // If this candidate was disabled by enable_if, say so.
8362 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8363 if (PDiag && PDiag->second.getDiagID() ==
8364 diag::err_typename_nested_not_found_enable_if) {
8365 // FIXME: Use the source range of the condition, and the fully-qualified
8366 // name of the enable_if template. These are both present in PDiag.
8367 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8368 << "'enable_if'" << TemplateArgString;
8369 return;
8370 }
8371
Richard Smithb8590f32012-05-07 09:03:25 +00008372 // Format the SFINAE diagnostic into the argument string.
8373 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8374 // formatted message in another diagnostic.
8375 llvm::SmallString<128> SFINAEArgString;
8376 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008377 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008378 SFINAEArgString = ": ";
8379 R = SourceRange(PDiag->first, PDiag->first);
8380 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8381 }
8382
Douglas Gregorec20f462010-05-08 20:07:26 +00008383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008384 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008385 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008386 return;
8387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008388
John McCall342fec42010-02-01 18:53:26 +00008389 // TODO: diagnose these individually, then kill off
8390 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008391 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008392 case Sema::TDK_FailedOverloadResolution:
8393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008394 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008395 return;
8396 }
8397}
8398
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008399/// CUDA: diagnose an invalid call across targets.
8400void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8401 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8402 FunctionDecl *Callee = Cand->Function;
8403
8404 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8405 CalleeTarget = S.IdentifyCUDATarget(Callee);
8406
8407 std::string FnDesc;
8408 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8409
8410 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8411 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8412}
8413
John McCall342fec42010-02-01 18:53:26 +00008414/// Generates a 'note' diagnostic for an overload candidate. We've
8415/// already generated a primary error at the call site.
8416///
8417/// It really does need to be a single diagnostic with its caret
8418/// pointed at the candidate declaration. Yes, this creates some
8419/// major challenges of technical writing. Yes, this makes pointing
8420/// out problems with specific arguments quite awkward. It's still
8421/// better than generating twenty screens of text for every failed
8422/// overload.
8423///
8424/// It would be great to be able to express per-candidate problems
8425/// more richly for those diagnostic clients that cared, but we'd
8426/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008427void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008428 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008429 FunctionDecl *Fn = Cand->Function;
8430
John McCall81201622010-01-08 04:41:39 +00008431 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008432 if (Cand->Viable && (Fn->isDeleted() ||
8433 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008434 std::string FnDesc;
8435 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008436
8437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008438 << FnKind << FnDesc
8439 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008440 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008441 return;
John McCall81201622010-01-08 04:41:39 +00008442 }
8443
John McCall220ccbf2010-01-13 00:25:19 +00008444 // We don't really have anything else to say about viable candidates.
8445 if (Cand->Viable) {
8446 S.NoteOverloadCandidate(Fn);
8447 return;
8448 }
John McCall1d318332010-01-12 00:44:57 +00008449
John McCalladbb8f82010-01-13 09:16:55 +00008450 switch (Cand->FailureKind) {
8451 case ovl_fail_too_many_arguments:
8452 case ovl_fail_too_few_arguments:
8453 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008454
John McCalladbb8f82010-01-13 09:16:55 +00008455 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008456 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008457
John McCall717e8912010-01-23 05:17:32 +00008458 case ovl_fail_trivial_conversion:
8459 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008460 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008461 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008462
John McCallb1bdc622010-02-25 01:37:24 +00008463 case ovl_fail_bad_conversion: {
8464 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008465 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008466 if (Cand->Conversions[I].isBad())
8467 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008468
John McCalladbb8f82010-01-13 09:16:55 +00008469 // FIXME: this currently happens when we're called from SemaInit
8470 // when user-conversion overload fails. Figure out how to handle
8471 // those conditions and diagnose them well.
8472 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008473 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008474
8475 case ovl_fail_bad_target:
8476 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008477 }
John McCalla1d7d622010-01-08 00:58:21 +00008478}
8479
8480void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8481 // Desugar the type of the surrogate down to a function type,
8482 // retaining as many typedefs as possible while still showing
8483 // the function type (and, therefore, its parameter types).
8484 QualType FnType = Cand->Surrogate->getConversionType();
8485 bool isLValueReference = false;
8486 bool isRValueReference = false;
8487 bool isPointer = false;
8488 if (const LValueReferenceType *FnTypeRef =
8489 FnType->getAs<LValueReferenceType>()) {
8490 FnType = FnTypeRef->getPointeeType();
8491 isLValueReference = true;
8492 } else if (const RValueReferenceType *FnTypeRef =
8493 FnType->getAs<RValueReferenceType>()) {
8494 FnType = FnTypeRef->getPointeeType();
8495 isRValueReference = true;
8496 }
8497 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8498 FnType = FnTypePtr->getPointeeType();
8499 isPointer = true;
8500 }
8501 // Desugar down to a function type.
8502 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8503 // Reconstruct the pointer/reference as appropriate.
8504 if (isPointer) FnType = S.Context.getPointerType(FnType);
8505 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8506 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8507
8508 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8509 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008510 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008511}
8512
8513void NoteBuiltinOperatorCandidate(Sema &S,
8514 const char *Opc,
8515 SourceLocation OpLoc,
8516 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008517 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008518 std::string TypeStr("operator");
8519 TypeStr += Opc;
8520 TypeStr += "(";
8521 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008522 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008523 TypeStr += ")";
8524 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8525 } else {
8526 TypeStr += ", ";
8527 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8528 TypeStr += ")";
8529 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8530 }
8531}
8532
8533void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8534 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008535 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008536 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8537 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008538 if (ICS.isBad()) break; // all meaningless after first invalid
8539 if (!ICS.isAmbiguous()) continue;
8540
John McCall120d63c2010-08-24 20:38:10 +00008541 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008542 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008543 }
8544}
8545
John McCall1b77e732010-01-15 23:32:50 +00008546SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8547 if (Cand->Function)
8548 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008549 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008550 return Cand->Surrogate->getLocation();
8551 return SourceLocation();
8552}
8553
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008554static unsigned
8555RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008556 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008557 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008558 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008559
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008560 case Sema::TDK_Incomplete:
8561 return 1;
8562
8563 case Sema::TDK_Underqualified:
8564 case Sema::TDK_Inconsistent:
8565 return 2;
8566
8567 case Sema::TDK_SubstitutionFailure:
8568 case Sema::TDK_NonDeducedMismatch:
8569 return 3;
8570
8571 case Sema::TDK_InstantiationDepth:
8572 case Sema::TDK_FailedOverloadResolution:
8573 return 4;
8574
8575 case Sema::TDK_InvalidExplicitArguments:
8576 return 5;
8577
8578 case Sema::TDK_TooManyArguments:
8579 case Sema::TDK_TooFewArguments:
8580 return 6;
8581 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008582 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008583}
8584
John McCallbf65c0b2010-01-12 00:48:53 +00008585struct CompareOverloadCandidatesForDisplay {
8586 Sema &S;
8587 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008588
8589 bool operator()(const OverloadCandidate *L,
8590 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008591 // Fast-path this check.
8592 if (L == R) return false;
8593
John McCall81201622010-01-08 04:41:39 +00008594 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008595 if (L->Viable) {
8596 if (!R->Viable) return true;
8597
8598 // TODO: introduce a tri-valued comparison for overload
8599 // candidates. Would be more worthwhile if we had a sort
8600 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008601 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8602 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008603 } else if (R->Viable)
8604 return false;
John McCall81201622010-01-08 04:41:39 +00008605
John McCall1b77e732010-01-15 23:32:50 +00008606 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008607
John McCall1b77e732010-01-15 23:32:50 +00008608 // Criteria by which we can sort non-viable candidates:
8609 if (!L->Viable) {
8610 // 1. Arity mismatches come after other candidates.
8611 if (L->FailureKind == ovl_fail_too_many_arguments ||
8612 L->FailureKind == ovl_fail_too_few_arguments)
8613 return false;
8614 if (R->FailureKind == ovl_fail_too_many_arguments ||
8615 R->FailureKind == ovl_fail_too_few_arguments)
8616 return true;
John McCall81201622010-01-08 04:41:39 +00008617
John McCall717e8912010-01-23 05:17:32 +00008618 // 2. Bad conversions come first and are ordered by the number
8619 // of bad conversions and quality of good conversions.
8620 if (L->FailureKind == ovl_fail_bad_conversion) {
8621 if (R->FailureKind != ovl_fail_bad_conversion)
8622 return true;
8623
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008624 // The conversion that can be fixed with a smaller number of changes,
8625 // comes first.
8626 unsigned numLFixes = L->Fix.NumConversionsFixed;
8627 unsigned numRFixes = R->Fix.NumConversionsFixed;
8628 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8629 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008630 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008631 if (numLFixes < numRFixes)
8632 return true;
8633 else
8634 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008635 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008636
John McCall717e8912010-01-23 05:17:32 +00008637 // If there's any ordering between the defined conversions...
8638 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008639 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008640
8641 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008642 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008643 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008644 switch (CompareImplicitConversionSequences(S,
8645 L->Conversions[I],
8646 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008647 case ImplicitConversionSequence::Better:
8648 leftBetter++;
8649 break;
8650
8651 case ImplicitConversionSequence::Worse:
8652 leftBetter--;
8653 break;
8654
8655 case ImplicitConversionSequence::Indistinguishable:
8656 break;
8657 }
8658 }
8659 if (leftBetter > 0) return true;
8660 if (leftBetter < 0) return false;
8661
8662 } else if (R->FailureKind == ovl_fail_bad_conversion)
8663 return false;
8664
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008665 if (L->FailureKind == ovl_fail_bad_deduction) {
8666 if (R->FailureKind != ovl_fail_bad_deduction)
8667 return true;
8668
8669 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8670 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008671 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008672 } else if (R->FailureKind == ovl_fail_bad_deduction)
8673 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008674
John McCall1b77e732010-01-15 23:32:50 +00008675 // TODO: others?
8676 }
8677
8678 // Sort everything else by location.
8679 SourceLocation LLoc = GetLocationForCandidate(L);
8680 SourceLocation RLoc = GetLocationForCandidate(R);
8681
8682 // Put candidates without locations (e.g. builtins) at the end.
8683 if (LLoc.isInvalid()) return false;
8684 if (RLoc.isInvalid()) return true;
8685
8686 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008687 }
8688};
8689
John McCall717e8912010-01-23 05:17:32 +00008690/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008691/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008692void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008693 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008694 assert(!Cand->Viable);
8695
8696 // Don't do anything on failures other than bad conversion.
8697 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8698
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008699 // We only want the FixIts if all the arguments can be corrected.
8700 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008701 // Use a implicit copy initialization to check conversion fixes.
8702 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008703
John McCall717e8912010-01-23 05:17:32 +00008704 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008705 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008706 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008707 while (true) {
8708 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8709 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008710 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008711 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008712 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008713 }
John McCall717e8912010-01-23 05:17:32 +00008714 }
8715
8716 if (ConvIdx == ConvCount)
8717 return;
8718
John McCallb1bdc622010-02-25 01:37:24 +00008719 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8720 "remaining conversion is initialized?");
8721
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008722 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008723 // operation somehow.
8724 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008725
8726 const FunctionProtoType* Proto;
8727 unsigned ArgIdx = ConvIdx;
8728
8729 if (Cand->IsSurrogate) {
8730 QualType ConvType
8731 = Cand->Surrogate->getConversionType().getNonReferenceType();
8732 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8733 ConvType = ConvPtrType->getPointeeType();
8734 Proto = ConvType->getAs<FunctionProtoType>();
8735 ArgIdx--;
8736 } else if (Cand->Function) {
8737 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8738 if (isa<CXXMethodDecl>(Cand->Function) &&
8739 !isa<CXXConstructorDecl>(Cand->Function))
8740 ArgIdx--;
8741 } else {
8742 // Builtin binary operator with a bad first conversion.
8743 assert(ConvCount <= 3);
8744 for (; ConvIdx != ConvCount; ++ConvIdx)
8745 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008746 = TryCopyInitialization(S, Args[ConvIdx],
8747 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008748 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008749 /*InOverloadResolution*/ true,
8750 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008751 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008752 return;
8753 }
8754
8755 // Fill in the rest of the conversions.
8756 unsigned NumArgsInProto = Proto->getNumArgs();
8757 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008758 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008759 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008760 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008761 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008762 /*InOverloadResolution=*/true,
8763 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008764 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008765 // Store the FixIt in the candidate if it exists.
8766 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008767 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008768 }
John McCall717e8912010-01-23 05:17:32 +00008769 else
8770 Cand->Conversions[ConvIdx].setEllipsis();
8771 }
8772}
8773
John McCalla1d7d622010-01-08 00:58:21 +00008774} // end anonymous namespace
8775
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008776/// PrintOverloadCandidates - When overload resolution fails, prints
8777/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008778/// set.
John McCall120d63c2010-08-24 20:38:10 +00008779void OverloadCandidateSet::NoteCandidates(Sema &S,
8780 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008781 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008782 const char *Opc,
8783 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008784 // Sort the candidates by viability and position. Sorting directly would
8785 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008786 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008787 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8788 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008789 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008790 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008791 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008792 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008793 if (Cand->Function || Cand->IsSurrogate)
8794 Cands.push_back(Cand);
8795 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8796 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008797 }
8798 }
8799
John McCallbf65c0b2010-01-12 00:48:53 +00008800 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008801 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008802
John McCall1d318332010-01-12 00:44:57 +00008803 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008804
Chris Lattner5f9e2722011-07-23 10:55:15 +00008805 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008806 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8807 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008808 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008809 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8810 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008811
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008812 // Set an arbitrary limit on the number of candidate functions we'll spam
8813 // the user with. FIXME: This limit should depend on details of the
8814 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008815 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008816 break;
8817 }
8818 ++CandsShown;
8819
John McCalla1d7d622010-01-08 00:58:21 +00008820 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008821 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008822 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008823 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008824 else {
8825 assert(Cand->Viable &&
8826 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008827 // Generally we only see ambiguities including viable builtin
8828 // operators if overload resolution got screwed up by an
8829 // ambiguous user-defined conversion.
8830 //
8831 // FIXME: It's quite possible for different conversions to see
8832 // different ambiguities, though.
8833 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008834 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008835 ReportedAmbiguousConversions = true;
8836 }
John McCalla1d7d622010-01-08 00:58:21 +00008837
John McCall1d318332010-01-12 00:44:57 +00008838 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008839 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008840 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008841 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008842
8843 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008844 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008845}
8846
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008847// [PossiblyAFunctionType] --> [Return]
8848// NonFunctionType --> NonFunctionType
8849// R (A) --> R(A)
8850// R (*)(A) --> R (A)
8851// R (&)(A) --> R (A)
8852// R (S::*)(A) --> R (A)
8853QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8854 QualType Ret = PossiblyAFunctionType;
8855 if (const PointerType *ToTypePtr =
8856 PossiblyAFunctionType->getAs<PointerType>())
8857 Ret = ToTypePtr->getPointeeType();
8858 else if (const ReferenceType *ToTypeRef =
8859 PossiblyAFunctionType->getAs<ReferenceType>())
8860 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008861 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008862 PossiblyAFunctionType->getAs<MemberPointerType>())
8863 Ret = MemTypePtr->getPointeeType();
8864 Ret =
8865 Context.getCanonicalType(Ret).getUnqualifiedType();
8866 return Ret;
8867}
Douglas Gregor904eed32008-11-10 20:40:00 +00008868
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008869// A helper class to help with address of function resolution
8870// - allows us to avoid passing around all those ugly parameters
8871class AddressOfFunctionResolver
8872{
8873 Sema& S;
8874 Expr* SourceExpr;
8875 const QualType& TargetType;
8876 QualType TargetFunctionType; // Extracted function type from target type
8877
8878 bool Complain;
8879 //DeclAccessPair& ResultFunctionAccessPair;
8880 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008881
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008882 bool TargetTypeIsNonStaticMemberFunction;
8883 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008884
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008885 OverloadExpr::FindResult OvlExprInfo;
8886 OverloadExpr *OvlExpr;
8887 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008888 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008889
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008890public:
8891 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8892 const QualType& TargetType, bool Complain)
8893 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8894 Complain(Complain), Context(S.getASTContext()),
8895 TargetTypeIsNonStaticMemberFunction(
8896 !!TargetType->getAs<MemberPointerType>()),
8897 FoundNonTemplateFunction(false),
8898 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8899 OvlExpr(OvlExprInfo.Expression)
8900 {
8901 ExtractUnqualifiedFunctionTypeFromTargetType();
8902
8903 if (!TargetFunctionType->isFunctionType()) {
8904 if (OvlExpr->hasExplicitTemplateArgs()) {
8905 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008906 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008907 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008908
8909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8910 if (!Method->isStatic()) {
8911 // If the target type is a non-function type and the function
8912 // found is a non-static member function, pretend as if that was
8913 // the target, it's the only possible type to end up with.
8914 TargetTypeIsNonStaticMemberFunction = true;
8915
8916 // And skip adding the function if its not in the proper form.
8917 // We'll diagnose this due to an empty set of functions.
8918 if (!OvlExprInfo.HasFormOfMemberPointer)
8919 return;
8920 }
8921 }
8922
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008923 Matches.push_back(std::make_pair(dap,Fn));
8924 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008925 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008926 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008927 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008928
8929 if (OvlExpr->hasExplicitTemplateArgs())
8930 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008931
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008932 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8933 // C++ [over.over]p4:
8934 // If more than one function is selected, [...]
8935 if (Matches.size() > 1) {
8936 if (FoundNonTemplateFunction)
8937 EliminateAllTemplateMatches();
8938 else
8939 EliminateAllExceptMostSpecializedTemplate();
8940 }
8941 }
8942 }
8943
8944private:
8945 bool isTargetTypeAFunction() const {
8946 return TargetFunctionType->isFunctionType();
8947 }
8948
8949 // [ToType] [Return]
8950
8951 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8952 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8953 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8954 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8955 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8956 }
8957
8958 // return true if any matching specializations were found
8959 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8960 const DeclAccessPair& CurAccessFunPair) {
8961 if (CXXMethodDecl *Method
8962 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8963 // Skip non-static function templates when converting to pointer, and
8964 // static when converting to member pointer.
8965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8966 return false;
8967 }
8968 else if (TargetTypeIsNonStaticMemberFunction)
8969 return false;
8970
8971 // C++ [over.over]p2:
8972 // If the name is a function template, template argument deduction is
8973 // done (14.8.2.2), and if the argument deduction succeeds, the
8974 // resulting template argument list is used to generate a single
8975 // function template specialization, which is added to the set of
8976 // overloaded functions considered.
8977 FunctionDecl *Specialization = 0;
8978 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8979 if (Sema::TemplateDeductionResult Result
8980 = S.DeduceTemplateArguments(FunctionTemplate,
8981 &OvlExplicitTemplateArgs,
8982 TargetFunctionType, Specialization,
8983 Info)) {
8984 // FIXME: make a note of the failed deduction for diagnostics.
8985 (void)Result;
8986 return false;
8987 }
8988
8989 // Template argument deduction ensures that we have an exact match.
8990 // This function template specicalization works.
8991 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8992 assert(TargetFunctionType
8993 == Context.getCanonicalType(Specialization->getType()));
8994 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8995 return true;
8996 }
8997
8998 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8999 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009000 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009001 // Skip non-static functions when converting to pointer, and static
9002 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009003 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9004 return false;
9005 }
9006 else if (TargetTypeIsNonStaticMemberFunction)
9007 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009008
Chandler Carruthbd647292009-12-29 06:17:27 +00009009 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009010 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009011 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9012 if (S.CheckCUDATarget(Caller, FunDecl))
9013 return false;
9014
Douglas Gregor43c79c22009-12-09 00:47:37 +00009015 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009016 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9017 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009018 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9019 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009020 Matches.push_back(std::make_pair(CurAccessFunPair,
9021 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009022 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009023 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009024 }
Mike Stump1eb44332009-09-09 15:08:12 +00009025 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009026
9027 return false;
9028 }
9029
9030 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9031 bool Ret = false;
9032
9033 // If the overload expression doesn't have the form of a pointer to
9034 // member, don't try to convert it to a pointer-to-member type.
9035 if (IsInvalidFormOfPointerToMemberFunction())
9036 return false;
9037
9038 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9039 E = OvlExpr->decls_end();
9040 I != E; ++I) {
9041 // Look through any using declarations to find the underlying function.
9042 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9043
9044 // C++ [over.over]p3:
9045 // Non-member functions and static member functions match
9046 // targets of type "pointer-to-function" or "reference-to-function."
9047 // Nonstatic member functions match targets of
9048 // type "pointer-to-member-function."
9049 // Note that according to DR 247, the containing class does not matter.
9050 if (FunctionTemplateDecl *FunctionTemplate
9051 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9052 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9053 Ret = true;
9054 }
9055 // If we have explicit template arguments supplied, skip non-templates.
9056 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9057 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9058 Ret = true;
9059 }
9060 assert(Ret || Matches.empty());
9061 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009062 }
9063
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009064 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009065 // [...] and any given function template specialization F1 is
9066 // eliminated if the set contains a second function template
9067 // specialization whose function template is more specialized
9068 // than the function template of F1 according to the partial
9069 // ordering rules of 14.5.5.2.
9070
9071 // The algorithm specified above is quadratic. We instead use a
9072 // two-pass algorithm (similar to the one used to identify the
9073 // best viable function in an overload set) that identifies the
9074 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009075
9076 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9077 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9078 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009079
John McCallc373d482010-01-27 01:50:18 +00009080 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009081 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9082 TPOC_Other, 0, SourceExpr->getLocStart(),
9083 S.PDiag(),
9084 S.PDiag(diag::err_addr_ovl_ambiguous)
9085 << Matches[0].second->getDeclName(),
9086 S.PDiag(diag::note_ovl_candidate)
9087 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009088 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009089
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009090 if (Result != MatchesCopy.end()) {
9091 // Make it the first and only element
9092 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9093 Matches[0].second = cast<FunctionDecl>(*Result);
9094 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009095 }
9096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009097
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009098 void EliminateAllTemplateMatches() {
9099 // [...] any function template specializations in the set are
9100 // eliminated if the set also contains a non-template function, [...]
9101 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9102 if (Matches[I].second->getPrimaryTemplate() == 0)
9103 ++I;
9104 else {
9105 Matches[I] = Matches[--N];
9106 Matches.set_size(N);
9107 }
9108 }
9109 }
9110
9111public:
9112 void ComplainNoMatchesFound() const {
9113 assert(Matches.empty());
9114 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9115 << OvlExpr->getName() << TargetFunctionType
9116 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009117 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009118 }
9119
9120 bool IsInvalidFormOfPointerToMemberFunction() const {
9121 return TargetTypeIsNonStaticMemberFunction &&
9122 !OvlExprInfo.HasFormOfMemberPointer;
9123 }
9124
9125 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9126 // TODO: Should we condition this on whether any functions might
9127 // have matched, or is it more appropriate to do that in callers?
9128 // TODO: a fixit wouldn't hurt.
9129 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9130 << TargetType << OvlExpr->getSourceRange();
9131 }
9132
9133 void ComplainOfInvalidConversion() const {
9134 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9135 << OvlExpr->getName() << TargetType;
9136 }
9137
9138 void ComplainMultipleMatchesFound() const {
9139 assert(Matches.size() > 1);
9140 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9141 << OvlExpr->getName()
9142 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009143 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009145
9146 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9147
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009148 int getNumMatches() const { return Matches.size(); }
9149
9150 FunctionDecl* getMatchingFunctionDecl() const {
9151 if (Matches.size() != 1) return 0;
9152 return Matches[0].second;
9153 }
9154
9155 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9156 if (Matches.size() != 1) return 0;
9157 return &Matches[0].first;
9158 }
9159};
9160
9161/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9162/// an overloaded function (C++ [over.over]), where @p From is an
9163/// expression with overloaded function type and @p ToType is the type
9164/// we're trying to resolve to. For example:
9165///
9166/// @code
9167/// int f(double);
9168/// int f(int);
9169///
9170/// int (*pfd)(double) = f; // selects f(double)
9171/// @endcode
9172///
9173/// This routine returns the resulting FunctionDecl if it could be
9174/// resolved, and NULL otherwise. When @p Complain is true, this
9175/// routine will emit diagnostics if there is an error.
9176FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009177Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9178 QualType TargetType,
9179 bool Complain,
9180 DeclAccessPair &FoundResult,
9181 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009182 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009183
9184 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9185 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009186 int NumMatches = Resolver.getNumMatches();
9187 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009188 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009189 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9190 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9191 else
9192 Resolver.ComplainNoMatchesFound();
9193 }
9194 else if (NumMatches > 1 && Complain)
9195 Resolver.ComplainMultipleMatchesFound();
9196 else if (NumMatches == 1) {
9197 Fn = Resolver.getMatchingFunctionDecl();
9198 assert(Fn);
9199 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009200 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009201 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009202 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009203 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009204
9205 if (pHadMultipleCandidates)
9206 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009207 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009208}
9209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009210/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009211/// resolve that overloaded function expression down to a single function.
9212///
9213/// This routine can only resolve template-ids that refer to a single function
9214/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009215/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009216/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009217FunctionDecl *
9218Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9219 bool Complain,
9220 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009221 // C++ [over.over]p1:
9222 // [...] [Note: any redundant set of parentheses surrounding the
9223 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009224 // C++ [over.over]p1:
9225 // [...] The overloaded function name can be preceded by the &
9226 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009227
Douglas Gregor4b52e252009-12-21 23:17:24 +00009228 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009229 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009230 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009231
9232 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009233 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009234
Douglas Gregor4b52e252009-12-21 23:17:24 +00009235 // Look through all of the overloaded functions, searching for one
9236 // whose type matches exactly.
9237 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009238 for (UnresolvedSetIterator I = ovl->decls_begin(),
9239 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009240 // C++0x [temp.arg.explicit]p3:
9241 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009242 // where deduction is not done, if a template argument list is
9243 // specified and it, along with any default template arguments,
9244 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009245 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009246 FunctionTemplateDecl *FunctionTemplate
9247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009248
Douglas Gregor4b52e252009-12-21 23:17:24 +00009249 // C++ [over.over]p2:
9250 // If the name is a function template, template argument deduction is
9251 // done (14.8.2.2), and if the argument deduction succeeds, the
9252 // resulting template argument list is used to generate a single
9253 // function template specialization, which is added to the set of
9254 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009255 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009256 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009257 if (TemplateDeductionResult Result
9258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9259 Specialization, Info)) {
9260 // FIXME: make a note of the failed deduction for diagnostics.
9261 (void)Result;
9262 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009263 }
9264
John McCall864c0412011-04-26 20:42:42 +00009265 assert(Specialization && "no specialization and no error?");
9266
Douglas Gregor4b52e252009-12-21 23:17:24 +00009267 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009268 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009269 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009270 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9271 << ovl->getName();
9272 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009273 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009274 return 0;
John McCall864c0412011-04-26 20:42:42 +00009275 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009276
John McCall864c0412011-04-26 20:42:42 +00009277 Matched = Specialization;
9278 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009280
Douglas Gregor4b52e252009-12-21 23:17:24 +00009281 return Matched;
9282}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009283
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009284
9285
9286
John McCall6dbba4f2011-10-11 23:14:30 +00009287// Resolve and fix an overloaded expression that can be resolved
9288// because it identifies a single function template specialization.
9289//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009290// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009291//
9292// Return true if it was logically possible to so resolve the
9293// expression, regardless of whether or not it succeeded. Always
9294// returns true if 'complain' is set.
9295bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9296 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9297 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009298 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009299 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009300 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009301
John McCall6dbba4f2011-10-11 23:14:30 +00009302 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009303
John McCall864c0412011-04-26 20:42:42 +00009304 DeclAccessPair found;
9305 ExprResult SingleFunctionExpression;
9306 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9307 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009308 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009309 SrcExpr = ExprError();
9310 return true;
9311 }
John McCall864c0412011-04-26 20:42:42 +00009312
9313 // It is only correct to resolve to an instance method if we're
9314 // resolving a form that's permitted to be a pointer to member.
9315 // Otherwise we'll end up making a bound member expression, which
9316 // is illegal in all the contexts we resolve like this.
9317 if (!ovl.HasFormOfMemberPointer &&
9318 isa<CXXMethodDecl>(fn) &&
9319 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009320 if (!complain) return false;
9321
9322 Diag(ovl.Expression->getExprLoc(),
9323 diag::err_bound_member_function)
9324 << 0 << ovl.Expression->getSourceRange();
9325
9326 // TODO: I believe we only end up here if there's a mix of
9327 // static and non-static candidates (otherwise the expression
9328 // would have 'bound member' type, not 'overload' type).
9329 // Ideally we would note which candidate was chosen and why
9330 // the static candidates were rejected.
9331 SrcExpr = ExprError();
9332 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009333 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009334
John McCall864c0412011-04-26 20:42:42 +00009335 // Fix the expresion to refer to 'fn'.
9336 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009337 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009338
9339 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009340 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009341 SingleFunctionExpression =
9342 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009343 if (SingleFunctionExpression.isInvalid()) {
9344 SrcExpr = ExprError();
9345 return true;
9346 }
9347 }
John McCall864c0412011-04-26 20:42:42 +00009348 }
9349
9350 if (!SingleFunctionExpression.isUsable()) {
9351 if (complain) {
9352 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9353 << ovl.Expression->getName()
9354 << DestTypeForComplaining
9355 << OpRangeForComplaining
9356 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009357 NoteAllOverloadCandidates(SrcExpr.get());
9358
9359 SrcExpr = ExprError();
9360 return true;
9361 }
9362
9363 return false;
John McCall864c0412011-04-26 20:42:42 +00009364 }
9365
John McCall6dbba4f2011-10-11 23:14:30 +00009366 SrcExpr = SingleFunctionExpression;
9367 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009368}
9369
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009370/// \brief Add a single candidate to the overload set.
9371static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009372 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009373 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009374 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009375 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009376 bool PartialOverloading,
9377 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009378 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009379 if (isa<UsingShadowDecl>(Callee))
9380 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9381
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009382 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009383 if (ExplicitTemplateArgs) {
9384 assert(!KnownValid && "Explicit template arguments?");
9385 return;
9386 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009387 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9388 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009389 return;
John McCallba135432009-11-21 08:51:07 +00009390 }
9391
9392 if (FunctionTemplateDecl *FuncTemplate
9393 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009394 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009395 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009396 return;
9397 }
9398
Richard Smith2ced0442011-06-26 22:19:54 +00009399 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009400}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009401
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009402/// \brief Add the overload candidates named by callee and/or found by argument
9403/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009404void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009405 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009406 OverloadCandidateSet &CandidateSet,
9407 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009408
9409#ifndef NDEBUG
9410 // Verify that ArgumentDependentLookup is consistent with the rules
9411 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009412 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009413 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9414 // and let Y be the lookup set produced by argument dependent
9415 // lookup (defined as follows). If X contains
9416 //
9417 // -- a declaration of a class member, or
9418 //
9419 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009420 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009421 //
9422 // -- a declaration that is neither a function or a function
9423 // template
9424 //
9425 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009426
John McCall3b4294e2009-12-16 12:17:52 +00009427 if (ULE->requiresADL()) {
9428 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9429 E = ULE->decls_end(); I != E; ++I) {
9430 assert(!(*I)->getDeclContext()->isRecord());
9431 assert(isa<UsingShadowDecl>(*I) ||
9432 !(*I)->getDeclContext()->isFunctionOrMethod());
9433 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009434 }
9435 }
9436#endif
9437
John McCall3b4294e2009-12-16 12:17:52 +00009438 // It would be nice to avoid this copy.
9439 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009440 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009441 if (ULE->hasExplicitTemplateArgs()) {
9442 ULE->copyTemplateArgumentsInto(TABuffer);
9443 ExplicitTemplateArgs = &TABuffer;
9444 }
9445
9446 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9447 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009448 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9449 CandidateSet, PartialOverloading,
9450 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009451
John McCall3b4294e2009-12-16 12:17:52 +00009452 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009453 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009454 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009455 Args, ExplicitTemplateArgs,
9456 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009457 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009458}
John McCall578b69b2009-12-16 08:11:27 +00009459
Richard Smithf50e88a2011-06-05 22:42:48 +00009460/// Attempt to recover from an ill-formed use of a non-dependent name in a
9461/// template, where the non-dependent name was declared after the template
9462/// was defined. This is common in code written for a compilers which do not
9463/// correctly implement two-stage name lookup.
9464///
9465/// Returns true if a viable candidate was found and a diagnostic was issued.
9466static bool
9467DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9468 const CXXScopeSpec &SS, LookupResult &R,
9469 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009470 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009471 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9472 return false;
9473
9474 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009475 if (DC->isTransparentContext())
9476 continue;
9477
Richard Smithf50e88a2011-06-05 22:42:48 +00009478 SemaRef.LookupQualifiedName(R, DC);
9479
9480 if (!R.empty()) {
9481 R.suppressDiagnostics();
9482
9483 if (isa<CXXRecordDecl>(DC)) {
9484 // Don't diagnose names we find in classes; we get much better
9485 // diagnostics for these from DiagnoseEmptyLookup.
9486 R.clear();
9487 return false;
9488 }
9489
9490 OverloadCandidateSet Candidates(FnLoc);
9491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9492 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009493 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009494 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009495
9496 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009497 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009498 // No viable functions. Don't bother the user with notes for functions
9499 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009500 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009501 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009502 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009503
9504 // Find the namespaces where ADL would have looked, and suggest
9505 // declaring the function there instead.
9506 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9507 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009508 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009509 AssociatedNamespaces,
9510 AssociatedClasses);
9511 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009512 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009513 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009514 for (Sema::AssociatedNamespaceSet::iterator
9515 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009516 end = AssociatedNamespaces.end(); it != end; ++it) {
9517 if (!Std->Encloses(*it))
9518 SuggestedNamespaces.insert(*it);
9519 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009520 } else {
9521 // Lacking the 'std::' namespace, use all of the associated namespaces.
9522 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009523 }
9524
9525 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9526 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009527 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009528 SemaRef.Diag(Best->Function->getLocation(),
9529 diag::note_not_found_by_two_phase_lookup)
9530 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009531 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009532 SemaRef.Diag(Best->Function->getLocation(),
9533 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009534 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009535 } else {
9536 // FIXME: It would be useful to list the associated namespaces here,
9537 // but the diagnostics infrastructure doesn't provide a way to produce
9538 // a localized representation of a list of items.
9539 SemaRef.Diag(Best->Function->getLocation(),
9540 diag::note_not_found_by_two_phase_lookup)
9541 << R.getLookupName() << 2;
9542 }
9543
9544 // Try to recover by calling this function.
9545 return true;
9546 }
9547
9548 R.clear();
9549 }
9550
9551 return false;
9552}
9553
9554/// Attempt to recover from ill-formed use of a non-dependent operator in a
9555/// template, where the non-dependent operator was declared after the template
9556/// was defined.
9557///
9558/// Returns true if a viable candidate was found and a diagnostic was issued.
9559static bool
9560DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9561 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009562 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009563 DeclarationName OpName =
9564 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9565 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9566 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009567 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009568}
9569
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009570namespace {
9571// Callback to limit the allowed keywords and to only accept typo corrections
9572// that are keywords or whose decls refer to functions (or template functions)
9573// that accept the given number of arguments.
9574class RecoveryCallCCC : public CorrectionCandidateCallback {
9575 public:
9576 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9577 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009578 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009579 WantRemainingKeywords = false;
9580 }
9581
9582 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9583 if (!candidate.getCorrectionDecl())
9584 return candidate.isKeyword();
9585
9586 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9587 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9588 FunctionDecl *FD = 0;
9589 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9590 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9591 FD = FTD->getTemplatedDecl();
9592 if (!HasExplicitTemplateArgs && !FD) {
9593 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9594 // If the Decl is neither a function nor a template function,
9595 // determine if it is a pointer or reference to a function. If so,
9596 // check against the number of arguments expected for the pointee.
9597 QualType ValType = cast<ValueDecl>(ND)->getType();
9598 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9599 ValType = ValType->getPointeeType();
9600 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9601 if (FPT->getNumArgs() == NumArgs)
9602 return true;
9603 }
9604 }
9605 if (FD && FD->getNumParams() >= NumArgs &&
9606 FD->getMinRequiredArguments() <= NumArgs)
9607 return true;
9608 }
9609 return false;
9610 }
9611
9612 private:
9613 unsigned NumArgs;
9614 bool HasExplicitTemplateArgs;
9615};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009616
9617// Callback that effectively disabled typo correction
9618class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9619 public:
9620 NoTypoCorrectionCCC() {
9621 WantTypeSpecifiers = false;
9622 WantExpressionKeywords = false;
9623 WantCXXNamedCasts = false;
9624 WantRemainingKeywords = false;
9625 }
9626
9627 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9628 return false;
9629 }
9630};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009631}
9632
John McCall578b69b2009-12-16 08:11:27 +00009633/// Attempts to recover from a call where no functions were found.
9634///
9635/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009636static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009637BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009638 UnresolvedLookupExpr *ULE,
9639 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009640 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009641 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009642 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009643
9644 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009645 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009646 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009647
John McCall3b4294e2009-12-16 12:17:52 +00009648 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009649 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009650 if (ULE->hasExplicitTemplateArgs()) {
9651 ULE->copyTemplateArgumentsInto(TABuffer);
9652 ExplicitTemplateArgs = &TABuffer;
9653 }
9654
John McCall578b69b2009-12-16 08:11:27 +00009655 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9656 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009657 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009658 NoTypoCorrectionCCC RejectAll;
9659 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9660 (CorrectionCandidateCallback*)&Validator :
9661 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009662 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009663 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009664 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009665 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009666 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009667 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009668
John McCall3b4294e2009-12-16 12:17:52 +00009669 assert(!R.empty() && "lookup results empty despite recovery");
9670
9671 // Build an implicit member call if appropriate. Just drop the
9672 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009673 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009674 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009675 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9676 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009677 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009678 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009679 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009680 else
9681 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9682
9683 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009684 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009685
9686 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009687 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009688 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009689 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009690 MultiExprArg(Args.data(), Args.size()),
9691 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009692}
Douglas Gregord7a95972010-06-08 17:35:15 +00009693
Douglas Gregorf6b89692008-11-26 05:54:23 +00009694/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009695/// (which eventually refers to the declaration Func) and the call
9696/// arguments Args/NumArgs, attempt to resolve the function call down
9697/// to a specific function. If overload resolution succeeds, returns
9698/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009699/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009700/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009701ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009702Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009703 SourceLocation LParenLoc,
9704 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009705 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009706 Expr *ExecConfig,
9707 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009708#ifndef NDEBUG
9709 if (ULE->requiresADL()) {
9710 // To do ADL, we must have found an unqualified name.
9711 assert(!ULE->getQualifier() && "qualified name with ADL");
9712
9713 // We don't perform ADL for implicit declarations of builtins.
9714 // Verify that this was correctly set up.
9715 FunctionDecl *F;
9716 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9717 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9718 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009719 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009720
John McCall3b4294e2009-12-16 12:17:52 +00009721 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009722 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009723 } else
9724 assert(!ULE->isStdAssociatedNamespace() &&
9725 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009726#endif
9727
John McCall5acb0c92011-10-17 18:40:02 +00009728 UnbridgedCastsSet UnbridgedCasts;
9729 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9730 return ExprError();
9731
John McCall5769d612010-02-08 23:07:23 +00009732 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009733
John McCall3b4294e2009-12-16 12:17:52 +00009734 // Add the functions denoted by the callee to the set of candidate
9735 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009736 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9737 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009738
9739 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009740 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9741 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009742 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009743 // In Microsoft mode, if we are inside a template class member function then
9744 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009745 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009746 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009747 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009748 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009749 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9750 Context.DependentTy, VK_RValue,
9751 RParenLoc);
9752 CE->setTypeDependent(true);
9753 return Owned(CE);
9754 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009755 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9756 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009757 RParenLoc, /*EmptyLookup=*/true,
9758 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009759 }
John McCall578b69b2009-12-16 08:11:27 +00009760
John McCall5acb0c92011-10-17 18:40:02 +00009761 UnbridgedCasts.restore();
9762
Douglas Gregorf6b89692008-11-26 05:54:23 +00009763 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009764 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009765 case OR_Success: {
9766 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009767 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009768 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009769 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009770 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009771 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9772 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009773 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009774
Richard Smithf50e88a2011-06-05 22:42:48 +00009775 case OR_No_Viable_Function: {
9776 // Try to recover by looking for viable functions which the user might
9777 // have meant to call.
9778 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009779 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9780 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009781 /*EmptyLookup=*/false,
9782 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009783 if (!Recovery.isInvalid())
9784 return Recovery;
9785
Daniel Dunbar96a00142012-03-09 18:35:03 +00009786 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009787 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009788 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009789 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9790 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009791 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009792 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009793
9794 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009795 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009796 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009797 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9798 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009799 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009800
9801 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009802 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009803 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009804 << Best->Function->isDeleted()
9805 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009806 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009807 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9809 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009810
9811 // We emitted an error for the unvailable/deleted function call but keep
9812 // the call in the AST.
9813 FunctionDecl *FDecl = Best->Function;
9814 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9815 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9816 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009817 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009818 }
9819
Douglas Gregorff331c12010-07-25 18:17:45 +00009820 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009821 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009822}
9823
John McCall6e266892010-01-26 03:27:55 +00009824static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009825 return Functions.size() > 1 ||
9826 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9827}
9828
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009829/// \brief Create a unary operation that may resolve to an overloaded
9830/// operator.
9831///
9832/// \param OpLoc The location of the operator itself (e.g., '*').
9833///
9834/// \param OpcIn The UnaryOperator::Opcode that describes this
9835/// operator.
9836///
James Dennett40ae6662012-06-22 08:52:37 +00009837/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009838/// considered by overload resolution. The caller needs to build this
9839/// set based on the context using, e.g.,
9840/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9841/// set should not contain any member functions; those will be added
9842/// by CreateOverloadedUnaryOp().
9843///
James Dennett8da16872012-06-22 10:32:46 +00009844/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009845ExprResult
John McCall6e266892010-01-26 03:27:55 +00009846Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9847 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009848 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009849 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009850
9851 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9852 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9853 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009854 // TODO: provide better source location info.
9855 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009856
John McCall5acb0c92011-10-17 18:40:02 +00009857 if (checkPlaceholderForOverload(*this, Input))
9858 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009859
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009860 Expr *Args[2] = { Input, 0 };
9861 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009862
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009863 // For post-increment and post-decrement, add the implicit '0' as
9864 // the second argument, so that we know this is a post-increment or
9865 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009866 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009867 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009868 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9869 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009870 NumArgs = 2;
9871 }
9872
9873 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009874 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009875 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009876 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009877 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009878 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009879 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009880
John McCallc373d482010-01-27 01:50:18 +00009881 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009882 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009883 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009884 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009885 /*ADL*/ true, IsOverloaded(Fns),
9886 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009887 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009888 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009889 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009890 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009891 OpLoc));
9892 }
9893
9894 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009895 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009896
9897 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009898 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9899 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009900
9901 // Add operator candidates that are member functions.
9902 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9903
John McCall6e266892010-01-26 03:27:55 +00009904 // Add candidates from ADL.
9905 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009906 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009907 /*ExplicitTemplateArgs*/ 0,
9908 CandidateSet);
9909
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009910 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009911 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009912
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009913 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9914
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009915 // Perform overload resolution.
9916 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009917 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009918 case OR_Success: {
9919 // We found a built-in operator or an overloaded operator.
9920 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009921
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009922 if (FnDecl) {
9923 // We matched an overloaded operator. Build a call to that
9924 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009925
Eli Friedman5f2987c2012-02-02 03:46:19 +00009926 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009927
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009928 // Convert the arguments.
9929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009930 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009931
John Wiegley429bb272011-04-08 18:41:53 +00009932 ExprResult InputRes =
9933 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9934 Best->FoundDecl, Method);
9935 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009936 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009937 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009938 } else {
9939 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009940 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009941 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009942 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009943 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009944 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009945 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009946 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009947 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009948 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009949 }
9950
John McCallb697e082010-05-06 18:15:07 +00009951 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9952
John McCallf89e55a2010-11-18 06:31:45 +00009953 // Determine the result type.
9954 QualType ResultTy = FnDecl->getResultType();
9955 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9956 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009957
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009958 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009959 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009960 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009961 if (FnExpr.isInvalid())
9962 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009963
Eli Friedman4c3b8962009-11-18 03:58:17 +00009964 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009965 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009966 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009967 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009968
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009969 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009970 FnDecl))
9971 return ExprError();
9972
John McCall9ae2f072010-08-23 23:25:46 +00009973 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009974 } else {
9975 // We matched a built-in operator. Convert the arguments, then
9976 // break out so that we will build the appropriate built-in
9977 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009978 ExprResult InputRes =
9979 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9980 Best->Conversions[0], AA_Passing);
9981 if (InputRes.isInvalid())
9982 return ExprError();
9983 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009984 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009985 }
John Wiegley429bb272011-04-08 18:41:53 +00009986 }
9987
9988 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009989 // This is an erroneous use of an operator which can be overloaded by
9990 // a non-member function. Check for non-member operators which were
9991 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009992 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9993 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009994 // FIXME: Recover by calling the found function.
9995 return ExprError();
9996
John Wiegley429bb272011-04-08 18:41:53 +00009997 // No viable function; fall through to handling this as a
9998 // built-in operator, which will produce an error message for us.
9999 break;
10000
10001 case OR_Ambiguous:
10002 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10003 << UnaryOperator::getOpcodeStr(Opc)
10004 << Input->getType()
10005 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010006 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10007 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010008 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10009 return ExprError();
10010
10011 case OR_Deleted:
10012 Diag(OpLoc, diag::err_ovl_deleted_oper)
10013 << Best->Function->isDeleted()
10014 << UnaryOperator::getOpcodeStr(Opc)
10015 << getDeletedOrUnavailableSuffix(Best->Function)
10016 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10018 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010019 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010020 return ExprError();
10021 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010022
10023 // Either we found no viable overloaded operator or we matched a
10024 // built-in operator. In either case, fall through to trying to
10025 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010026 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010027}
10028
Douglas Gregor063daf62009-03-13 18:40:31 +000010029/// \brief Create a binary operation that may resolve to an overloaded
10030/// operator.
10031///
10032/// \param OpLoc The location of the operator itself (e.g., '+').
10033///
10034/// \param OpcIn The BinaryOperator::Opcode that describes this
10035/// operator.
10036///
James Dennett40ae6662012-06-22 08:52:37 +000010037/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010038/// considered by overload resolution. The caller needs to build this
10039/// set based on the context using, e.g.,
10040/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10041/// set should not contain any member functions; those will be added
10042/// by CreateOverloadedBinOp().
10043///
10044/// \param LHS Left-hand argument.
10045/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010046ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010047Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010048 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010049 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010050 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010051 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010052 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010053
10054 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10055 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10056 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10057
10058 // If either side is type-dependent, create an appropriate dependent
10059 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010060 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010061 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010062 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010063 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010064 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010065 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010066 Context.DependentTy,
10067 VK_RValue, OK_Ordinary,
10068 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010069
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010070 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10071 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010072 VK_LValue,
10073 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010074 Context.DependentTy,
10075 Context.DependentTy,
10076 OpLoc));
10077 }
John McCall6e266892010-01-26 03:27:55 +000010078
10079 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010080 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010081 // TODO: provide better source location info in DNLoc component.
10082 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010083 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010084 = UnresolvedLookupExpr::Create(Context, NamingClass,
10085 NestedNameSpecifierLoc(), OpNameInfo,
10086 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010087 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +000010088 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +000010089 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +000010090 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010091 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +000010092 OpLoc));
10093 }
10094
John McCall5acb0c92011-10-17 18:40:02 +000010095 // Always do placeholder-like conversions on the RHS.
10096 if (checkPlaceholderForOverload(*this, Args[1]))
10097 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010098
John McCall3c3b7f92011-10-25 17:37:35 +000010099 // Do placeholder-like conversion on the LHS; note that we should
10100 // not get here with a PseudoObject LHS.
10101 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010102 if (checkPlaceholderForOverload(*this, Args[0]))
10103 return ExprError();
10104
Sebastian Redl275c2b42009-11-18 23:10:33 +000010105 // If this is the assignment operator, we only perform overload resolution
10106 // if the left-hand side is a class or enumeration type. This is actually
10107 // a hack. The standard requires that we do overload resolution between the
10108 // various built-in candidates, but as DR507 points out, this can lead to
10109 // problems. So we do it this way, which pretty much follows what GCC does.
10110 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010111 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010113
John McCall0e800c92010-12-04 08:14:53 +000010114 // If this is the .* operator, which is not overloadable, just
10115 // create a built-in binary operator.
10116 if (Opc == BO_PtrMemD)
10117 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10118
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010119 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010120 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010121
10122 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010123 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010124
10125 // Add operator candidates that are member functions.
10126 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10127
John McCall6e266892010-01-26 03:27:55 +000010128 // Add candidates from ADL.
10129 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010130 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010131 /*ExplicitTemplateArgs*/ 0,
10132 CandidateSet);
10133
Douglas Gregor063daf62009-03-13 18:40:31 +000010134 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010135 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010136
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10138
Douglas Gregor063daf62009-03-13 18:40:31 +000010139 // Perform overload resolution.
10140 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010141 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010142 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010143 // We found a built-in operator or an overloaded operator.
10144 FunctionDecl *FnDecl = Best->Function;
10145
10146 if (FnDecl) {
10147 // We matched an overloaded operator. Build a call to that
10148 // operator.
10149
Eli Friedman5f2987c2012-02-02 03:46:19 +000010150 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010151
Douglas Gregor063daf62009-03-13 18:40:31 +000010152 // Convert the arguments.
10153 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010154 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010155 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010156
Chandler Carruth6df868e2010-12-12 08:17:55 +000010157 ExprResult Arg1 =
10158 PerformCopyInitialization(
10159 InitializedEntity::InitializeParameter(Context,
10160 FnDecl->getParamDecl(0)),
10161 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010162 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010163 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010164
John Wiegley429bb272011-04-08 18:41:53 +000010165 ExprResult Arg0 =
10166 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10167 Best->FoundDecl, Method);
10168 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010169 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010170 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010171 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010172 } else {
10173 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010174 ExprResult Arg0 = PerformCopyInitialization(
10175 InitializedEntity::InitializeParameter(Context,
10176 FnDecl->getParamDecl(0)),
10177 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010178 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010179 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010180
Chandler Carruth6df868e2010-12-12 08:17:55 +000010181 ExprResult Arg1 =
10182 PerformCopyInitialization(
10183 InitializedEntity::InitializeParameter(Context,
10184 FnDecl->getParamDecl(1)),
10185 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010186 if (Arg1.isInvalid())
10187 return ExprError();
10188 Args[0] = LHS = Arg0.takeAs<Expr>();
10189 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010190 }
10191
John McCallb697e082010-05-06 18:15:07 +000010192 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10193
John McCallf89e55a2010-11-18 06:31:45 +000010194 // Determine the result type.
10195 QualType ResultTy = FnDecl->getResultType();
10196 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10197 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010198
10199 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010200 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10201 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010202 if (FnExpr.isInvalid())
10203 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010204
John McCall9ae2f072010-08-23 23:25:46 +000010205 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010206 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010207 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010208
10209 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010210 FnDecl))
10211 return ExprError();
10212
John McCall9ae2f072010-08-23 23:25:46 +000010213 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010214 } else {
10215 // We matched a built-in operator. Convert the arguments, then
10216 // break out so that we will build the appropriate built-in
10217 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010218 ExprResult ArgsRes0 =
10219 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10220 Best->Conversions[0], AA_Passing);
10221 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010222 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010223 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010224
John Wiegley429bb272011-04-08 18:41:53 +000010225 ExprResult ArgsRes1 =
10226 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10227 Best->Conversions[1], AA_Passing);
10228 if (ArgsRes1.isInvalid())
10229 return ExprError();
10230 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010231 break;
10232 }
10233 }
10234
Douglas Gregor33074752009-09-30 21:46:01 +000010235 case OR_No_Viable_Function: {
10236 // C++ [over.match.oper]p9:
10237 // If the operator is the operator , [...] and there are no
10238 // viable functions, then the operator is assumed to be the
10239 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010240 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010241 break;
10242
Chandler Carruth6df868e2010-12-12 08:17:55 +000010243 // For class as left operand for assignment or compound assigment
10244 // operator do not fall through to handling in built-in, but report that
10245 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010246 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010247 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010248 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010249 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10250 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010251 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010252 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010253 // This is an erroneous use of an operator which can be overloaded by
10254 // a non-member function. Check for non-member operators which were
10255 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010256 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010257 // FIXME: Recover by calling the found function.
10258 return ExprError();
10259
Douglas Gregor33074752009-09-30 21:46:01 +000010260 // No viable function; try to create a built-in operation, which will
10261 // produce an error. Then, show the non-viable candidates.
10262 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010263 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010264 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010265 "C++ binary operator overloading is missing candidates!");
10266 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010267 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010268 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010269 return move(Result);
10270 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010271
10272 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010273 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010274 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010275 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010276 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010277 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010278 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010279 return ExprError();
10280
10281 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010282 if (isImplicitlyDeleted(Best->Function)) {
10283 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10284 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10285 << getSpecialMember(Method)
10286 << BinaryOperator::getOpcodeStr(Opc)
10287 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010288
10289 if (getSpecialMember(Method) != CXXInvalid) {
10290 // The user probably meant to call this special member. Just
10291 // explain why it's deleted.
10292 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010293 return ExprError();
10294 }
10295 } else {
10296 Diag(OpLoc, diag::err_ovl_deleted_oper)
10297 << Best->Function->isDeleted()
10298 << BinaryOperator::getOpcodeStr(Opc)
10299 << getDeletedOrUnavailableSuffix(Best->Function)
10300 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10301 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010302 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010303 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010304 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010305 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010306
Douglas Gregor33074752009-09-30 21:46:01 +000010307 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010309}
10310
John McCall60d7b3a2010-08-24 06:29:42 +000010311ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010312Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10313 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010314 Expr *Base, Expr *Idx) {
10315 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010316 DeclarationName OpName =
10317 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10318
10319 // If either side is type-dependent, create an appropriate dependent
10320 // expression.
10321 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10322
John McCallc373d482010-01-27 01:50:18 +000010323 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010324 // CHECKME: no 'operator' keyword?
10325 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10326 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010327 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010328 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010329 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010330 /*ADL*/ true, /*Overloaded*/ false,
10331 UnresolvedSetIterator(),
10332 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010333 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010334
Sebastian Redlf322ed62009-10-29 20:17:01 +000010335 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10336 Args, 2,
10337 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010338 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010339 RLoc));
10340 }
10341
John McCall5acb0c92011-10-17 18:40:02 +000010342 // Handle placeholders on both operands.
10343 if (checkPlaceholderForOverload(*this, Args[0]))
10344 return ExprError();
10345 if (checkPlaceholderForOverload(*this, Args[1]))
10346 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010347
Sebastian Redlf322ed62009-10-29 20:17:01 +000010348 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010349 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010350
10351 // Subscript can only be overloaded as a member function.
10352
10353 // Add operator candidates that are member functions.
10354 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10355
10356 // Add builtin operator candidates.
10357 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10358
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010359 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10360
Sebastian Redlf322ed62009-10-29 20:17:01 +000010361 // Perform overload resolution.
10362 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010363 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010364 case OR_Success: {
10365 // We found a built-in operator or an overloaded operator.
10366 FunctionDecl *FnDecl = Best->Function;
10367
10368 if (FnDecl) {
10369 // We matched an overloaded operator. Build a call to that
10370 // operator.
10371
Eli Friedman5f2987c2012-02-02 03:46:19 +000010372 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010373
John McCall9aa472c2010-03-19 07:35:19 +000010374 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010375 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010376
Sebastian Redlf322ed62009-10-29 20:17:01 +000010377 // Convert the arguments.
10378 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010379 ExprResult Arg0 =
10380 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10381 Best->FoundDecl, Method);
10382 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010383 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010384 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010385
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010386 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010387 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010388 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010389 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010390 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010391 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010392 Owned(Args[1]));
10393 if (InputInit.isInvalid())
10394 return ExprError();
10395
10396 Args[1] = InputInit.takeAs<Expr>();
10397
Sebastian Redlf322ed62009-10-29 20:17:01 +000010398 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010399 QualType ResultTy = FnDecl->getResultType();
10400 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10401 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010402
10403 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010404 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10405 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010406 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10407 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010408 OpLocInfo.getLoc(),
10409 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010410 if (FnExpr.isInvalid())
10411 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010412
John McCall9ae2f072010-08-23 23:25:46 +000010413 CXXOperatorCallExpr *TheCall =
10414 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010415 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010416 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010417
John McCall9ae2f072010-08-23 23:25:46 +000010418 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010419 FnDecl))
10420 return ExprError();
10421
John McCall9ae2f072010-08-23 23:25:46 +000010422 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010423 } else {
10424 // We matched a built-in operator. Convert the arguments, then
10425 // break out so that we will build the appropriate built-in
10426 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010427 ExprResult ArgsRes0 =
10428 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10429 Best->Conversions[0], AA_Passing);
10430 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010431 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010432 Args[0] = ArgsRes0.take();
10433
10434 ExprResult ArgsRes1 =
10435 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10436 Best->Conversions[1], AA_Passing);
10437 if (ArgsRes1.isInvalid())
10438 return ExprError();
10439 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010440
10441 break;
10442 }
10443 }
10444
10445 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010446 if (CandidateSet.empty())
10447 Diag(LLoc, diag::err_ovl_no_oper)
10448 << Args[0]->getType() << /*subscript*/ 0
10449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10450 else
10451 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10452 << Args[0]->getType()
10453 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010455 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010456 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010457 }
10458
10459 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010460 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010461 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010462 << Args[0]->getType() << Args[1]->getType()
10463 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010464 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010465 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010466 return ExprError();
10467
10468 case OR_Deleted:
10469 Diag(LLoc, diag::err_ovl_deleted_oper)
10470 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010471 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010472 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010474 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010475 return ExprError();
10476 }
10477
10478 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010479 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010480}
10481
Douglas Gregor88a35142008-12-22 05:46:06 +000010482/// BuildCallToMemberFunction - Build a call to a member
10483/// function. MemExpr is the expression that refers to the member
10484/// function (and includes the object parameter), Args/NumArgs are the
10485/// arguments to the function call (not including the object
10486/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010487/// expression refers to a non-static member function or an overloaded
10488/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010489ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010490Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10491 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010492 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010493 assert(MemExprE->getType() == Context.BoundMemberTy ||
10494 MemExprE->getType() == Context.OverloadTy);
10495
Douglas Gregor88a35142008-12-22 05:46:06 +000010496 // Dig out the member expression. This holds both the object
10497 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010498 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010499
John McCall864c0412011-04-26 20:42:42 +000010500 // Determine whether this is a call to a pointer-to-member function.
10501 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10502 assert(op->getType() == Context.BoundMemberTy);
10503 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10504
10505 QualType fnType =
10506 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10507
10508 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10509 QualType resultType = proto->getCallResultType(Context);
10510 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10511
10512 // Check that the object type isn't more qualified than the
10513 // member function we're calling.
10514 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10515
10516 QualType objectType = op->getLHS()->getType();
10517 if (op->getOpcode() == BO_PtrMemI)
10518 objectType = objectType->castAs<PointerType>()->getPointeeType();
10519 Qualifiers objectQuals = objectType.getQualifiers();
10520
10521 Qualifiers difference = objectQuals - funcQuals;
10522 difference.removeObjCGCAttr();
10523 difference.removeAddressSpace();
10524 if (difference) {
10525 std::string qualsString = difference.getAsString();
10526 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10527 << fnType.getUnqualifiedType()
10528 << qualsString
10529 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10530 }
10531
10532 CXXMemberCallExpr *call
10533 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10534 resultType, valueKind, RParenLoc);
10535
10536 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010537 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010538 call, 0))
10539 return ExprError();
10540
10541 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10542 return ExprError();
10543
10544 return MaybeBindToTemporary(call);
10545 }
10546
John McCall5acb0c92011-10-17 18:40:02 +000010547 UnbridgedCastsSet UnbridgedCasts;
10548 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10549 return ExprError();
10550
John McCall129e2df2009-11-30 22:42:35 +000010551 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010552 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010553 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010554 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010555 if (isa<MemberExpr>(NakedMemExpr)) {
10556 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010557 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010558 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010559 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010560 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010561 } else {
10562 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010563 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010564
John McCall701c89e2009-12-03 04:06:58 +000010565 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010566 Expr::Classification ObjectClassification
10567 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10568 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010569
Douglas Gregor88a35142008-12-22 05:46:06 +000010570 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010571 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010572
John McCallaa81e162009-12-01 22:10:20 +000010573 // FIXME: avoid copy.
10574 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10575 if (UnresExpr->hasExplicitTemplateArgs()) {
10576 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10577 TemplateArgs = &TemplateArgsBuffer;
10578 }
10579
John McCall129e2df2009-11-30 22:42:35 +000010580 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10581 E = UnresExpr->decls_end(); I != E; ++I) {
10582
John McCall701c89e2009-12-03 04:06:58 +000010583 NamedDecl *Func = *I;
10584 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10585 if (isa<UsingShadowDecl>(Func))
10586 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10587
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010588
Francois Pichetdbee3412011-01-18 05:04:39 +000010589 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010590 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010591 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10592 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010593 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010594 // If explicit template arguments were provided, we can't call a
10595 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010596 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010597 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010598
John McCall9aa472c2010-03-19 07:35:19 +000010599 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010600 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010601 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010602 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010603 } else {
John McCall129e2df2009-11-30 22:42:35 +000010604 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010605 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010606 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010607 llvm::makeArrayRef(Args, NumArgs),
10608 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010609 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010610 }
Douglas Gregordec06662009-08-21 18:42:58 +000010611 }
Mike Stump1eb44332009-09-09 15:08:12 +000010612
John McCall129e2df2009-11-30 22:42:35 +000010613 DeclarationName DeclName = UnresExpr->getMemberName();
10614
John McCall5acb0c92011-10-17 18:40:02 +000010615 UnbridgedCasts.restore();
10616
Douglas Gregor88a35142008-12-22 05:46:06 +000010617 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010618 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010619 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010620 case OR_Success:
10621 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010622 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010623 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010624 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010625 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010626 break;
10627
10628 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010629 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010630 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010631 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10633 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010634 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010635 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010636
10637 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010638 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010639 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10641 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010642 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010643 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010644
10645 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010646 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010647 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010648 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010649 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010650 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10652 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010653 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010654 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010655 }
10656
John McCall6bb80172010-03-30 21:47:33 +000010657 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010658
John McCallaa81e162009-12-01 22:10:20 +000010659 // If overload resolution picked a static member, build a
10660 // non-member call based on that function.
10661 if (Method->isStatic()) {
10662 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10663 Args, NumArgs, RParenLoc);
10664 }
10665
John McCall129e2df2009-11-30 22:42:35 +000010666 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010667 }
10668
John McCallf89e55a2010-11-18 06:31:45 +000010669 QualType ResultType = Method->getResultType();
10670 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10671 ResultType = ResultType.getNonLValueExprType(Context);
10672
Douglas Gregor88a35142008-12-22 05:46:06 +000010673 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010674 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010675 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010676 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010677
Anders Carlssoneed3e692009-10-10 00:06:20 +000010678 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010679 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010680 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010681 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010682
Douglas Gregor88a35142008-12-22 05:46:06 +000010683 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010684 // We only need to do this if there was actually an overload; otherwise
10685 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010686 if (!Method->isStatic()) {
10687 ExprResult ObjectArg =
10688 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10689 FoundDecl, Method);
10690 if (ObjectArg.isInvalid())
10691 return ExprError();
10692 MemExpr->setBase(ObjectArg.take());
10693 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010694
10695 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010696 const FunctionProtoType *Proto =
10697 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010698 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010699 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010700 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010701
Eli Friedmane61eb042012-02-18 04:48:30 +000010702 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10703
Richard Smith831421f2012-06-25 20:30:08 +000010704 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010705 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010706
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010707 if ((isa<CXXConstructorDecl>(CurContext) ||
10708 isa<CXXDestructorDecl>(CurContext)) &&
10709 TheCall->getMethodDecl()->isPure()) {
10710 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10711
Chandler Carruthae198062011-06-27 08:31:58 +000010712 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010713 Diag(MemExpr->getLocStart(),
10714 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10715 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10716 << MD->getParent()->getDeclName();
10717
10718 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010719 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010720 }
John McCall9ae2f072010-08-23 23:25:46 +000010721 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010722}
10723
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010724/// BuildCallToObjectOfClassType - Build a call to an object of class
10725/// type (C++ [over.call.object]), which can end up invoking an
10726/// overloaded function call operator (@c operator()) or performing a
10727/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010728ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010729Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010730 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010731 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010732 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010733 if (checkPlaceholderForOverload(*this, Obj))
10734 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010735 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010736
10737 UnbridgedCastsSet UnbridgedCasts;
10738 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10739 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010740
John Wiegley429bb272011-04-08 18:41:53 +000010741 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10742 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010743
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010744 // C++ [over.call.object]p1:
10745 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010746 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010747 // candidate functions includes at least the function call
10748 // operators of T. The function call operators of T are obtained by
10749 // ordinary lookup of the name operator() in the context of
10750 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010751 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010752 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010753
John Wiegley429bb272011-04-08 18:41:53 +000010754 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010755 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010756 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010757
John McCalla24dc2e2009-11-17 02:14:36 +000010758 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10759 LookupQualifiedName(R, Record->getDecl());
10760 R.suppressDiagnostics();
10761
Douglas Gregor593564b2009-11-15 07:48:03 +000010762 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010763 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010764 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10765 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010766 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010768
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010769 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010770 // In addition, for each (non-explicit in C++0x) conversion function
10771 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010772 //
10773 // operator conversion-type-id () cv-qualifier;
10774 //
10775 // where cv-qualifier is the same cv-qualification as, or a
10776 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010777 // denotes the type "pointer to function of (P1,...,Pn) returning
10778 // R", or the type "reference to pointer to function of
10779 // (P1,...,Pn) returning R", or the type "reference to function
10780 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010781 // is also considered as a candidate function. Similarly,
10782 // surrogate call functions are added to the set of candidate
10783 // functions for each conversion function declared in an
10784 // accessible base class provided the function is not hidden
10785 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010786 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010787 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010788 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010789 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010790 NamedDecl *D = *I;
10791 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10792 if (isa<UsingShadowDecl>(D))
10793 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010794
Douglas Gregor4a27d702009-10-21 06:18:39 +000010795 // Skip over templated conversion functions; they aren't
10796 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010797 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010798 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010799
John McCall701c89e2009-12-03 04:06:58 +000010800 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010801 if (!Conv->isExplicit()) {
10802 // Strip the reference type (if any) and then the pointer type (if
10803 // any) to get down to what might be a function type.
10804 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10805 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10806 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010807
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010808 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10809 {
10810 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010811 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10812 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010813 }
10814 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010815 }
Mike Stump1eb44332009-09-09 15:08:12 +000010816
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010817 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10818
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010819 // Perform overload resolution.
10820 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010821 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010822 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010823 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010824 // Overload resolution succeeded; we'll build the appropriate call
10825 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010826 break;
10827
10828 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010829 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010830 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010831 << Object.get()->getType() << /*call*/ 1
10832 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010833 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010834 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010835 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010836 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010837 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10838 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010839 break;
10840
10841 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010842 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010843 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010844 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010845 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10846 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010847 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010848
10849 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010850 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010851 diag::err_ovl_deleted_object_call)
10852 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010853 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010854 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010855 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10857 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010858 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010859 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010860
Douglas Gregorff331c12010-07-25 18:17:45 +000010861 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010862 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010863
John McCall5acb0c92011-10-17 18:40:02 +000010864 UnbridgedCasts.restore();
10865
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010866 if (Best->Function == 0) {
10867 // Since there is no function declaration, this is one of the
10868 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010869 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010870 = cast<CXXConversionDecl>(
10871 Best->Conversions[0].UserDefined.ConversionFunction);
10872
John Wiegley429bb272011-04-08 18:41:53 +000010873 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010874 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010875
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010876 // We selected one of the surrogate functions that converts the
10877 // object parameter to a function pointer. Perform the conversion
10878 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010879
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010880 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010881 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010882 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10883 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010884 if (Call.isInvalid())
10885 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010886 // Record usage of conversion in an implicit cast.
10887 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10888 CK_UserDefinedConversion,
10889 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010890
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010891 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010892 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010893 }
10894
Eli Friedman5f2987c2012-02-02 03:46:19 +000010895 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010896 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010897 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010898
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010899 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10900 // that calls this method, using Object for the implicit object
10901 // parameter and passing along the remaining arguments.
10902 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010903 const FunctionProtoType *Proto =
10904 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010905
10906 unsigned NumArgsInProto = Proto->getNumArgs();
10907 unsigned NumArgsToCheck = NumArgs;
10908
10909 // Build the full argument list for the method call (the
10910 // implicit object parameter is placed at the beginning of the
10911 // list).
10912 Expr **MethodArgs;
10913 if (NumArgs < NumArgsInProto) {
10914 NumArgsToCheck = NumArgsInProto;
10915 MethodArgs = new Expr*[NumArgsInProto + 1];
10916 } else {
10917 MethodArgs = new Expr*[NumArgs + 1];
10918 }
John Wiegley429bb272011-04-08 18:41:53 +000010919 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10921 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010922
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010923 DeclarationNameInfo OpLocInfo(
10924 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10925 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010926 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010927 HadMultipleCandidates,
10928 OpLocInfo.getLoc(),
10929 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010930 if (NewFn.isInvalid())
10931 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010932
10933 // Once we've built TheCall, all of the expressions are properly
10934 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010935 QualType ResultTy = Method->getResultType();
10936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10937 ResultTy = ResultTy.getNonLValueExprType(Context);
10938
John McCall9ae2f072010-08-23 23:25:46 +000010939 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010940 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010941 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010942 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010943 delete [] MethodArgs;
10944
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010945 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010946 Method))
10947 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010948
Douglas Gregor518fda12009-01-13 05:10:00 +000010949 // We may have default arguments. If so, we need to allocate more
10950 // slots in the call for them.
10951 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010952 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010953 else if (NumArgs > NumArgsInProto)
10954 NumArgsToCheck = NumArgsInProto;
10955
Chris Lattner312531a2009-04-12 08:11:20 +000010956 bool IsError = false;
10957
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010958 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010959 ExprResult ObjRes =
10960 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10961 Best->FoundDecl, Method);
10962 if (ObjRes.isInvalid())
10963 IsError = true;
10964 else
10965 Object = move(ObjRes);
10966 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010967
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010968 // Check the argument types.
10969 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010970 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010971 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010972 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010973
Douglas Gregor518fda12009-01-13 05:10:00 +000010974 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010975
John McCall60d7b3a2010-08-24 06:29:42 +000010976 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010977 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010978 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010979 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010980 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010981
Anders Carlsson3faa4862010-01-29 18:43:53 +000010982 IsError |= InputInit.isInvalid();
10983 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010984 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010985 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010986 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10987 if (DefArg.isInvalid()) {
10988 IsError = true;
10989 break;
10990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010991
Douglas Gregord47c47d2009-11-09 19:27:57 +000010992 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010993 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010994
10995 TheCall->setArg(i + 1, Arg);
10996 }
10997
10998 // If this is a variadic call, handle args passed through "...".
10999 if (Proto->isVariadic()) {
11000 // Promote the arguments (C99 6.5.2.2p7).
11001 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011002 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11003 IsError |= Arg.isInvalid();
11004 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011005 }
11006 }
11007
Chris Lattner312531a2009-04-12 08:11:20 +000011008 if (IsError) return true;
11009
Eli Friedmane61eb042012-02-18 04:48:30 +000011010 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11011
Richard Smith831421f2012-06-25 20:30:08 +000011012 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011013 return true;
11014
John McCall182f7092010-08-24 06:09:16 +000011015 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011016}
11017
Douglas Gregor8ba10742008-11-20 16:27:02 +000011018/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011019/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011020/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011021ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011022Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011023 assert(Base->getType()->isRecordType() &&
11024 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011025
John McCall5acb0c92011-10-17 18:40:02 +000011026 if (checkPlaceholderForOverload(*this, Base))
11027 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011028
John McCall5769d612010-02-08 23:07:23 +000011029 SourceLocation Loc = Base->getExprLoc();
11030
Douglas Gregor8ba10742008-11-20 16:27:02 +000011031 // C++ [over.ref]p1:
11032 //
11033 // [...] An expression x->m is interpreted as (x.operator->())->m
11034 // for a class object x of type T if T::operator->() exists and if
11035 // the operator is selected as the best match function by the
11036 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011037 DeclarationName OpName =
11038 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011039 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011040 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011041
John McCall5769d612010-02-08 23:07:23 +000011042 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011043 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011044 return ExprError();
11045
John McCalla24dc2e2009-11-17 02:14:36 +000011046 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11047 LookupQualifiedName(R, BaseRecord->getDecl());
11048 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011049
11050 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011051 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011052 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11053 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011054 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011055
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011056 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11057
Douglas Gregor8ba10742008-11-20 16:27:02 +000011058 // Perform overload resolution.
11059 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011060 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011061 case OR_Success:
11062 // Overload resolution succeeded; we'll build the call below.
11063 break;
11064
11065 case OR_No_Viable_Function:
11066 if (CandidateSet.empty())
11067 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011068 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011069 else
11070 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011071 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011073 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011074
11075 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011076 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11077 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011078 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011079 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011080
11081 case OR_Deleted:
11082 Diag(OpLoc, diag::err_ovl_deleted_oper)
11083 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011084 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011085 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011086 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011088 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011089 }
11090
Eli Friedman5f2987c2012-02-02 03:46:19 +000011091 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011092 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011093 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011094
Douglas Gregor8ba10742008-11-20 16:27:02 +000011095 // Convert the object parameter.
11096 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011097 ExprResult BaseResult =
11098 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11099 Best->FoundDecl, Method);
11100 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011101 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011102 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011103
Douglas Gregor8ba10742008-11-20 16:27:02 +000011104 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011105 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011106 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011107 if (FnExpr.isInvalid())
11108 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011109
John McCallf89e55a2010-11-18 06:31:45 +000011110 QualType ResultTy = Method->getResultType();
11111 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11112 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011113 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011114 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000011115 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011116
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011117 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011118 Method))
11119 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011120
11121 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011122}
11123
Richard Smith36f5cfe2012-03-09 08:00:36 +000011124/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11125/// a literal operator described by the provided lookup results.
11126ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11127 DeclarationNameInfo &SuffixInfo,
11128 ArrayRef<Expr*> Args,
11129 SourceLocation LitEndLoc,
11130 TemplateArgumentListInfo *TemplateArgs) {
11131 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011132
Richard Smith36f5cfe2012-03-09 08:00:36 +000011133 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11134 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11135 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011136
Richard Smith36f5cfe2012-03-09 08:00:36 +000011137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11138
Richard Smith36f5cfe2012-03-09 08:00:36 +000011139 // Perform overload resolution. This will usually be trivial, but might need
11140 // to perform substitutions for a literal operator template.
11141 OverloadCandidateSet::iterator Best;
11142 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11143 case OR_Success:
11144 case OR_Deleted:
11145 break;
11146
11147 case OR_No_Viable_Function:
11148 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11149 << R.getLookupName();
11150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11151 return ExprError();
11152
11153 case OR_Ambiguous:
11154 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11155 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11156 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011157 }
11158
Richard Smith36f5cfe2012-03-09 08:00:36 +000011159 FunctionDecl *FD = Best->Function;
11160 MarkFunctionReferenced(UDSuffixLoc, FD);
11161 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011162
Richard Smith36f5cfe2012-03-09 08:00:36 +000011163 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11164 SuffixInfo.getLoc(),
11165 SuffixInfo.getInfo());
11166 if (Fn.isInvalid())
11167 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011168
11169 // Check the argument types. This should almost always be a no-op, except
11170 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011171 Expr *ConvArgs[2];
11172 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11173 ExprResult InputInit = PerformCopyInitialization(
11174 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11175 SourceLocation(), Args[ArgIdx]);
11176 if (InputInit.isInvalid())
11177 return true;
11178 ConvArgs[ArgIdx] = InputInit.take();
11179 }
11180
Richard Smith9fcce652012-03-07 08:35:16 +000011181 QualType ResultTy = FD->getResultType();
11182 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11183 ResultTy = ResultTy.getNonLValueExprType(Context);
11184
Richard Smith9fcce652012-03-07 08:35:16 +000011185 UserDefinedLiteral *UDL =
11186 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11187 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11188
11189 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11190 return ExprError();
11191
Richard Smith831421f2012-06-25 20:30:08 +000011192 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011193 return ExprError();
11194
11195 return MaybeBindToTemporary(UDL);
11196}
11197
Douglas Gregor904eed32008-11-10 20:40:00 +000011198/// FixOverloadedFunctionReference - E is an expression that refers to
11199/// a C++ overloaded function (possibly with some parentheses and
11200/// perhaps a '&' around it). We have resolved the overloaded function
11201/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011202/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011203Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011204 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011205 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011206 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11207 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011208 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011209 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011210
Douglas Gregor699ee522009-11-20 19:42:02 +000011211 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011212 }
11213
Douglas Gregor699ee522009-11-20 19:42:02 +000011214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011215 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11216 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011217 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011218 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011219 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011220 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011221 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011222 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011223
11224 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011225 ICE->getCastKind(),
11226 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011227 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011228 }
11229
Douglas Gregor699ee522009-11-20 19:42:02 +000011230 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011231 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011232 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11234 if (Method->isStatic()) {
11235 // Do nothing: static member functions aren't any different
11236 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011237 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011238 // Fix the sub expression, which really has to be an
11239 // UnresolvedLookupExpr holding an overloaded member function
11240 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011241 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11242 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011243 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011244 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011245
John McCallba135432009-11-21 08:51:07 +000011246 assert(isa<DeclRefExpr>(SubExpr)
11247 && "fixed to something other than a decl ref");
11248 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11249 && "fixed to a member ref with no nested name qualifier");
11250
11251 // We have taken the address of a pointer to member
11252 // function. Perform the computation here so that we get the
11253 // appropriate pointer to member type.
11254 QualType ClassType
11255 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11256 QualType MemPtrType
11257 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11258
John McCallf89e55a2010-11-18 06:31:45 +000011259 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11260 VK_RValue, OK_Ordinary,
11261 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011262 }
11263 }
John McCall6bb80172010-03-30 21:47:33 +000011264 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11265 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011266 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011267 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011268
John McCall2de56d12010-08-25 11:45:40 +000011269 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011270 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011271 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011272 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011273 }
John McCallba135432009-11-21 08:51:07 +000011274
11275 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011276 // FIXME: avoid copy.
11277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011278 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011279 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11280 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011281 }
11282
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011283 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11284 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011285 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011286 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011287 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011288 ULE->getNameLoc(),
11289 Fn->getType(),
11290 VK_LValue,
11291 Found.getDecl(),
11292 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011293 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011294 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11295 return DRE;
John McCallba135432009-11-21 08:51:07 +000011296 }
11297
John McCall129e2df2009-11-30 22:42:35 +000011298 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011299 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011300 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11301 if (MemExpr->hasExplicitTemplateArgs()) {
11302 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11303 TemplateArgs = &TemplateArgsBuffer;
11304 }
John McCalld5532b62009-11-23 01:53:49 +000011305
John McCallaa81e162009-12-01 22:10:20 +000011306 Expr *Base;
11307
John McCallf89e55a2010-11-18 06:31:45 +000011308 // If we're filling in a static method where we used to have an
11309 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011310 if (MemExpr->isImplicitAccess()) {
11311 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011312 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11313 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011314 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011315 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011316 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011317 MemExpr->getMemberLoc(),
11318 Fn->getType(),
11319 VK_LValue,
11320 Found.getDecl(),
11321 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011322 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011323 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11324 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011325 } else {
11326 SourceLocation Loc = MemExpr->getMemberLoc();
11327 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011328 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011329 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011330 Base = new (Context) CXXThisExpr(Loc,
11331 MemExpr->getBaseType(),
11332 /*isImplicit=*/true);
11333 }
John McCallaa81e162009-12-01 22:10:20 +000011334 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011335 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011336
John McCallf5307512011-04-27 00:36:17 +000011337 ExprValueKind valueKind;
11338 QualType type;
11339 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11340 valueKind = VK_LValue;
11341 type = Fn->getType();
11342 } else {
11343 valueKind = VK_RValue;
11344 type = Context.BoundMemberTy;
11345 }
11346
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011347 MemberExpr *ME = MemberExpr::Create(Context, Base,
11348 MemExpr->isArrow(),
11349 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011350 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011351 Fn,
11352 Found,
11353 MemExpr->getMemberNameInfo(),
11354 TemplateArgs,
11355 type, valueKind, OK_Ordinary);
11356 ME->setHadMultipleCandidates(true);
11357 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011359
John McCall3fa5cae2010-10-26 07:05:15 +000011360 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011361}
11362
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011363ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011364 DeclAccessPair Found,
11365 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011366 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011367}
11368
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011369} // end namespace clang