blob: 9a14cad72be6096e060403c25dc07b737169ea79 [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() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000738 for (iterator i = begin(), e = end(); i != e; ++i)
739 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
740 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000741 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000742 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000743 Functions.clear();
744}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
John McCall5acb0c92011-10-17 18:40:02 +0000746namespace {
747 class UnbridgedCastsSet {
748 struct Entry {
749 Expr **Addr;
750 Expr *Saved;
751 };
752 SmallVector<Entry, 2> Entries;
753
754 public:
755 void save(Sema &S, Expr *&E) {
756 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
757 Entry entry = { &E, E };
758 Entries.push_back(entry);
759 E = S.stripARCUnbridgedCast(E);
760 }
761
762 void restore() {
763 for (SmallVectorImpl<Entry>::iterator
764 i = Entries.begin(), e = Entries.end(); i != e; ++i)
765 *i->Addr = i->Saved;
766 }
767 };
768}
769
770/// checkPlaceholderForOverload - Do any interesting placeholder-like
771/// preprocessing on the given expression.
772///
773/// \param unbridgedCasts a collection to which to add unbridged casts;
774/// without this, they will be immediately diagnosed as errors
775///
776/// Return true on unrecoverable error.
777static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
778 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000779 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
780 // We can't handle overloaded expressions here because overload
781 // resolution might reasonably tweak them.
782 if (placeholder->getKind() == BuiltinType::Overload) return false;
783
784 // If the context potentially accepts unbridged ARC casts, strip
785 // the unbridged cast and add it to the collection for later restoration.
786 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
787 unbridgedCasts) {
788 unbridgedCasts->save(S, E);
789 return false;
790 }
791
792 // Go ahead and check everything else.
793 ExprResult result = S.CheckPlaceholderExpr(E);
794 if (result.isInvalid())
795 return true;
796
797 E = result.take();
798 return false;
799 }
800
801 // Nothing to do.
802 return false;
803}
804
805/// checkArgPlaceholdersForOverload - Check a set of call operands for
806/// placeholders.
807static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
808 unsigned numArgs,
809 UnbridgedCastsSet &unbridged) {
810 for (unsigned i = 0; i != numArgs; ++i)
811 if (checkPlaceholderForOverload(S, args[i], &unbridged))
812 return true;
813
814 return false;
815}
816
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000817// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000818// overload of the declarations in Old. This routine returns false if
819// New and Old cannot be overloaded, e.g., if New has the same
820// signature as some function in Old (C++ 1.3.10) or if the Old
821// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000822// it does return false, MatchedDecl will point to the decl that New
823// cannot be overloaded with. This decl may be a UsingShadowDecl on
824// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000825//
826// Example: Given the following input:
827//
828// void f(int, float); // #1
829// void f(int, int); // #2
830// int f(int, int); // #3
831//
832// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000833// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834//
John McCall51fa86f2009-12-02 08:47:38 +0000835// When we process #2, Old contains only the FunctionDecl for #1. By
836// comparing the parameter types, we see that #1 and #2 are overloaded
837// (since they have different signatures), so this routine returns
838// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839//
John McCall51fa86f2009-12-02 08:47:38 +0000840// When we process #3, Old is an overload set containing #1 and #2. We
841// compare the signatures of #3 to #1 (they're overloaded, so we do
842// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
843// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000844// signature), IsOverload returns false and MatchedDecl will be set to
845// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000846//
847// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
848// into a class by a using declaration. The rules for whether to hide
849// shadow declarations ignore some properties which otherwise figure
850// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000851Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000852Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
853 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000854 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000855 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000856 NamedDecl *OldD = *I;
857
858 bool OldIsUsingDecl = false;
859 if (isa<UsingShadowDecl>(OldD)) {
860 OldIsUsingDecl = true;
861
862 // We can always introduce two using declarations into the same
863 // context, even if they have identical signatures.
864 if (NewIsUsingDecl) continue;
865
866 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
867 }
868
869 // If either declaration was introduced by a using declaration,
870 // we'll need to use slightly different rules for matching.
871 // Essentially, these rules are the normal rules, except that
872 // function templates hide function templates with different
873 // return types or template parameter lists.
874 bool UseMemberUsingDeclRules =
875 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
876
John McCall51fa86f2009-12-02 08:47:38 +0000877 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000878 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
879 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
880 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
881 continue;
882 }
883
John McCall871b2e72009-12-09 03:35:25 +0000884 Match = *I;
885 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000886 }
John McCall51fa86f2009-12-02 08:47:38 +0000887 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000888 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
889 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
890 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
891 continue;
892 }
893
John McCall871b2e72009-12-09 03:35:25 +0000894 Match = *I;
895 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000896 }
John McCalld7945c62010-11-10 03:01:53 +0000897 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000898 // We can overload with these, which can show up when doing
899 // redeclaration checks for UsingDecls.
900 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000901 } else if (isa<TagDecl>(OldD)) {
902 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000903 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
904 // Optimistically assume that an unresolved using decl will
905 // overload; if it doesn't, we'll have to diagnose during
906 // template instantiation.
907 } else {
John McCall68263142009-11-18 22:49:29 +0000908 // (C++ 13p1):
909 // Only function declarations can be overloaded; object and type
910 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000911 Match = *I;
912 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000913 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000914 }
John McCall68263142009-11-18 22:49:29 +0000915
John McCall871b2e72009-12-09 03:35:25 +0000916 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000917}
918
John McCallad00b772010-06-16 08:42:20 +0000919bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
920 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000921 // If both of the functions are extern "C", then they are not
922 // overloads.
923 if (Old->isExternC() && New->isExternC())
924 return false;
925
John McCall68263142009-11-18 22:49:29 +0000926 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
927 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
928
929 // C++ [temp.fct]p2:
930 // A function template can be overloaded with other function templates
931 // and with normal (non-template) functions.
932 if ((OldTemplate == 0) != (NewTemplate == 0))
933 return true;
934
935 // Is the function New an overload of the function Old?
936 QualType OldQType = Context.getCanonicalType(Old->getType());
937 QualType NewQType = Context.getCanonicalType(New->getType());
938
939 // Compare the signatures (C++ 1.3.10) of the two functions to
940 // determine whether they are overloads. If we find any mismatch
941 // in the signature, they are overloads.
942
943 // If either of these functions is a K&R-style function (no
944 // prototype), then we consider them to have matching signatures.
945 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
946 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
947 return false;
948
John McCallf4c73712011-01-19 06:33:43 +0000949 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
950 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000951
952 // The signature of a function includes the types of its
953 // parameters (C++ 1.3.10), which includes the presence or absence
954 // of the ellipsis; see C++ DR 357).
955 if (OldQType != NewQType &&
956 (OldType->getNumArgs() != NewType->getNumArgs() ||
957 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000958 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000959 return true;
960
961 // C++ [temp.over.link]p4:
962 // The signature of a function template consists of its function
963 // signature, its return type and its template parameter list. The names
964 // of the template parameters are significant only for establishing the
965 // relationship between the template parameters and the rest of the
966 // signature.
967 //
968 // We check the return type and template parameter lists for function
969 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000970 //
971 // However, we don't consider either of these when deciding whether
972 // a member introduced by a shadow declaration is hidden.
973 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000974 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
975 OldTemplate->getTemplateParameters(),
976 false, TPL_TemplateMatch) ||
977 OldType->getResultType() != NewType->getResultType()))
978 return true;
979
980 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000981 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000982 //
983 // As part of this, also check whether one of the member functions
984 // is static, in which case they are not overloads (C++
985 // 13.1p2). While not part of the definition of the signature,
986 // this check is important to determine whether these functions
987 // can be overloaded.
988 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
989 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
990 if (OldMethod && NewMethod &&
991 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000992 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000993 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
994 if (!UseUsingDeclRules &&
995 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
996 (OldMethod->getRefQualifier() == RQ_None ||
997 NewMethod->getRefQualifier() == RQ_None)) {
998 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999 // - Member function declarations with the same name and the same
1000 // parameter-type-list as well as member function template
1001 // declarations with the same name, the same parameter-type-list, and
1002 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001003 // them, but not all, have a ref-qualifier (8.3.5).
1004 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1005 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1006 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1007 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001008
John McCall68263142009-11-18 22:49:29 +00001009 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001010 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
John McCall68263142009-11-18 22:49:29 +00001012 // The signatures match; this is not an overload.
1013 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001014}
1015
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001016/// \brief Checks availability of the function depending on the current
1017/// function context. Inside an unavailable function, unavailability is ignored.
1018///
1019/// \returns true if \arg FD is unavailable and current context is inside
1020/// an available function, false otherwise.
1021bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1022 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1023}
1024
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001025/// \brief Tries a user-defined conversion from From to ToType.
1026///
1027/// Produces an implicit conversion sequence for when a standard conversion
1028/// is not an option. See TryImplicitConversion for more information.
1029static ImplicitConversionSequence
1030TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1031 bool SuppressUserConversions,
1032 bool AllowExplicit,
1033 bool InOverloadResolution,
1034 bool CStyle,
1035 bool AllowObjCWritebackConversion) {
1036 ImplicitConversionSequence ICS;
1037
1038 if (SuppressUserConversions) {
1039 // We're not in the case above, so there is no conversion that
1040 // we can perform.
1041 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1042 return ICS;
1043 }
1044
1045 // Attempt user-defined conversion.
1046 OverloadCandidateSet Conversions(From->getExprLoc());
1047 OverloadingResult UserDefResult
1048 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1049 AllowExplicit);
1050
1051 if (UserDefResult == OR_Success) {
1052 ICS.setUserDefined();
1053 // C++ [over.ics.user]p4:
1054 // A conversion of an expression of class type to the same class
1055 // type is given Exact Match rank, and a conversion of an
1056 // expression of class type to a base class of that type is
1057 // given Conversion rank, in spite of the fact that a copy
1058 // constructor (i.e., a user-defined conversion function) is
1059 // called for those cases.
1060 if (CXXConstructorDecl *Constructor
1061 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1062 QualType FromCanon
1063 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1064 QualType ToCanon
1065 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1066 if (Constructor->isCopyConstructor() &&
1067 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1068 // Turn this into a "standard" conversion sequence, so that it
1069 // gets ranked with standard conversion sequences.
1070 ICS.setStandard();
1071 ICS.Standard.setAsIdentityConversion();
1072 ICS.Standard.setFromType(From->getType());
1073 ICS.Standard.setAllToTypes(ToType);
1074 ICS.Standard.CopyConstructor = Constructor;
1075 if (ToCanon != FromCanon)
1076 ICS.Standard.Second = ICK_Derived_To_Base;
1077 }
1078 }
1079
1080 // C++ [over.best.ics]p4:
1081 // However, when considering the argument of a user-defined
1082 // conversion function that is a candidate by 13.3.1.3 when
1083 // invoked for the copying of the temporary in the second step
1084 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1085 // 13.3.1.6 in all cases, only standard conversion sequences and
1086 // ellipsis conversion sequences are allowed.
1087 if (SuppressUserConversions && ICS.isUserDefined()) {
1088 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1089 }
1090 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1091 ICS.setAmbiguous();
1092 ICS.Ambiguous.setFromType(From->getType());
1093 ICS.Ambiguous.setToType(ToType);
1094 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1095 Cand != Conversions.end(); ++Cand)
1096 if (Cand->Viable)
1097 ICS.Ambiguous.addConversion(Cand->Function);
1098 } else {
1099 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1100 }
1101
1102 return ICS;
1103}
1104
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001105/// TryImplicitConversion - Attempt to perform an implicit conversion
1106/// from the given expression (Expr) to the given type (ToType). This
1107/// function returns an implicit conversion sequence that can be used
1108/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001109///
1110/// void f(float f);
1111/// void g(int i) { f(i); }
1112///
1113/// this routine would produce an implicit conversion sequence to
1114/// describe the initialization of f from i, which will be a standard
1115/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1116/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1117//
1118/// Note that this routine only determines how the conversion can be
1119/// performed; it does not actually perform the conversion. As such,
1120/// it will not produce any diagnostics if no conversion is available,
1121/// but will instead return an implicit conversion sequence of kind
1122/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001123///
1124/// If @p SuppressUserConversions, then user-defined conversions are
1125/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001126/// If @p AllowExplicit, then explicit user-defined conversions are
1127/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001128///
1129/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1130/// writeback conversion, which allows __autoreleasing id* parameters to
1131/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001132static ImplicitConversionSequence
1133TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1134 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001135 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001136 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001137 bool CStyle,
1138 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001139 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001140 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001141 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001142 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001143 return ICS;
1144 }
1145
David Blaikie4e4d0842012-03-11 07:00:24 +00001146 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001147 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001148 return ICS;
1149 }
1150
Douglas Gregor604eb652010-08-11 02:15:33 +00001151 // C++ [over.ics.user]p4:
1152 // A conversion of an expression of class type to the same class
1153 // type is given Exact Match rank, and a conversion of an
1154 // expression of class type to a base class of that type is
1155 // given Conversion rank, in spite of the fact that a copy/move
1156 // constructor (i.e., a user-defined conversion function) is
1157 // called for those cases.
1158 QualType FromType = From->getType();
1159 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001160 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1161 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001162 ICS.setStandard();
1163 ICS.Standard.setAsIdentityConversion();
1164 ICS.Standard.setFromType(FromType);
1165 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001166
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001167 // We don't actually check at this point whether there is a valid
1168 // copy/move constructor, since overloading just assumes that it
1169 // exists. When we actually perform initialization, we'll find the
1170 // appropriate constructor to copy the returned object, if needed.
1171 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001173 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001174 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001175 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176
Douglas Gregor604eb652010-08-11 02:15:33 +00001177 return ICS;
1178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001180 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1181 AllowExplicit, InOverloadResolution, CStyle,
1182 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001183}
1184
John McCallf85e1932011-06-15 23:02:42 +00001185ImplicitConversionSequence
1186Sema::TryImplicitConversion(Expr *From, QualType ToType,
1187 bool SuppressUserConversions,
1188 bool AllowExplicit,
1189 bool InOverloadResolution,
1190 bool CStyle,
1191 bool AllowObjCWritebackConversion) {
1192 return clang::TryImplicitConversion(*this, From, ToType,
1193 SuppressUserConversions, AllowExplicit,
1194 InOverloadResolution, CStyle,
1195 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001196}
1197
Douglas Gregor575c63a2010-04-16 22:27:05 +00001198/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001199/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001200/// converted expression. Flavor is the kind of conversion we're
1201/// performing, used in the error message. If @p AllowExplicit,
1202/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001203ExprResult
1204Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001205 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001206 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001207 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001208}
1209
John Wiegley429bb272011-04-08 18:41:53 +00001210ExprResult
1211Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001212 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001213 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001214 if (checkPlaceholderForOverload(*this, From))
1215 return ExprError();
1216
John McCallf85e1932011-06-15 23:02:42 +00001217 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1218 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001219 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001220 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001221
John McCall120d63c2010-08-24 20:38:10 +00001222 ICS = clang::TryImplicitConversion(*this, From, ToType,
1223 /*SuppressUserConversions=*/false,
1224 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001225 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001226 /*CStyle=*/false,
1227 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001228 return PerformImplicitConversion(From, ToType, ICS, Action);
1229}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001230
1231/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001232/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001233bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1234 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001235 if (Context.hasSameUnqualifiedType(FromType, ToType))
1236 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001237
John McCall00ccbef2010-12-21 00:44:39 +00001238 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1239 // where F adds one of the following at most once:
1240 // - a pointer
1241 // - a member pointer
1242 // - a block pointer
1243 CanQualType CanTo = Context.getCanonicalType(ToType);
1244 CanQualType CanFrom = Context.getCanonicalType(FromType);
1245 Type::TypeClass TyClass = CanTo->getTypeClass();
1246 if (TyClass != CanFrom->getTypeClass()) return false;
1247 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1248 if (TyClass == Type::Pointer) {
1249 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1250 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1251 } else if (TyClass == Type::BlockPointer) {
1252 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1253 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1254 } else if (TyClass == Type::MemberPointer) {
1255 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1256 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1257 } else {
1258 return false;
1259 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001260
John McCall00ccbef2010-12-21 00:44:39 +00001261 TyClass = CanTo->getTypeClass();
1262 if (TyClass != CanFrom->getTypeClass()) return false;
1263 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1264 return false;
1265 }
1266
1267 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1268 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1269 if (!EInfo.getNoReturn()) return false;
1270
1271 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1272 assert(QualType(FromFn, 0).isCanonical());
1273 if (QualType(FromFn, 0) != CanTo) return false;
1274
1275 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001276 return true;
1277}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001278
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001279/// \brief Determine whether the conversion from FromType to ToType is a valid
1280/// vector conversion.
1281///
1282/// \param ICK Will be set to the vector conversion kind, if this is a vector
1283/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001284static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1285 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001286 // We need at least one of these types to be a vector type to have a vector
1287 // conversion.
1288 if (!ToType->isVectorType() && !FromType->isVectorType())
1289 return false;
1290
1291 // Identical types require no conversions.
1292 if (Context.hasSameUnqualifiedType(FromType, ToType))
1293 return false;
1294
1295 // There are no conversions between extended vector types, only identity.
1296 if (ToType->isExtVectorType()) {
1297 // There are no conversions between extended vector types other than the
1298 // identity conversion.
1299 if (FromType->isExtVectorType())
1300 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001301
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001302 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001303 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001304 ICK = ICK_Vector_Splat;
1305 return true;
1306 }
1307 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001308
1309 // We can perform the conversion between vector types in the following cases:
1310 // 1)vector types are equivalent AltiVec and GCC vector types
1311 // 2)lax vector conversions are permitted and the vector types are of the
1312 // same size
1313 if (ToType->isVectorType() && FromType->isVectorType()) {
1314 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001315 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001316 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001317 ICK = ICK_Vector_Conversion;
1318 return true;
1319 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001320 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001321
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001322 return false;
1323}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001324
Douglas Gregor7d000652012-04-12 20:48:09 +00001325static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1326 bool InOverloadResolution,
1327 StandardConversionSequence &SCS,
1328 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001329
Douglas Gregor60d62c22008-10-31 16:23:19 +00001330/// IsStandardConversion - Determines whether there is a standard
1331/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1332/// expression From to the type ToType. Standard conversion sequences
1333/// only consider non-class types; for conversions that involve class
1334/// types, use TryImplicitConversion. If a conversion exists, SCS will
1335/// contain the standard conversion sequence required to perform this
1336/// conversion and this routine will return true. Otherwise, this
1337/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001338static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1339 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001340 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001341 bool CStyle,
1342 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001343 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001344
Douglas Gregor60d62c22008-10-31 16:23:19 +00001345 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001346 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001347 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001348 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001349 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001350 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001351
Douglas Gregorf9201e02009-02-11 23:02:49 +00001352 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001353 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001354 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001355 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001356 return false;
1357
Mike Stump1eb44332009-09-09 15:08:12 +00001358 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001359 }
1360
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 // The first conversion can be an lvalue-to-rvalue conversion,
1362 // array-to-pointer conversion, or function-to-pointer conversion
1363 // (C++ 4p1).
1364
John McCall120d63c2010-08-24 20:38:10 +00001365 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001366 DeclAccessPair AccessPair;
1367 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001369 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001370 // We were able to resolve the address of the overloaded function,
1371 // so we can convert to the type of that function.
1372 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001373
1374 // we can sometimes resolve &foo<int> regardless of ToType, so check
1375 // if the type matches (identity) or we are converting to bool
1376 if (!S.Context.hasSameUnqualifiedType(
1377 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1378 QualType resultTy;
1379 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001380 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001381 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1382 // otherwise, only a boolean conversion is standard
1383 if (!ToType->isBooleanType())
1384 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386
Chandler Carruth90434232011-03-29 08:08:18 +00001387 // Check if the "from" expression is taking the address of an overloaded
1388 // function and recompute the FromType accordingly. Take advantage of the
1389 // fact that non-static member functions *must* have such an address-of
1390 // expression.
1391 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1392 if (Method && !Method->isStatic()) {
1393 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1394 "Non-unary operator on non-static member address");
1395 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1396 == UO_AddrOf &&
1397 "Non-address-of operator on non-static member address");
1398 const Type *ClassType
1399 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1400 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001401 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1402 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1403 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001404 "Non-address-of operator for overloaded function expression");
1405 FromType = S.Context.getPointerType(FromType);
1406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001408 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001409 assert(S.Context.hasSameType(
1410 FromType,
1411 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001412 } else {
1413 return false;
1414 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001415 }
John McCall21480112011-08-30 00:57:29 +00001416 // Lvalue-to-rvalue conversion (C++11 4.1):
1417 // A glvalue (3.10) of a non-function, non-array type T can
1418 // be converted to a prvalue.
1419 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001420 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001421 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001422 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001423 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001425 // C11 6.3.2.1p2:
1426 // ... if the lvalue has atomic type, the value has the non-atomic version
1427 // of the type of the lvalue ...
1428 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1429 FromType = Atomic->getValueType();
1430
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001431 // If T is a non-class type, the type of the rvalue is the
1432 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001433 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1434 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001435 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001436 } else if (FromType->isArrayType()) {
1437 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001438 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001439
1440 // An lvalue or rvalue of type "array of N T" or "array of unknown
1441 // bound of T" can be converted to an rvalue of type "pointer to
1442 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001443 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444
John McCall120d63c2010-08-24 20:38:10 +00001445 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001446 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001447 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001448
1449 // For the purpose of ranking in overload resolution
1450 // (13.3.3.1.1), this conversion is considered an
1451 // array-to-pointer conversion followed by a qualification
1452 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001453 SCS.Second = ICK_Identity;
1454 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001455 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001456 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001457 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001458 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001459 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001460 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001461 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462
1463 // An lvalue of function type T can be converted to an rvalue of
1464 // type "pointer to T." The result is a pointer to the
1465 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001466 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001467 } else {
1468 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001469 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001470 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001471 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001472
1473 // The second conversion can be an integral promotion, floating
1474 // point promotion, integral conversion, floating point conversion,
1475 // floating-integral conversion, pointer conversion,
1476 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001477 // For overloading in C, this can also be a "compatible-type"
1478 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001479 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001480 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001481 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001482 // The unqualified versions of the types are the same: there's no
1483 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001484 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001485 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001486 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001487 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001488 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001489 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001490 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001491 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001492 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001493 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001494 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001495 SCS.Second = ICK_Complex_Promotion;
1496 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001497 } else if (ToType->isBooleanType() &&
1498 (FromType->isArithmeticType() ||
1499 FromType->isAnyPointerType() ||
1500 FromType->isBlockPointerType() ||
1501 FromType->isMemberPointerType() ||
1502 FromType->isNullPtrType())) {
1503 // Boolean conversions (C++ 4.12).
1504 SCS.Second = ICK_Boolean_Conversion;
1505 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001506 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001507 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001508 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001509 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001510 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001511 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001512 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001513 SCS.Second = ICK_Complex_Conversion;
1514 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001515 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1516 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001517 // Complex-real conversions (C99 6.3.1.7)
1518 SCS.Second = ICK_Complex_Real;
1519 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001520 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001521 // Floating point conversions (C++ 4.8).
1522 SCS.Second = ICK_Floating_Conversion;
1523 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001524 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001525 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001526 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001527 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001528 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001529 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001530 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001531 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001532 SCS.Second = ICK_Block_Pointer_Conversion;
1533 } else if (AllowObjCWritebackConversion &&
1534 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1535 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001536 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1537 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001538 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001540 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001541 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001542 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001543 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001544 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001545 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001546 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001547 SCS.Second = SecondICK;
1548 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001549 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001550 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001551 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001552 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001553 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001554 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001555 // Treat a conversion that strips "noreturn" as an identity conversion.
1556 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001557 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1558 InOverloadResolution,
1559 SCS, CStyle)) {
1560 SCS.Second = ICK_TransparentUnionConversion;
1561 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001562 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1563 CStyle)) {
1564 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001565 // appropriately.
1566 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001567 } else {
1568 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001569 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001570 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001571 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001572
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001573 QualType CanonFrom;
1574 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001576 bool ObjCLifetimeConversion;
1577 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1578 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001579 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001580 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001582 CanonFrom = S.Context.getCanonicalType(FromType);
1583 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001584 } else {
1585 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586 SCS.Third = ICK_Identity;
1587
Mike Stump1eb44332009-09-09 15:08:12 +00001588 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589 // [...] Any difference in top-level cv-qualification is
1590 // subsumed by the initialization itself and does not constitute
1591 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001592 CanonFrom = S.Context.getCanonicalType(FromType);
1593 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001595 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001596 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001597 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1598 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001599 FromType = ToType;
1600 CanonFrom = CanonTo;
1601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001602 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001603 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001604
1605 // If we have not converted the argument type to the parameter type,
1606 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001607 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001609
Douglas Gregor60d62c22008-10-31 16:23:19 +00001610 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001611}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001612
1613static bool
1614IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1615 QualType &ToType,
1616 bool InOverloadResolution,
1617 StandardConversionSequence &SCS,
1618 bool CStyle) {
1619
1620 const RecordType *UT = ToType->getAsUnionType();
1621 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1622 return false;
1623 // The field to initialize within the transparent union.
1624 RecordDecl *UD = UT->getDecl();
1625 // It's compatible if the expression matches any of the fields.
1626 for (RecordDecl::field_iterator it = UD->field_begin(),
1627 itend = UD->field_end();
1628 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001629 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1630 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001631 ToType = it->getType();
1632 return true;
1633 }
1634 }
1635 return false;
1636}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637
1638/// IsIntegralPromotion - Determines whether the conversion from the
1639/// expression From (whose potentially-adjusted type is FromType) to
1640/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1641/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001642bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001643 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001644 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001645 if (!To) {
1646 return false;
1647 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001648
1649 // An rvalue of type char, signed char, unsigned char, short int, or
1650 // unsigned short int can be converted to an rvalue of type int if
1651 // int can represent all the values of the source type; otherwise,
1652 // the source rvalue can be converted to an rvalue of type unsigned
1653 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001654 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1655 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001656 if (// We can promote any signed, promotable integer type to an int
1657 (FromType->isSignedIntegerType() ||
1658 // We can promote any unsigned integer type whose size is
1659 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001660 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001661 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001662 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001663 }
1664
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 return To->getKind() == BuiltinType::UInt;
1666 }
1667
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668 // C++0x [conv.prom]p3:
1669 // A prvalue of an unscoped enumeration type whose underlying type is not
1670 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1671 // following types that can represent all the values of the enumeration
1672 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1673 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001674 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001676 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677 // with lowest integer conversion rank (4.13) greater than the rank of long
1678 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001679 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001680 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1681 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1682 // provided for a scoped enumeration.
1683 if (FromEnumType->getDecl()->isScoped())
1684 return false;
1685
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001686 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001688 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001689 return Context.hasSameUnqualifiedType(ToType,
1690 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001691 }
John McCall842aef82009-12-09 09:09:27 +00001692
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001693 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001694 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1695 // to an rvalue a prvalue of the first of the following types that can
1696 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001697 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001698 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001699 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001700 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001701 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001702 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001703 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001704 // Determine whether the type we're converting from is signed or
1705 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001706 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001707 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001709 // The types we'll try to promote to, in the appropriate
1710 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001711 QualType PromoteTypes[6] = {
1712 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001713 Context.LongTy, Context.UnsignedLongTy ,
1714 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001715 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001716 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1718 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001719 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001720 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1721 // We found the type that we can promote to. If this is the
1722 // type we wanted, we have a promotion. Otherwise, no
1723 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001724 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001725 }
1726 }
1727 }
1728
1729 // An rvalue for an integral bit-field (9.6) can be converted to an
1730 // rvalue of type int if int can represent all the values of the
1731 // bit-field; otherwise, it can be converted to unsigned int if
1732 // unsigned int can represent all the values of the bit-field. If
1733 // the bit-field is larger yet, no integral promotion applies to
1734 // it. If the bit-field has an enumerated type, it is treated as any
1735 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001736 // FIXME: We should delay checking of bit-fields until we actually perform the
1737 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001738 using llvm::APSInt;
1739 if (From)
1740 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001741 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001742 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001743 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1744 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1745 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor86f19402008-12-20 23:49:58 +00001747 // Are we promoting to an int from a bitfield that fits in an int?
1748 if (BitWidth < ToSize ||
1749 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1750 return To->getKind() == BuiltinType::Int;
1751 }
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Douglas Gregor86f19402008-12-20 23:49:58 +00001753 // Are we promoting to an unsigned int from an unsigned bitfield
1754 // that fits into an unsigned int?
1755 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1756 return To->getKind() == BuiltinType::UInt;
1757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Douglas Gregor86f19402008-12-20 23:49:58 +00001759 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001760 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001761 }
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001763 // An rvalue of type bool can be converted to an rvalue of type int,
1764 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001765 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001766 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001767 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001768
1769 return false;
1770}
1771
1772/// IsFloatingPointPromotion - Determines whether the conversion from
1773/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1774/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001775bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001776 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1777 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001778 /// An rvalue of type float can be converted to an rvalue of type
1779 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780 if (FromBuiltin->getKind() == BuiltinType::Float &&
1781 ToBuiltin->getKind() == BuiltinType::Double)
1782 return true;
1783
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001784 // C99 6.3.1.5p1:
1785 // When a float is promoted to double or long double, or a
1786 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001787 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001788 (FromBuiltin->getKind() == BuiltinType::Float ||
1789 FromBuiltin->getKind() == BuiltinType::Double) &&
1790 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1791 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001792
1793 // Half can be promoted to float.
1794 if (FromBuiltin->getKind() == BuiltinType::Half &&
1795 ToBuiltin->getKind() == BuiltinType::Float)
1796 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001797 }
1798
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 return false;
1800}
1801
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001802/// \brief Determine if a conversion is a complex promotion.
1803///
1804/// A complex promotion is defined as a complex -> complex conversion
1805/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001806/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001807bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001808 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001809 if (!FromComplex)
1810 return false;
1811
John McCall183700f2009-09-21 23:43:11 +00001812 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001813 if (!ToComplex)
1814 return false;
1815
1816 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001817 ToComplex->getElementType()) ||
1818 IsIntegralPromotion(0, FromComplex->getElementType(),
1819 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001820}
1821
Douglas Gregorcb7de522008-11-26 23:31:11 +00001822/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1823/// the pointer type FromPtr to a pointer to type ToPointee, with the
1824/// same type qualifiers as FromPtr has on its pointee type. ToType,
1825/// if non-empty, will be a pointer to ToType that may or may not have
1826/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001827///
Mike Stump1eb44332009-09-09 15:08:12 +00001828static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001829BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001830 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001831 ASTContext &Context,
1832 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001833 assert((FromPtr->getTypeClass() == Type::Pointer ||
1834 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1835 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
John McCallf85e1932011-06-15 23:02:42 +00001837 /// Conversions to 'id' subsume cv-qualifier conversions.
1838 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001839 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001840
1841 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001842 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001843 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001844 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001845
John McCallf85e1932011-06-15 23:02:42 +00001846 if (StripObjCLifetime)
1847 Quals.removeObjCLifetime();
1848
Mike Stump1eb44332009-09-09 15:08:12 +00001849 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001850 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001851 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001852 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001853 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001854
1855 // Build a pointer to ToPointee. It has the right qualifiers
1856 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001857 if (isa<ObjCObjectPointerType>(ToType))
1858 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001859 return Context.getPointerType(ToPointee);
1860 }
1861
1862 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001863 QualType QualifiedCanonToPointee
1864 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001865
Douglas Gregorda80f742010-12-01 21:43:58 +00001866 if (isa<ObjCObjectPointerType>(ToType))
1867 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1868 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001869}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001870
Mike Stump1eb44332009-09-09 15:08:12 +00001871static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001872 bool InOverloadResolution,
1873 ASTContext &Context) {
1874 // Handle value-dependent integral null pointer constants correctly.
1875 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1876 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001877 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001878 return !InOverloadResolution;
1879
Douglas Gregorce940492009-09-25 04:25:58 +00001880 return Expr->isNullPointerConstant(Context,
1881 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1882 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001883}
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001885/// IsPointerConversion - Determines whether the conversion of the
1886/// expression From, which has the (possibly adjusted) type FromType,
1887/// can be converted to the type ToType via a pointer conversion (C++
1888/// 4.10). If so, returns true and places the converted type (that
1889/// might differ from ToType in its cv-qualifiers at some level) into
1890/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001891///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001892/// This routine also supports conversions to and from block pointers
1893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1894/// pointers to interfaces. FIXME: Once we've determined the
1895/// appropriate overloading rules for Objective-C, we may want to
1896/// split the Objective-C checks into a different routine; however,
1897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001898/// conversions, so for now they live here. IncompatibleObjC will be
1899/// set if the conversion is an allowed Objective-C conversion that
1900/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001902 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001903 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001904 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001905 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001906 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1907 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001908 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001909
Mike Stump1eb44332009-09-09 15:08:12 +00001910 // Conversion from a null pointer constant to any Objective-C pointer type.
1911 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001913 ConvertedType = ToType;
1914 return true;
1915 }
1916
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001917 // Blocks: Block pointers can be converted to void*.
1918 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001919 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001920 ConvertedType = ToType;
1921 return true;
1922 }
1923 // Blocks: A null pointer constant can be converted to a block
1924 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001925 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001927 ConvertedType = ToType;
1928 return true;
1929 }
1930
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001931 // If the left-hand-side is nullptr_t, the right side can be a null
1932 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001933 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001934 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001935 ConvertedType = ToType;
1936 return true;
1937 }
1938
Ted Kremenek6217b802009-07-29 21:53:49 +00001939 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001940 if (!ToTypePtr)
1941 return false;
1942
1943 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001944 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001945 ConvertedType = ToType;
1946 return true;
1947 }
Sebastian Redl07779722008-10-31 14:43:28 +00001948
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001949 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001950 // , including objective-c pointers.
1951 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001952 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001953 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001954 ConvertedType = BuildSimilarlyQualifiedPointerType(
1955 FromType->getAs<ObjCObjectPointerType>(),
1956 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001957 ToType, Context);
1958 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001959 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001961 if (!FromTypePtr)
1962 return false;
1963
1964 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001965
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001966 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001967 // pointer conversion, so don't do all of the work below.
1968 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1969 return false;
1970
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001971 // An rvalue of type "pointer to cv T," where T is an object type,
1972 // can be converted to an rvalue of type "pointer to cv void" (C++
1973 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001974 if (FromPointeeType->isIncompleteOrObjectType() &&
1975 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001977 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001978 ToType, Context,
1979 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001980 return true;
1981 }
1982
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001983 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001984 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001985 ToPointeeType->isVoidType()) {
1986 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1987 ToPointeeType,
1988 ToType, Context);
1989 return true;
1990 }
1991
Douglas Gregorf9201e02009-02-11 23:02:49 +00001992 // When we're overloading in C, we allow a special kind of pointer
1993 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001994 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001995 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001997 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001998 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001999 return true;
2000 }
2001
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002002 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002003 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002004 // An rvalue of type "pointer to cv D," where D is a class type,
2005 // can be converted to an rvalue of type "pointer to cv B," where
2006 // B is a base class (clause 10) of D. If B is an inaccessible
2007 // (clause 11) or ambiguous (10.2) base class of D, a program that
2008 // necessitates this conversion is ill-formed. The result of the
2009 // conversion is a pointer to the base class sub-object of the
2010 // derived class object. The null pointer value is converted to
2011 // the null pointer value of the destination type.
2012 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002013 // Note that we do not check for ambiguity or inaccessibility
2014 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002015 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002016 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002017 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002018 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002019 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002020 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002021 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002022 ToType, Context);
2023 return true;
2024 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002025
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002026 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2027 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2028 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2029 ToPointeeType,
2030 ToType, Context);
2031 return true;
2032 }
2033
Douglas Gregorc7887512008-12-19 19:13:09 +00002034 return false;
2035}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002036
2037/// \brief Adopt the given qualifiers for the given type.
2038static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2039 Qualifiers TQs = T.getQualifiers();
2040
2041 // Check whether qualifiers already match.
2042 if (TQs == Qs)
2043 return T;
2044
2045 if (Qs.compatiblyIncludes(TQs))
2046 return Context.getQualifiedType(T, Qs);
2047
2048 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2049}
Douglas Gregorc7887512008-12-19 19:13:09 +00002050
2051/// isObjCPointerConversion - Determines whether this is an
2052/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2053/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002054bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002055 QualType& ConvertedType,
2056 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002057 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002058 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002059
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002060 // The set of qualifiers on the type we're converting from.
2061 Qualifiers FromQualifiers = FromType.getQualifiers();
2062
Steve Naroff14108da2009-07-10 23:34:53 +00002063 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002064 const ObjCObjectPointerType* ToObjCPtr =
2065 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002066 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002067 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002068
Steve Naroff14108da2009-07-10 23:34:53 +00002069 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002070 // If the pointee types are the same (ignoring qualifications),
2071 // then this is not a pointer conversion.
2072 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2073 FromObjCPtr->getPointeeType()))
2074 return false;
2075
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002076 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002077 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002078 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002079 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002080 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002081 return true;
2082 }
2083 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002084 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002085 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002086 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002087 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002088 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002089 return true;
2090 }
2091 // Objective C++: We're able to convert from a pointer to an
2092 // interface to a pointer to a different interface.
2093 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002094 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2095 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002096 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002097 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2098 FromObjCPtr->getPointeeType()))
2099 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002101 ToObjCPtr->getPointeeType(),
2102 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002103 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002104 return true;
2105 }
2106
2107 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2108 // Okay: this is some kind of implicit downcast of Objective-C
2109 // interfaces, which is permitted. However, we're going to
2110 // complain about it.
2111 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002113 ToObjCPtr->getPointeeType(),
2114 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002115 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002116 return true;
2117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118 }
Steve Naroff14108da2009-07-10 23:34:53 +00002119 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002120 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002121 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002122 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002123 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002124 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002125 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002126 // to a block pointer type.
2127 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002128 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002129 return true;
2130 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002131 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002133 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002134 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002136 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002137 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002138 return true;
2139 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002140 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002141 return false;
2142
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002143 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002144 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002145 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002146 else if (const BlockPointerType *FromBlockPtr =
2147 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002148 FromPointeeType = FromBlockPtr->getPointeeType();
2149 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002150 return false;
2151
Douglas Gregorc7887512008-12-19 19:13:09 +00002152 // If we have pointers to pointers, recursively check whether this
2153 // is an Objective-C conversion.
2154 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2155 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2156 IncompatibleObjC)) {
2157 // We always complain about this conversion.
2158 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002159 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002160 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002161 return true;
2162 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002163 // Allow conversion of pointee being objective-c pointer to another one;
2164 // as in I* to id.
2165 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2166 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2167 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2168 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002169
Douglas Gregorda80f742010-12-01 21:43:58 +00002170 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002171 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002172 return true;
2173 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002174
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002175 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002176 // differences in the argument and result types are in Objective-C
2177 // pointer conversions. If so, we permit the conversion (but
2178 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002179 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002180 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002181 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002182 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002183 if (FromFunctionType && ToFunctionType) {
2184 // If the function types are exactly the same, this isn't an
2185 // Objective-C pointer conversion.
2186 if (Context.getCanonicalType(FromPointeeType)
2187 == Context.getCanonicalType(ToPointeeType))
2188 return false;
2189
2190 // Perform the quick checks that will tell us whether these
2191 // function types are obviously different.
2192 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2193 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2194 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2195 return false;
2196
2197 bool HasObjCConversion = false;
2198 if (Context.getCanonicalType(FromFunctionType->getResultType())
2199 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2200 // Okay, the types match exactly. Nothing to do.
2201 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2202 ToFunctionType->getResultType(),
2203 ConvertedType, IncompatibleObjC)) {
2204 // Okay, we have an Objective-C pointer conversion.
2205 HasObjCConversion = true;
2206 } else {
2207 // Function types are too different. Abort.
2208 return false;
2209 }
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Douglas Gregorc7887512008-12-19 19:13:09 +00002211 // Check argument types.
2212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2213 ArgIdx != NumArgs; ++ArgIdx) {
2214 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2215 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2216 if (Context.getCanonicalType(FromArgType)
2217 == Context.getCanonicalType(ToArgType)) {
2218 // Okay, the types match exactly. Nothing to do.
2219 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2220 ConvertedType, IncompatibleObjC)) {
2221 // Okay, we have an Objective-C pointer conversion.
2222 HasObjCConversion = true;
2223 } else {
2224 // Argument types are too different. Abort.
2225 return false;
2226 }
2227 }
2228
2229 if (HasObjCConversion) {
2230 // We had an Objective-C conversion. Allow this pointer
2231 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002232 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002233 IncompatibleObjC = true;
2234 return true;
2235 }
2236 }
2237
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002238 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002239}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002240
John McCallf85e1932011-06-15 23:02:42 +00002241/// \brief Determine whether this is an Objective-C writeback conversion,
2242/// used for parameter passing when performing automatic reference counting.
2243///
2244/// \param FromType The type we're converting form.
2245///
2246/// \param ToType The type we're converting to.
2247///
2248/// \param ConvertedType The type that will be produced after applying
2249/// this conversion.
2250bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2251 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002252 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002253 Context.hasSameUnqualifiedType(FromType, ToType))
2254 return false;
2255
2256 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2257 QualType ToPointee;
2258 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2259 ToPointee = ToPointer->getPointeeType();
2260 else
2261 return false;
2262
2263 Qualifiers ToQuals = ToPointee.getQualifiers();
2264 if (!ToPointee->isObjCLifetimeType() ||
2265 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002266 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002267 return false;
2268
2269 // Argument must be a pointer to __strong to __weak.
2270 QualType FromPointee;
2271 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2272 FromPointee = FromPointer->getPointeeType();
2273 else
2274 return false;
2275
2276 Qualifiers FromQuals = FromPointee.getQualifiers();
2277 if (!FromPointee->isObjCLifetimeType() ||
2278 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2279 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2280 return false;
2281
2282 // Make sure that we have compatible qualifiers.
2283 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2284 if (!ToQuals.compatiblyIncludes(FromQuals))
2285 return false;
2286
2287 // Remove qualifiers from the pointee type we're converting from; they
2288 // aren't used in the compatibility check belong, and we'll be adding back
2289 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2290 FromPointee = FromPointee.getUnqualifiedType();
2291
2292 // The unqualified form of the pointee types must be compatible.
2293 ToPointee = ToPointee.getUnqualifiedType();
2294 bool IncompatibleObjC;
2295 if (Context.typesAreCompatible(FromPointee, ToPointee))
2296 FromPointee = ToPointee;
2297 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2298 IncompatibleObjC))
2299 return false;
2300
2301 /// \brief Construct the type we're converting to, which is a pointer to
2302 /// __autoreleasing pointee.
2303 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2304 ConvertedType = Context.getPointerType(FromPointee);
2305 return true;
2306}
2307
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002308bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2309 QualType& ConvertedType) {
2310 QualType ToPointeeType;
2311 if (const BlockPointerType *ToBlockPtr =
2312 ToType->getAs<BlockPointerType>())
2313 ToPointeeType = ToBlockPtr->getPointeeType();
2314 else
2315 return false;
2316
2317 QualType FromPointeeType;
2318 if (const BlockPointerType *FromBlockPtr =
2319 FromType->getAs<BlockPointerType>())
2320 FromPointeeType = FromBlockPtr->getPointeeType();
2321 else
2322 return false;
2323 // We have pointer to blocks, check whether the only
2324 // differences in the argument and result types are in Objective-C
2325 // pointer conversions. If so, we permit the conversion.
2326
2327 const FunctionProtoType *FromFunctionType
2328 = FromPointeeType->getAs<FunctionProtoType>();
2329 const FunctionProtoType *ToFunctionType
2330 = ToPointeeType->getAs<FunctionProtoType>();
2331
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002332 if (!FromFunctionType || !ToFunctionType)
2333 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002334
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002335 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002336 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002337
2338 // Perform the quick checks that will tell us whether these
2339 // function types are obviously different.
2340 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2341 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2342 return false;
2343
2344 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2345 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2346 if (FromEInfo != ToEInfo)
2347 return false;
2348
2349 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002350 if (Context.hasSameType(FromFunctionType->getResultType(),
2351 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002352 // Okay, the types match exactly. Nothing to do.
2353 } else {
2354 QualType RHS = FromFunctionType->getResultType();
2355 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002356 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002357 !RHS.hasQualifiers() && LHS.hasQualifiers())
2358 LHS = LHS.getUnqualifiedType();
2359
2360 if (Context.hasSameType(RHS,LHS)) {
2361 // OK exact match.
2362 } else if (isObjCPointerConversion(RHS, LHS,
2363 ConvertedType, IncompatibleObjC)) {
2364 if (IncompatibleObjC)
2365 return false;
2366 // Okay, we have an Objective-C pointer conversion.
2367 }
2368 else
2369 return false;
2370 }
2371
2372 // Check argument types.
2373 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2374 ArgIdx != NumArgs; ++ArgIdx) {
2375 IncompatibleObjC = false;
2376 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2377 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2378 if (Context.hasSameType(FromArgType, ToArgType)) {
2379 // Okay, the types match exactly. Nothing to do.
2380 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2381 ConvertedType, IncompatibleObjC)) {
2382 if (IncompatibleObjC)
2383 return false;
2384 // Okay, we have an Objective-C pointer conversion.
2385 } else
2386 // Argument types are too different. Abort.
2387 return false;
2388 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002389 if (LangOpts.ObjCAutoRefCount &&
2390 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2391 ToFunctionType))
2392 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002393
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002394 ConvertedType = ToType;
2395 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002396}
2397
Richard Trieu6efd4c52011-11-23 22:32:32 +00002398enum {
2399 ft_default,
2400 ft_different_class,
2401 ft_parameter_arity,
2402 ft_parameter_mismatch,
2403 ft_return_type,
2404 ft_qualifer_mismatch
2405};
2406
2407/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2408/// function types. Catches different number of parameter, mismatch in
2409/// parameter types, and different return types.
2410void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2411 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002412 // If either type is not valid, include no extra info.
2413 if (FromType.isNull() || ToType.isNull()) {
2414 PDiag << ft_default;
2415 return;
2416 }
2417
Richard Trieu6efd4c52011-11-23 22:32:32 +00002418 // Get the function type from the pointers.
2419 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2420 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2421 *ToMember = ToType->getAs<MemberPointerType>();
2422 if (FromMember->getClass() != ToMember->getClass()) {
2423 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2424 << QualType(FromMember->getClass(), 0);
2425 return;
2426 }
2427 FromType = FromMember->getPointeeType();
2428 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002429 }
2430
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002431 if (FromType->isPointerType())
2432 FromType = FromType->getPointeeType();
2433 if (ToType->isPointerType())
2434 ToType = ToType->getPointeeType();
2435
2436 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002437 FromType = FromType.getNonReferenceType();
2438 ToType = ToType.getNonReferenceType();
2439
Richard Trieu6efd4c52011-11-23 22:32:32 +00002440 // Don't print extra info for non-specialized template functions.
2441 if (FromType->isInstantiationDependentType() &&
2442 !FromType->getAs<TemplateSpecializationType>()) {
2443 PDiag << ft_default;
2444 return;
2445 }
2446
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002447 // No extra info for same types.
2448 if (Context.hasSameType(FromType, ToType)) {
2449 PDiag << ft_default;
2450 return;
2451 }
2452
Richard Trieu6efd4c52011-11-23 22:32:32 +00002453 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2454 *ToFunction = ToType->getAs<FunctionProtoType>();
2455
2456 // Both types need to be function types.
2457 if (!FromFunction || !ToFunction) {
2458 PDiag << ft_default;
2459 return;
2460 }
2461
2462 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2463 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2464 << FromFunction->getNumArgs();
2465 return;
2466 }
2467
2468 // Handle different parameter types.
2469 unsigned ArgPos;
2470 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2471 PDiag << ft_parameter_mismatch << ArgPos + 1
2472 << ToFunction->getArgType(ArgPos)
2473 << FromFunction->getArgType(ArgPos);
2474 return;
2475 }
2476
2477 // Handle different return type.
2478 if (!Context.hasSameType(FromFunction->getResultType(),
2479 ToFunction->getResultType())) {
2480 PDiag << ft_return_type << ToFunction->getResultType()
2481 << FromFunction->getResultType();
2482 return;
2483 }
2484
2485 unsigned FromQuals = FromFunction->getTypeQuals(),
2486 ToQuals = ToFunction->getTypeQuals();
2487 if (FromQuals != ToQuals) {
2488 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2489 return;
2490 }
2491
2492 // Unable to find a difference, so add no extra info.
2493 PDiag << ft_default;
2494}
2495
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002496/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002497/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002498/// they have same number of arguments. This routine assumes that Objective-C
2499/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002500/// If the parameters are different, ArgPos will have the the parameter index
2501/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002502bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002503 const FunctionProtoType *NewType,
2504 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002505 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002506 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2507 N = NewType->arg_type_begin(),
2508 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2509 if (!Context.hasSameType(*O, *N)) {
2510 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2511 return false;
2512 }
2513 }
2514 return true;
2515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002517 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2518 N = NewType->arg_type_begin(),
2519 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2520 QualType ToType = (*O);
2521 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002522 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002523 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2524 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002525 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2526 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2527 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2528 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002529 continue;
2530 }
John McCallc12c5bb2010-05-15 11:32:37 +00002531 else if (const ObjCObjectPointerType *PTTo =
2532 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002534 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002535 if (Context.hasSameUnqualifiedType(
2536 PTTo->getObjectType()->getBaseType(),
2537 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002538 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002539 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002540 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002542 }
2543 }
2544 return true;
2545}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002546
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002547/// CheckPointerConversion - Check the pointer conversion from the
2548/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002549/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550/// conversions for which IsPointerConversion has already returned
2551/// true. It returns true and produces a diagnostic if there was an
2552/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002553bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002554 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002555 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002556 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002557 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002558 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002559
John McCalldaa8e4e2010-11-15 09:13:47 +00002560 Kind = CK_BitCast;
2561
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002562 if (!IsCStyleOrFunctionalCast &&
2563 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2564 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2565 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002566 PDiag(diag::warn_impcast_bool_to_null_pointer)
2567 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002568
John McCall1d9b3b22011-09-09 05:25:32 +00002569 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2570 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002571 QualType FromPointeeType = FromPtrType->getPointeeType(),
2572 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002573
Douglas Gregor5fccd362010-03-03 23:55:11 +00002574 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2575 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002576 // We must have a derived-to-base conversion. Check an
2577 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002578 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2579 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002580 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002581 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002582 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583
Anders Carlsson61faec12009-09-12 04:46:44 +00002584 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002585 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002586 }
2587 }
John McCall1d9b3b22011-09-09 05:25:32 +00002588 } else if (const ObjCObjectPointerType *ToPtrType =
2589 ToType->getAs<ObjCObjectPointerType>()) {
2590 if (const ObjCObjectPointerType *FromPtrType =
2591 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002592 // Objective-C++ conversions are always okay.
2593 // FIXME: We should have a different class of conversions for the
2594 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002595 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002596 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002597 } else if (FromType->isBlockPointerType()) {
2598 Kind = CK_BlockPointerToObjCPointerCast;
2599 } else {
2600 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002601 }
John McCall1d9b3b22011-09-09 05:25:32 +00002602 } else if (ToType->isBlockPointerType()) {
2603 if (!FromType->isBlockPointerType())
2604 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002605 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002606
2607 // We shouldn't fall into this case unless it's valid for other
2608 // reasons.
2609 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2610 Kind = CK_NullToPointer;
2611
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002612 return false;
2613}
2614
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002615/// IsMemberPointerConversion - Determines whether the conversion of the
2616/// expression From, which has the (possibly adjusted) type FromType, can be
2617/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2618/// If so, returns true and places the converted type (that might differ from
2619/// ToType in its cv-qualifiers at some level) into ConvertedType.
2620bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002622 bool InOverloadResolution,
2623 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002624 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002625 if (!ToTypePtr)
2626 return false;
2627
2628 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002629 if (From->isNullPointerConstant(Context,
2630 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2631 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002632 ConvertedType = ToType;
2633 return true;
2634 }
2635
2636 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002637 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002638 if (!FromTypePtr)
2639 return false;
2640
2641 // A pointer to member of B can be converted to a pointer to member of D,
2642 // where D is derived from B (C++ 4.11p2).
2643 QualType FromClass(FromTypePtr->getClass(), 0);
2644 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002645
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002646 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002647 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002648 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002649 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2650 ToClass.getTypePtr());
2651 return true;
2652 }
2653
2654 return false;
2655}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002657/// CheckMemberPointerConversion - Check the member pointer conversion from the
2658/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002659/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002660/// for which IsMemberPointerConversion has already returned true. It returns
2661/// true and produces a diagnostic if there was an error, or returns false
2662/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002663bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002664 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002665 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002666 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002667 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002668 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002669 if (!FromPtrType) {
2670 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002672 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002673 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002674 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002675 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002676 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002677
Ted Kremenek6217b802009-07-29 21:53:49 +00002678 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002679 assert(ToPtrType && "No member pointer cast has a target type "
2680 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002681
Sebastian Redl21593ac2009-01-28 18:33:18 +00002682 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2683 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002684
Sebastian Redl21593ac2009-01-28 18:33:18 +00002685 // FIXME: What about dependent types?
2686 assert(FromClass->isRecordType() && "Pointer into non-class.");
2687 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002688
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002690 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002691 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2692 assert(DerivationOkay &&
2693 "Should not have been called if derivation isn't OK.");
2694 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002695
Sebastian Redl21593ac2009-01-28 18:33:18 +00002696 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2697 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002698 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2699 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2700 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2701 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002702 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002703
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002704 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002705 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2706 << FromClass << ToClass << QualType(VBase, 0)
2707 << From->getSourceRange();
2708 return true;
2709 }
2710
John McCall6b2accb2010-02-10 09:31:12 +00002711 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002712 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2713 Paths.front(),
2714 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002715
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002716 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002717 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002718 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002719 return false;
2720}
2721
Douglas Gregor98cd5992008-10-21 23:43:52 +00002722/// IsQualificationConversion - Determines whether the conversion from
2723/// an rvalue of type FromType to ToType is a qualification conversion
2724/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002725///
2726/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2727/// when the qualification conversion involves a change in the Objective-C
2728/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002729bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002730Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002731 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002732 FromType = Context.getCanonicalType(FromType);
2733 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002734 ObjCLifetimeConversion = false;
2735
Douglas Gregor98cd5992008-10-21 23:43:52 +00002736 // If FromType and ToType are the same type, this is not a
2737 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002738 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002740
Douglas Gregor98cd5992008-10-21 23:43:52 +00002741 // (C++ 4.4p4):
2742 // A conversion can add cv-qualifiers at levels other than the first
2743 // in multi-level pointers, subject to the following rules: [...]
2744 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002745 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002746 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002747 // Within each iteration of the loop, we check the qualifiers to
2748 // determine if this still looks like a qualification
2749 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002750 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002751 // until there are no more pointers or pointers-to-members left to
2752 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002753 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002754
Douglas Gregor621c92a2011-04-25 18:40:17 +00002755 Qualifiers FromQuals = FromType.getQualifiers();
2756 Qualifiers ToQuals = ToType.getQualifiers();
2757
John McCallf85e1932011-06-15 23:02:42 +00002758 // Objective-C ARC:
2759 // Check Objective-C lifetime conversions.
2760 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2761 UnwrappedAnyPointer) {
2762 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2763 ObjCLifetimeConversion = true;
2764 FromQuals.removeObjCLifetime();
2765 ToQuals.removeObjCLifetime();
2766 } else {
2767 // Qualification conversions cannot cast between different
2768 // Objective-C lifetime qualifiers.
2769 return false;
2770 }
2771 }
2772
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002773 // Allow addition/removal of GC attributes but not changing GC attributes.
2774 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2775 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2776 FromQuals.removeObjCGCAttr();
2777 ToQuals.removeObjCGCAttr();
2778 }
2779
Douglas Gregor98cd5992008-10-21 23:43:52 +00002780 // -- for every j > 0, if const is in cv 1,j then const is in cv
2781 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002782 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002783 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Douglas Gregor98cd5992008-10-21 23:43:52 +00002785 // -- if the cv 1,j and cv 2,j are different, then const is in
2786 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002787 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002788 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002789 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Douglas Gregor98cd5992008-10-21 23:43:52 +00002791 // Keep track of whether all prior cv-qualifiers in the "to" type
2792 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002793 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002794 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002795 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002796
2797 // We are left with FromType and ToType being the pointee types
2798 // after unwrapping the original FromType and ToType the same number
2799 // of types. If we unwrapped any pointers, and if FromType and
2800 // ToType have the same unqualified type (since we checked
2801 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002802 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002803}
2804
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002805/// \brief - Determine whether this is a conversion from a scalar type to an
2806/// atomic type.
2807///
2808/// If successful, updates \c SCS's second and third steps in the conversion
2809/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002810static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2811 bool InOverloadResolution,
2812 StandardConversionSequence &SCS,
2813 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002814 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2815 if (!ToAtomic)
2816 return false;
2817
2818 StandardConversionSequence InnerSCS;
2819 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2820 InOverloadResolution, InnerSCS,
2821 CStyle, /*AllowObjCWritebackConversion=*/false))
2822 return false;
2823
2824 SCS.Second = InnerSCS.Second;
2825 SCS.setToType(1, InnerSCS.getToType(1));
2826 SCS.Third = InnerSCS.Third;
2827 SCS.QualificationIncludesObjCLifetime
2828 = InnerSCS.QualificationIncludesObjCLifetime;
2829 SCS.setToType(2, InnerSCS.getToType(2));
2830 return true;
2831}
2832
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002833static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2834 CXXConstructorDecl *Constructor,
2835 QualType Type) {
2836 const FunctionProtoType *CtorType =
2837 Constructor->getType()->getAs<FunctionProtoType>();
2838 if (CtorType->getNumArgs() > 0) {
2839 QualType FirstArg = CtorType->getArgType(0);
2840 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2841 return true;
2842 }
2843 return false;
2844}
2845
Sebastian Redl56a04282012-02-11 23:51:08 +00002846static OverloadingResult
2847IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2848 CXXRecordDecl *To,
2849 UserDefinedConversionSequence &User,
2850 OverloadCandidateSet &CandidateSet,
2851 bool AllowExplicit) {
2852 DeclContext::lookup_iterator Con, ConEnd;
2853 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2854 Con != ConEnd; ++Con) {
2855 NamedDecl *D = *Con;
2856 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2857
2858 // Find the constructor (which may be a template).
2859 CXXConstructorDecl *Constructor = 0;
2860 FunctionTemplateDecl *ConstructorTmpl
2861 = dyn_cast<FunctionTemplateDecl>(D);
2862 if (ConstructorTmpl)
2863 Constructor
2864 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2865 else
2866 Constructor = cast<CXXConstructorDecl>(D);
2867
2868 bool Usable = !Constructor->isInvalidDecl() &&
2869 S.isInitListConstructor(Constructor) &&
2870 (AllowExplicit || !Constructor->isExplicit());
2871 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002872 // If the first argument is (a reference to) the target type,
2873 // suppress conversions.
2874 bool SuppressUserConversions =
2875 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002876 if (ConstructorTmpl)
2877 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2878 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002879 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002880 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002881 else
2882 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002883 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002884 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002885 }
2886 }
2887
2888 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2889
2890 OverloadCandidateSet::iterator Best;
2891 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2892 case OR_Success: {
2893 // Record the standard conversion we used and the conversion function.
2894 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2895 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2896
2897 QualType ThisType = Constructor->getThisType(S.Context);
2898 // Initializer lists don't have conversions as such.
2899 User.Before.setAsIdentityConversion();
2900 User.HadMultipleCandidates = HadMultipleCandidates;
2901 User.ConversionFunction = Constructor;
2902 User.FoundConversionFunction = Best->FoundDecl;
2903 User.After.setAsIdentityConversion();
2904 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2905 User.After.setAllToTypes(ToType);
2906 return OR_Success;
2907 }
2908
2909 case OR_No_Viable_Function:
2910 return OR_No_Viable_Function;
2911 case OR_Deleted:
2912 return OR_Deleted;
2913 case OR_Ambiguous:
2914 return OR_Ambiguous;
2915 }
2916
2917 llvm_unreachable("Invalid OverloadResult!");
2918}
2919
Douglas Gregor734d9862009-01-30 23:27:23 +00002920/// Determines whether there is a user-defined conversion sequence
2921/// (C++ [over.ics.user]) that converts expression From to the type
2922/// ToType. If such a conversion exists, User will contain the
2923/// user-defined conversion sequence that performs such a conversion
2924/// and this routine will return true. Otherwise, this routine returns
2925/// false and User is unspecified.
2926///
Douglas Gregor734d9862009-01-30 23:27:23 +00002927/// \param AllowExplicit true if the conversion should consider C++0x
2928/// "explicit" conversion functions as well as non-explicit conversion
2929/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002930static OverloadingResult
2931IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002932 UserDefinedConversionSequence &User,
2933 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002934 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002935 // Whether we will only visit constructors.
2936 bool ConstructorsOnly = false;
2937
2938 // If the type we are conversion to is a class type, enumerate its
2939 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002940 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002941 // C++ [over.match.ctor]p1:
2942 // When objects of class type are direct-initialized (8.5), or
2943 // copy-initialized from an expression of the same or a
2944 // derived class type (8.5), overload resolution selects the
2945 // constructor. [...] For copy-initialization, the candidate
2946 // functions are all the converting constructors (12.3.1) of
2947 // that class. The argument list is the expression-list within
2948 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002949 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002950 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002951 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002952 ConstructorsOnly = true;
2953
Douglas Gregord10099e2012-05-04 16:32:21 +00002954 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002955 // RequireCompleteType may have returned true due to some invalid decl
2956 // during template instantiation, but ToType may be complete enough now
2957 // to try to recover.
2958 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002959 // We're not going to find any constructors.
2960 } else if (CXXRecordDecl *ToRecordDecl
2961 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002962
2963 Expr **Args = &From;
2964 unsigned NumArgs = 1;
2965 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002966 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002967 // But first, see if there is an init-list-contructor that will work.
2968 OverloadingResult Result = IsInitializerListConstructorConversion(
2969 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2970 if (Result != OR_No_Viable_Function)
2971 return Result;
2972 // Never mind.
2973 CandidateSet.clear();
2974
2975 // If we're list-initializing, we pass the individual elements as
2976 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002977 Args = InitList->getInits();
2978 NumArgs = InitList->getNumInits();
2979 ListInitializing = true;
2980 }
2981
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002982 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002983 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002984 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002985 NamedDecl *D = *Con;
2986 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2987
Douglas Gregordec06662009-08-21 18:42:58 +00002988 // Find the constructor (which may be a template).
2989 CXXConstructorDecl *Constructor = 0;
2990 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002991 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002992 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002993 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002994 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2995 else
John McCall9aa472c2010-03-19 07:35:19 +00002996 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002997
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002998 bool Usable = !Constructor->isInvalidDecl();
2999 if (ListInitializing)
3000 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3001 else
3002 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3003 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003004 bool SuppressUserConversions = !ConstructorsOnly;
3005 if (SuppressUserConversions && ListInitializing) {
3006 SuppressUserConversions = false;
3007 if (NumArgs == 1) {
3008 // If the first argument is (a reference to) the target type,
3009 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003010 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3011 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003012 }
3013 }
Douglas Gregordec06662009-08-21 18:42:58 +00003014 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003015 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3016 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003017 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003018 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003019 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003020 // Allow one user-defined conversion when user specifies a
3021 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003022 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003023 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003024 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003025 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003026 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003027 }
3028 }
3029
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003030 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003031 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003032 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003033 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003034 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003035 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003036 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003037 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3038 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003039 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003040 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003041 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003042 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003043 DeclAccessPair FoundDecl = I.getPair();
3044 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003045 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3046 if (isa<UsingShadowDecl>(D))
3047 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3048
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003049 CXXConversionDecl *Conv;
3050 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003051 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3052 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003053 else
John McCall32daa422010-03-31 01:36:47 +00003054 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003055
3056 if (AllowExplicit || !Conv->isExplicit()) {
3057 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003058 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3059 ActingContext, From, ToType,
3060 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003061 else
John McCall120d63c2010-08-24 20:38:10 +00003062 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3063 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003064 }
3065 }
3066 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003067 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003068
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003069 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3070
Douglas Gregor60d62c22008-10-31 16:23:19 +00003071 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003072 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003073 case OR_Success:
3074 // Record the standard conversion we used and the conversion function.
3075 if (CXXConstructorDecl *Constructor
3076 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003077 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003078
John McCall120d63c2010-08-24 20:38:10 +00003079 // C++ [over.ics.user]p1:
3080 // If the user-defined conversion is specified by a
3081 // constructor (12.3.1), the initial standard conversion
3082 // sequence converts the source type to the type required by
3083 // the argument of the constructor.
3084 //
3085 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003086 if (isa<InitListExpr>(From)) {
3087 // Initializer lists don't have conversions as such.
3088 User.Before.setAsIdentityConversion();
3089 } else {
3090 if (Best->Conversions[0].isEllipsis())
3091 User.EllipsisConversion = true;
3092 else {
3093 User.Before = Best->Conversions[0].Standard;
3094 User.EllipsisConversion = false;
3095 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003096 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003097 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003098 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003099 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003100 User.After.setAsIdentityConversion();
3101 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3102 User.After.setAllToTypes(ToType);
3103 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003104 }
3105 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003106 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003107 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003108
John McCall120d63c2010-08-24 20:38:10 +00003109 // C++ [over.ics.user]p1:
3110 //
3111 // [...] If the user-defined conversion is specified by a
3112 // conversion function (12.3.2), the initial standard
3113 // conversion sequence converts the source type to the
3114 // implicit object parameter of the conversion function.
3115 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003116 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003117 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003118 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003119 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003120
John McCall120d63c2010-08-24 20:38:10 +00003121 // C++ [over.ics.user]p2:
3122 // The second standard conversion sequence converts the
3123 // result of the user-defined conversion to the target type
3124 // for the sequence. Since an implicit conversion sequence
3125 // is an initialization, the special rules for
3126 // initialization by user-defined conversion apply when
3127 // selecting the best user-defined conversion for a
3128 // user-defined conversion sequence (see 13.3.3 and
3129 // 13.3.3.1).
3130 User.After = Best->FinalConversion;
3131 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003132 }
David Blaikie7530c032012-01-17 06:56:22 +00003133 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003134
John McCall120d63c2010-08-24 20:38:10 +00003135 case OR_No_Viable_Function:
3136 return OR_No_Viable_Function;
3137 case OR_Deleted:
3138 // No conversion here! We're done.
3139 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
John McCall120d63c2010-08-24 20:38:10 +00003141 case OR_Ambiguous:
3142 return OR_Ambiguous;
3143 }
3144
David Blaikie7530c032012-01-17 06:56:22 +00003145 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003146}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003148bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003149Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003150 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003151 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003153 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003154 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003155 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003156 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003157 diag::err_typecheck_ambiguous_condition)
3158 << From->getType() << ToType << From->getSourceRange();
3159 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003160 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003161 diag::err_typecheck_nonviable_condition)
3162 << From->getType() << ToType << From->getSourceRange();
3163 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003164 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003166 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003167}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003168
Douglas Gregorb734e242012-02-22 17:32:19 +00003169/// \brief Compare the user-defined conversion functions or constructors
3170/// of two user-defined conversion sequences to determine whether any ordering
3171/// is possible.
3172static ImplicitConversionSequence::CompareKind
3173compareConversionFunctions(Sema &S,
3174 FunctionDecl *Function1,
3175 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003176 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003177 return ImplicitConversionSequence::Indistinguishable;
3178
3179 // Objective-C++:
3180 // If both conversion functions are implicitly-declared conversions from
3181 // a lambda closure type to a function pointer and a block pointer,
3182 // respectively, always prefer the conversion to a function pointer,
3183 // because the function pointer is more lightweight and is more likely
3184 // to keep code working.
3185 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3186 if (!Conv1)
3187 return ImplicitConversionSequence::Indistinguishable;
3188
3189 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3190 if (!Conv2)
3191 return ImplicitConversionSequence::Indistinguishable;
3192
3193 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3194 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3195 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3196 if (Block1 != Block2)
3197 return Block1? ImplicitConversionSequence::Worse
3198 : ImplicitConversionSequence::Better;
3199 }
3200
3201 return ImplicitConversionSequence::Indistinguishable;
3202}
3203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003204/// CompareImplicitConversionSequences - Compare two implicit
3205/// conversion sequences to determine whether one is better than the
3206/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003207static ImplicitConversionSequence::CompareKind
3208CompareImplicitConversionSequences(Sema &S,
3209 const ImplicitConversionSequence& ICS1,
3210 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003211{
3212 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3213 // conversion sequences (as defined in 13.3.3.1)
3214 // -- a standard conversion sequence (13.3.3.1.1) is a better
3215 // conversion sequence than a user-defined conversion sequence or
3216 // an ellipsis conversion sequence, and
3217 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3218 // conversion sequence than an ellipsis conversion sequence
3219 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003220 //
John McCall1d318332010-01-12 00:44:57 +00003221 // C++0x [over.best.ics]p10:
3222 // For the purpose of ranking implicit conversion sequences as
3223 // described in 13.3.3.2, the ambiguous conversion sequence is
3224 // treated as a user-defined sequence that is indistinguishable
3225 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003226 if (ICS1.getKindRank() < ICS2.getKindRank())
3227 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003228 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003229 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003230
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003231 // The following checks require both conversion sequences to be of
3232 // the same kind.
3233 if (ICS1.getKind() != ICS2.getKind())
3234 return ImplicitConversionSequence::Indistinguishable;
3235
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003236 ImplicitConversionSequence::CompareKind Result =
3237 ImplicitConversionSequence::Indistinguishable;
3238
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003239 // Two implicit conversion sequences of the same form are
3240 // indistinguishable conversion sequences unless one of the
3241 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003242 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003243 Result = CompareStandardConversionSequences(S,
3244 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003245 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003246 // User-defined conversion sequence U1 is a better conversion
3247 // sequence than another user-defined conversion sequence U2 if
3248 // they contain the same user-defined conversion function or
3249 // constructor and if the second standard conversion sequence of
3250 // U1 is better than the second standard conversion sequence of
3251 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003252 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003253 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003254 Result = CompareStandardConversionSequences(S,
3255 ICS1.UserDefined.After,
3256 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003257 else
3258 Result = compareConversionFunctions(S,
3259 ICS1.UserDefined.ConversionFunction,
3260 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003261 }
3262
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003263 // List-initialization sequence L1 is a better conversion sequence than
3264 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3265 // for some X and L2 does not.
3266 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003267 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003268 ICS1.isListInitializationSequence() &&
3269 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003270 if (ICS1.isStdInitializerListElement() &&
3271 !ICS2.isStdInitializerListElement())
3272 return ImplicitConversionSequence::Better;
3273 if (!ICS1.isStdInitializerListElement() &&
3274 ICS2.isStdInitializerListElement())
3275 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003276 }
3277
3278 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003279}
3280
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003281static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3282 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3283 Qualifiers Quals;
3284 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003288 return Context.hasSameUnqualifiedType(T1, T2);
3289}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290
Douglas Gregorad323a82010-01-27 03:51:04 +00003291// Per 13.3.3.2p3, compare the given standard conversion sequences to
3292// determine if one is a proper subset of the other.
3293static ImplicitConversionSequence::CompareKind
3294compareStandardConversionSubsets(ASTContext &Context,
3295 const StandardConversionSequence& SCS1,
3296 const StandardConversionSequence& SCS2) {
3297 ImplicitConversionSequence::CompareKind Result
3298 = ImplicitConversionSequence::Indistinguishable;
3299
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003300 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003301 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003302 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3303 return ImplicitConversionSequence::Better;
3304 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3305 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003306
Douglas Gregorad323a82010-01-27 03:51:04 +00003307 if (SCS1.Second != SCS2.Second) {
3308 if (SCS1.Second == ICK_Identity)
3309 Result = ImplicitConversionSequence::Better;
3310 else if (SCS2.Second == ICK_Identity)
3311 Result = ImplicitConversionSequence::Worse;
3312 else
3313 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003314 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003315 return ImplicitConversionSequence::Indistinguishable;
3316
3317 if (SCS1.Third == SCS2.Third) {
3318 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3319 : ImplicitConversionSequence::Indistinguishable;
3320 }
3321
3322 if (SCS1.Third == ICK_Identity)
3323 return Result == ImplicitConversionSequence::Worse
3324 ? ImplicitConversionSequence::Indistinguishable
3325 : ImplicitConversionSequence::Better;
3326
3327 if (SCS2.Third == ICK_Identity)
3328 return Result == ImplicitConversionSequence::Better
3329 ? ImplicitConversionSequence::Indistinguishable
3330 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331
Douglas Gregorad323a82010-01-27 03:51:04 +00003332 return ImplicitConversionSequence::Indistinguishable;
3333}
3334
Douglas Gregor440a4832011-01-26 14:52:12 +00003335/// \brief Determine whether one of the given reference bindings is better
3336/// than the other based on what kind of bindings they are.
3337static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3338 const StandardConversionSequence &SCS2) {
3339 // C++0x [over.ics.rank]p3b4:
3340 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3341 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003343 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003345 // reference*.
3346 //
3347 // FIXME: Rvalue references. We're going rogue with the above edits,
3348 // because the semantics in the current C++0x working paper (N3225 at the
3349 // time of this writing) break the standard definition of std::forward
3350 // and std::reference_wrapper when dealing with references to functions.
3351 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003352 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3353 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3354 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355
Douglas Gregor440a4832011-01-26 14:52:12 +00003356 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3357 SCS2.IsLvalueReference) ||
3358 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3359 !SCS2.IsLvalueReference);
3360}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003361
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003362/// CompareStandardConversionSequences - Compare two standard
3363/// conversion sequences to determine whether one is better than the
3364/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003365static ImplicitConversionSequence::CompareKind
3366CompareStandardConversionSequences(Sema &S,
3367 const StandardConversionSequence& SCS1,
3368 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003369{
3370 // Standard conversion sequence S1 is a better conversion sequence
3371 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3372
3373 // -- S1 is a proper subsequence of S2 (comparing the conversion
3374 // sequences in the canonical form defined by 13.3.3.1.1,
3375 // excluding any Lvalue Transformation; the identity conversion
3376 // sequence is considered to be a subsequence of any
3377 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003378 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003379 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003380 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003381
3382 // -- the rank of S1 is better than the rank of S2 (by the rules
3383 // defined below), or, if not that,
3384 ImplicitConversionRank Rank1 = SCS1.getRank();
3385 ImplicitConversionRank Rank2 = SCS2.getRank();
3386 if (Rank1 < Rank2)
3387 return ImplicitConversionSequence::Better;
3388 else if (Rank2 < Rank1)
3389 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003390
Douglas Gregor57373262008-10-22 14:17:15 +00003391 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3392 // are indistinguishable unless one of the following rules
3393 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003394
Douglas Gregor57373262008-10-22 14:17:15 +00003395 // A conversion that is not a conversion of a pointer, or
3396 // pointer to member, to bool is better than another conversion
3397 // that is such a conversion.
3398 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3399 return SCS2.isPointerConversionToBool()
3400 ? ImplicitConversionSequence::Better
3401 : ImplicitConversionSequence::Worse;
3402
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003403 // C++ [over.ics.rank]p4b2:
3404 //
3405 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003406 // conversion of B* to A* is better than conversion of B* to
3407 // void*, and conversion of A* to void* is better than conversion
3408 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003409 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003410 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003411 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003412 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003413 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3414 // Exactly one of the conversion sequences is a conversion to
3415 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003416 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3417 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003418 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3419 // Neither conversion sequence converts to a void pointer; compare
3420 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003421 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003422 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003423 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003424 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3425 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003426 // Both conversion sequences are conversions to void
3427 // pointers. Compare the source types to determine if there's an
3428 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003429 QualType FromType1 = SCS1.getFromType();
3430 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003431
3432 // Adjust the types we're converting from via the array-to-pointer
3433 // conversion, if we need to.
3434 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003435 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003436 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003437 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003438
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003439 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3440 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003441
John McCall120d63c2010-08-24 20:38:10 +00003442 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003443 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003444 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003445 return ImplicitConversionSequence::Worse;
3446
3447 // Objective-C++: If one interface is more specific than the
3448 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003449 const ObjCObjectPointerType* FromObjCPtr1
3450 = FromType1->getAs<ObjCObjectPointerType>();
3451 const ObjCObjectPointerType* FromObjCPtr2
3452 = FromType2->getAs<ObjCObjectPointerType>();
3453 if (FromObjCPtr1 && FromObjCPtr2) {
3454 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3455 FromObjCPtr2);
3456 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3457 FromObjCPtr1);
3458 if (AssignLeft != AssignRight) {
3459 return AssignLeft? ImplicitConversionSequence::Better
3460 : ImplicitConversionSequence::Worse;
3461 }
Douglas Gregor01919692009-12-13 21:37:05 +00003462 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003463 }
Douglas Gregor57373262008-10-22 14:17:15 +00003464
3465 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3466 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003467 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003468 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003469 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003470
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003471 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003472 // Check for a better reference binding based on the kind of bindings.
3473 if (isBetterReferenceBindingKind(SCS1, SCS2))
3474 return ImplicitConversionSequence::Better;
3475 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3476 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003477
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003478 // C++ [over.ics.rank]p3b4:
3479 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3480 // which the references refer are the same type except for
3481 // top-level cv-qualifiers, and the type to which the reference
3482 // initialized by S2 refers is more cv-qualified than the type
3483 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003484 QualType T1 = SCS1.getToType(2);
3485 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003486 T1 = S.Context.getCanonicalType(T1);
3487 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003488 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003489 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3490 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003491 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003492 // Objective-C++ ARC: If the references refer to objects with different
3493 // lifetimes, prefer bindings that don't change lifetime.
3494 if (SCS1.ObjCLifetimeConversionBinding !=
3495 SCS2.ObjCLifetimeConversionBinding) {
3496 return SCS1.ObjCLifetimeConversionBinding
3497 ? ImplicitConversionSequence::Worse
3498 : ImplicitConversionSequence::Better;
3499 }
3500
Chandler Carruth6df868e2010-12-12 08:17:55 +00003501 // If the type is an array type, promote the element qualifiers to the
3502 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003503 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003504 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003505 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003506 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003507 if (T2.isMoreQualifiedThan(T1))
3508 return ImplicitConversionSequence::Better;
3509 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003510 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003511 }
3512 }
Douglas Gregor57373262008-10-22 14:17:15 +00003513
Francois Pichet1c98d622011-09-18 21:37:37 +00003514 // In Microsoft mode, prefer an integral conversion to a
3515 // floating-to-integral conversion if the integral conversion
3516 // is between types of the same size.
3517 // For example:
3518 // void f(float);
3519 // void f(int);
3520 // int main {
3521 // long a;
3522 // f(a);
3523 // }
3524 // Here, MSVC will call f(int) instead of generating a compile error
3525 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003526 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003527 SCS1.Second == ICK_Integral_Conversion &&
3528 SCS2.Second == ICK_Floating_Integral &&
3529 S.Context.getTypeSize(SCS1.getFromType()) ==
3530 S.Context.getTypeSize(SCS1.getToType(2)))
3531 return ImplicitConversionSequence::Better;
3532
Douglas Gregor57373262008-10-22 14:17:15 +00003533 return ImplicitConversionSequence::Indistinguishable;
3534}
3535
3536/// CompareQualificationConversions - Compares two standard conversion
3537/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003538/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3539ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003540CompareQualificationConversions(Sema &S,
3541 const StandardConversionSequence& SCS1,
3542 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003543 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003544 // -- S1 and S2 differ only in their qualification conversion and
3545 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3546 // cv-qualification signature of type T1 is a proper subset of
3547 // the cv-qualification signature of type T2, and S1 is not the
3548 // deprecated string literal array-to-pointer conversion (4.2).
3549 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3550 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3551 return ImplicitConversionSequence::Indistinguishable;
3552
3553 // FIXME: the example in the standard doesn't use a qualification
3554 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003555 QualType T1 = SCS1.getToType(2);
3556 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003557 T1 = S.Context.getCanonicalType(T1);
3558 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003559 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003560 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3561 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003562
3563 // If the types are the same, we won't learn anything by unwrapped
3564 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003565 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003566 return ImplicitConversionSequence::Indistinguishable;
3567
Chandler Carruth28e318c2009-12-29 07:16:59 +00003568 // If the type is an array type, promote the element qualifiers to the type
3569 // for comparison.
3570 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003571 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003572 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003573 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003574
Mike Stump1eb44332009-09-09 15:08:12 +00003575 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003576 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003577
3578 // Objective-C++ ARC:
3579 // Prefer qualification conversions not involving a change in lifetime
3580 // to qualification conversions that do not change lifetime.
3581 if (SCS1.QualificationIncludesObjCLifetime !=
3582 SCS2.QualificationIncludesObjCLifetime) {
3583 Result = SCS1.QualificationIncludesObjCLifetime
3584 ? ImplicitConversionSequence::Worse
3585 : ImplicitConversionSequence::Better;
3586 }
3587
John McCall120d63c2010-08-24 20:38:10 +00003588 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003589 // Within each iteration of the loop, we check the qualifiers to
3590 // determine if this still looks like a qualification
3591 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003592 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003593 // until there are no more pointers or pointers-to-members left
3594 // to unwrap. This essentially mimics what
3595 // IsQualificationConversion does, but here we're checking for a
3596 // strict subset of qualifiers.
3597 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3598 // The qualifiers are the same, so this doesn't tell us anything
3599 // about how the sequences rank.
3600 ;
3601 else if (T2.isMoreQualifiedThan(T1)) {
3602 // T1 has fewer qualifiers, so it could be the better sequence.
3603 if (Result == ImplicitConversionSequence::Worse)
3604 // Neither has qualifiers that are a subset of the other's
3605 // qualifiers.
3606 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003607
Douglas Gregor57373262008-10-22 14:17:15 +00003608 Result = ImplicitConversionSequence::Better;
3609 } else if (T1.isMoreQualifiedThan(T2)) {
3610 // T2 has fewer qualifiers, so it could be the better sequence.
3611 if (Result == ImplicitConversionSequence::Better)
3612 // Neither has qualifiers that are a subset of the other's
3613 // qualifiers.
3614 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003615
Douglas Gregor57373262008-10-22 14:17:15 +00003616 Result = ImplicitConversionSequence::Worse;
3617 } else {
3618 // Qualifiers are disjoint.
3619 return ImplicitConversionSequence::Indistinguishable;
3620 }
3621
3622 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003623 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003624 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003625 }
3626
Douglas Gregor57373262008-10-22 14:17:15 +00003627 // Check that the winning standard conversion sequence isn't using
3628 // the deprecated string literal array to pointer conversion.
3629 switch (Result) {
3630 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003631 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003632 Result = ImplicitConversionSequence::Indistinguishable;
3633 break;
3634
3635 case ImplicitConversionSequence::Indistinguishable:
3636 break;
3637
3638 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003639 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003640 Result = ImplicitConversionSequence::Indistinguishable;
3641 break;
3642 }
3643
3644 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003645}
3646
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003647/// CompareDerivedToBaseConversions - Compares two standard conversion
3648/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003649/// various kinds of derived-to-base conversions (C++
3650/// [over.ics.rank]p4b3). As part of these checks, we also look at
3651/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003652ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003653CompareDerivedToBaseConversions(Sema &S,
3654 const StandardConversionSequence& SCS1,
3655 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003656 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003657 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003658 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003659 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003660
3661 // Adjust the types we're converting from via the array-to-pointer
3662 // conversion, if we need to.
3663 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003664 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003665 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003666 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003667
3668 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003669 FromType1 = S.Context.getCanonicalType(FromType1);
3670 ToType1 = S.Context.getCanonicalType(ToType1);
3671 FromType2 = S.Context.getCanonicalType(FromType2);
3672 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003673
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003674 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003675 //
3676 // If class B is derived directly or indirectly from class A and
3677 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003678 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003679 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003680 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003681 SCS2.Second == ICK_Pointer_Conversion &&
3682 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3683 FromType1->isPointerType() && FromType2->isPointerType() &&
3684 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003685 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003686 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003687 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003688 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003689 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003690 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003691 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003692 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003693
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003694 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003696 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003697 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003698 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003699 return ImplicitConversionSequence::Worse;
3700 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003701
3702 // -- conversion of B* to A* is better than conversion of C* to A*,
3703 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003704 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003705 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003706 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003707 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003708 }
3709 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3710 SCS2.Second == ICK_Pointer_Conversion) {
3711 const ObjCObjectPointerType *FromPtr1
3712 = FromType1->getAs<ObjCObjectPointerType>();
3713 const ObjCObjectPointerType *FromPtr2
3714 = FromType2->getAs<ObjCObjectPointerType>();
3715 const ObjCObjectPointerType *ToPtr1
3716 = ToType1->getAs<ObjCObjectPointerType>();
3717 const ObjCObjectPointerType *ToPtr2
3718 = ToType2->getAs<ObjCObjectPointerType>();
3719
3720 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3721 // Apply the same conversion ranking rules for Objective-C pointer types
3722 // that we do for C++ pointers to class types. However, we employ the
3723 // Objective-C pseudo-subtyping relationship used for assignment of
3724 // Objective-C pointer types.
3725 bool FromAssignLeft
3726 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3727 bool FromAssignRight
3728 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3729 bool ToAssignLeft
3730 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3731 bool ToAssignRight
3732 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3733
3734 // A conversion to an a non-id object pointer type or qualified 'id'
3735 // type is better than a conversion to 'id'.
3736 if (ToPtr1->isObjCIdType() &&
3737 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3738 return ImplicitConversionSequence::Worse;
3739 if (ToPtr2->isObjCIdType() &&
3740 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3741 return ImplicitConversionSequence::Better;
3742
3743 // A conversion to a non-id object pointer type is better than a
3744 // conversion to a qualified 'id' type
3745 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3746 return ImplicitConversionSequence::Worse;
3747 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3748 return ImplicitConversionSequence::Better;
3749
3750 // A conversion to an a non-Class object pointer type or qualified 'Class'
3751 // type is better than a conversion to 'Class'.
3752 if (ToPtr1->isObjCClassType() &&
3753 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3754 return ImplicitConversionSequence::Worse;
3755 if (ToPtr2->isObjCClassType() &&
3756 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3757 return ImplicitConversionSequence::Better;
3758
3759 // A conversion to a non-Class object pointer type is better than a
3760 // conversion to a qualified 'Class' type.
3761 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3762 return ImplicitConversionSequence::Worse;
3763 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3764 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Douglas Gregor395cc372011-01-31 18:51:41 +00003766 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3767 if (S.Context.hasSameType(FromType1, FromType2) &&
3768 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3769 (ToAssignLeft != ToAssignRight))
3770 return ToAssignLeft? ImplicitConversionSequence::Worse
3771 : ImplicitConversionSequence::Better;
3772
3773 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3774 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3775 (FromAssignLeft != FromAssignRight))
3776 return FromAssignLeft? ImplicitConversionSequence::Better
3777 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003778 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003779 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003780
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003781 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003782 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3783 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3784 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003786 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003788 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003790 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003792 ToType2->getAs<MemberPointerType>();
3793 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3794 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3795 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3796 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3797 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3798 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3799 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3800 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003801 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003802 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003803 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003804 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003805 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003806 return ImplicitConversionSequence::Better;
3807 }
3808 // conversion of B::* to C::* is better than conversion of A::* to C::*
3809 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003810 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003811 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003812 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003813 return ImplicitConversionSequence::Worse;
3814 }
3815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003817 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003818 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003819 // -- binding of an expression of type C to a reference of type
3820 // B& is better than binding an expression of type C to a
3821 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003822 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3823 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3824 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003825 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003826 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003827 return ImplicitConversionSequence::Worse;
3828 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003829
Douglas Gregor225c41e2008-11-03 19:09:14 +00003830 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003831 // -- binding of an expression of type B to a reference of type
3832 // A& is better than binding an expression of type C to a
3833 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003834 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3835 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3836 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003837 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003838 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003839 return ImplicitConversionSequence::Worse;
3840 }
3841 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003842
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003843 return ImplicitConversionSequence::Indistinguishable;
3844}
3845
Douglas Gregorabe183d2010-04-13 16:31:36 +00003846/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3847/// determine whether they are reference-related,
3848/// reference-compatible, reference-compatible with added
3849/// qualification, or incompatible, for use in C++ initialization by
3850/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3851/// type, and the first type (T1) is the pointee type of the reference
3852/// type being initialized.
3853Sema::ReferenceCompareResult
3854Sema::CompareReferenceRelationship(SourceLocation Loc,
3855 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003856 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003857 bool &ObjCConversion,
3858 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003859 assert(!OrigT1->isReferenceType() &&
3860 "T1 must be the pointee type of the reference type");
3861 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3862
3863 QualType T1 = Context.getCanonicalType(OrigT1);
3864 QualType T2 = Context.getCanonicalType(OrigT2);
3865 Qualifiers T1Quals, T2Quals;
3866 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3867 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3868
3869 // C++ [dcl.init.ref]p4:
3870 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3871 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3872 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003873 DerivedToBase = false;
3874 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003875 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003876 if (UnqualT1 == UnqualT2) {
3877 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003878 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003879 IsDerivedFrom(UnqualT2, UnqualT1))
3880 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003881 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3882 UnqualT2->isObjCObjectOrInterfaceType() &&
3883 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3884 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003885 else
3886 return Ref_Incompatible;
3887
3888 // At this point, we know that T1 and T2 are reference-related (at
3889 // least).
3890
3891 // If the type is an array type, promote the element qualifiers to the type
3892 // for comparison.
3893 if (isa<ArrayType>(T1) && T1Quals)
3894 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3895 if (isa<ArrayType>(T2) && T2Quals)
3896 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3897
3898 // C++ [dcl.init.ref]p4:
3899 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3900 // reference-related to T2 and cv1 is the same cv-qualification
3901 // as, or greater cv-qualification than, cv2. For purposes of
3902 // overload resolution, cases for which cv1 is greater
3903 // cv-qualification than cv2 are identified as
3904 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003905 //
3906 // Note that we also require equivalence of Objective-C GC and address-space
3907 // qualifiers when performing these computations, so that e.g., an int in
3908 // address space 1 is not reference-compatible with an int in address
3909 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003910 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3911 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3912 T1Quals.removeObjCLifetime();
3913 T2Quals.removeObjCLifetime();
3914 ObjCLifetimeConversion = true;
3915 }
3916
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003917 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003918 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003919 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003920 return Ref_Compatible_With_Added_Qualification;
3921 else
3922 return Ref_Related;
3923}
3924
Douglas Gregor604eb652010-08-11 02:15:33 +00003925/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003926/// with DeclType. Return true if something definite is found.
3927static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003928FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3929 QualType DeclType, SourceLocation DeclLoc,
3930 Expr *Init, QualType T2, bool AllowRvalues,
3931 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003932 assert(T2->isRecordType() && "Can only find conversions of record types.");
3933 CXXRecordDecl *T2RecordDecl
3934 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3935
3936 OverloadCandidateSet CandidateSet(DeclLoc);
3937 const UnresolvedSetImpl *Conversions
3938 = T2RecordDecl->getVisibleConversionFunctions();
3939 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3940 E = Conversions->end(); I != E; ++I) {
3941 NamedDecl *D = *I;
3942 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946 FunctionTemplateDecl *ConvTemplate
3947 = dyn_cast<FunctionTemplateDecl>(D);
3948 CXXConversionDecl *Conv;
3949 if (ConvTemplate)
3950 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3951 else
3952 Conv = cast<CXXConversionDecl>(D);
3953
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003954 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003955 // explicit conversions, skip it.
3956 if (!AllowExplicit && Conv->isExplicit())
3957 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003958
Douglas Gregor604eb652010-08-11 02:15:33 +00003959 if (AllowRvalues) {
3960 bool DerivedToBase = false;
3961 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003962 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003963
3964 // If we are initializing an rvalue reference, don't permit conversion
3965 // functions that return lvalues.
3966 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3967 const ReferenceType *RefType
3968 = Conv->getConversionType()->getAs<LValueReferenceType>();
3969 if (RefType && !RefType->getPointeeType()->isFunctionType())
3970 continue;
3971 }
3972
Douglas Gregor604eb652010-08-11 02:15:33 +00003973 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003974 S.CompareReferenceRelationship(
3975 DeclLoc,
3976 Conv->getConversionType().getNonReferenceType()
3977 .getUnqualifiedType(),
3978 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003979 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003980 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003981 continue;
3982 } else {
3983 // If the conversion function doesn't return a reference type,
3984 // it can't be considered for this conversion. An rvalue reference
3985 // is only acceptable if its referencee is a function type.
3986
3987 const ReferenceType *RefType =
3988 Conv->getConversionType()->getAs<ReferenceType>();
3989 if (!RefType ||
3990 (!RefType->isLValueReferenceType() &&
3991 !RefType->getPointeeType()->isFunctionType()))
3992 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003993 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994
Douglas Gregor604eb652010-08-11 02:15:33 +00003995 if (ConvTemplate)
3996 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003997 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003998 else
3999 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004000 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004001 }
4002
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004003 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4004
Sebastian Redl4680bf22010-06-30 18:13:39 +00004005 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004006 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004007 case OR_Success:
4008 // C++ [over.ics.ref]p1:
4009 //
4010 // [...] If the parameter binds directly to the result of
4011 // applying a conversion function to the argument
4012 // expression, the implicit conversion sequence is a
4013 // user-defined conversion sequence (13.3.3.1.2), with the
4014 // second standard conversion sequence either an identity
4015 // conversion or, if the conversion function returns an
4016 // entity of a type that is a derived class of the parameter
4017 // type, a derived-to-base Conversion.
4018 if (!Best->FinalConversion.DirectBinding)
4019 return false;
4020
Chandler Carruth25ca4212011-02-25 19:41:05 +00004021 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004022 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004023 ICS.setUserDefined();
4024 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4025 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004026 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004027 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004028 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004029 ICS.UserDefined.EllipsisConversion = false;
4030 assert(ICS.UserDefined.After.ReferenceBinding &&
4031 ICS.UserDefined.After.DirectBinding &&
4032 "Expected a direct reference binding!");
4033 return true;
4034
4035 case OR_Ambiguous:
4036 ICS.setAmbiguous();
4037 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4038 Cand != CandidateSet.end(); ++Cand)
4039 if (Cand->Viable)
4040 ICS.Ambiguous.addConversion(Cand->Function);
4041 return true;
4042
4043 case OR_No_Viable_Function:
4044 case OR_Deleted:
4045 // There was no suitable conversion, or we found a deleted
4046 // conversion; continue with other checks.
4047 return false;
4048 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004049
David Blaikie7530c032012-01-17 06:56:22 +00004050 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004051}
4052
Douglas Gregorabe183d2010-04-13 16:31:36 +00004053/// \brief Compute an implicit conversion sequence for reference
4054/// initialization.
4055static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004056TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004057 SourceLocation DeclLoc,
4058 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004059 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004060 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4061
4062 // Most paths end in a failed conversion.
4063 ImplicitConversionSequence ICS;
4064 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4065
4066 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4067 QualType T2 = Init->getType();
4068
4069 // If the initializer is the address of an overloaded function, try
4070 // to resolve the overloaded function. If all goes well, T2 is the
4071 // type of the resulting function.
4072 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4073 DeclAccessPair Found;
4074 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4075 false, Found))
4076 T2 = Fn->getType();
4077 }
4078
4079 // Compute some basic properties of the types and the initializer.
4080 bool isRValRef = DeclType->isRValueReferenceType();
4081 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004082 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004083 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004084 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004085 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004086 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004087 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004088
Douglas Gregorabe183d2010-04-13 16:31:36 +00004089
Sebastian Redl4680bf22010-06-30 18:13:39 +00004090 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004091 // A reference to type "cv1 T1" is initialized by an expression
4092 // of type "cv2 T2" as follows:
4093
Sebastian Redl4680bf22010-06-30 18:13:39 +00004094 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004095 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004096 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4097 // reference-compatible with "cv2 T2," or
4098 //
4099 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4100 if (InitCategory.isLValue() &&
4101 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004102 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004103 // When a parameter of reference type binds directly (8.5.3)
4104 // to an argument expression, the implicit conversion sequence
4105 // is the identity conversion, unless the argument expression
4106 // has a type that is a derived class of the parameter type,
4107 // in which case the implicit conversion sequence is a
4108 // derived-to-base Conversion (13.3.3.1).
4109 ICS.setStandard();
4110 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004111 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4112 : ObjCConversion? ICK_Compatible_Conversion
4113 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004114 ICS.Standard.Third = ICK_Identity;
4115 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4116 ICS.Standard.setToType(0, T2);
4117 ICS.Standard.setToType(1, T1);
4118 ICS.Standard.setToType(2, T1);
4119 ICS.Standard.ReferenceBinding = true;
4120 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004121 ICS.Standard.IsLvalueReference = !isRValRef;
4122 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4123 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004124 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004125 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004126 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004127
Sebastian Redl4680bf22010-06-30 18:13:39 +00004128 // Nothing more to do: the inaccessibility/ambiguity check for
4129 // derived-to-base conversions is suppressed when we're
4130 // computing the implicit conversion sequence (C++
4131 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004132 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004133 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004134
Sebastian Redl4680bf22010-06-30 18:13:39 +00004135 // -- has a class type (i.e., T2 is a class type), where T1 is
4136 // not reference-related to T2, and can be implicitly
4137 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4138 // is reference-compatible with "cv3 T3" 92) (this
4139 // conversion is selected by enumerating the applicable
4140 // conversion functions (13.3.1.6) and choosing the best
4141 // one through overload resolution (13.3)),
4142 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004143 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004144 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004145 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4146 Init, T2, /*AllowRvalues=*/false,
4147 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004148 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004149 }
4150 }
4151
Sebastian Redl4680bf22010-06-30 18:13:39 +00004152 // -- Otherwise, the reference shall be an lvalue reference to a
4153 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004154 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004155 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004156 // We actually handle one oddity of C++ [over.ics.ref] at this
4157 // point, which is that, due to p2 (which short-circuits reference
4158 // binding by only attempting a simple conversion for non-direct
4159 // bindings) and p3's strange wording, we allow a const volatile
4160 // reference to bind to an rvalue. Hence the check for the presence
4161 // of "const" rather than checking for "const" being the only
4162 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004163 // This is also the point where rvalue references and lvalue inits no longer
4164 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004165 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004166 return ICS;
4167
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004168 // -- If the initializer expression
4169 //
4170 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004171 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004172 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4173 (InitCategory.isXValue() ||
4174 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4175 (InitCategory.isLValue() && T2->isFunctionType()))) {
4176 ICS.setStandard();
4177 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004179 : ObjCConversion? ICK_Compatible_Conversion
4180 : ICK_Identity;
4181 ICS.Standard.Third = ICK_Identity;
4182 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4183 ICS.Standard.setToType(0, T2);
4184 ICS.Standard.setToType(1, T1);
4185 ICS.Standard.setToType(2, T1);
4186 ICS.Standard.ReferenceBinding = true;
4187 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4188 // binding unless we're binding to a class prvalue.
4189 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4190 // allow the use of rvalue references in C++98/03 for the benefit of
4191 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004193 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004194 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004195 ICS.Standard.IsLvalueReference = !isRValRef;
4196 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004198 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004199 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004200 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004203
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004204 // -- has a class type (i.e., T2 is a class type), where T1 is not
4205 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206 // an xvalue, class prvalue, or function lvalue of type
4207 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004208 // "cv3 T3",
4209 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004211 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004212 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004213 // class subobject).
4214 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004216 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4217 Init, T2, /*AllowRvalues=*/true,
4218 AllowExplicit)) {
4219 // In the second case, if the reference is an rvalue reference
4220 // and the second standard conversion sequence of the
4221 // user-defined conversion sequence includes an lvalue-to-rvalue
4222 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004224 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4225 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4226
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004227 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004229
Douglas Gregorabe183d2010-04-13 16:31:36 +00004230 // -- Otherwise, a temporary of type "cv1 T1" is created and
4231 // initialized from the initializer expression using the
4232 // rules for a non-reference copy initialization (8.5). The
4233 // reference is then bound to the temporary. If T1 is
4234 // reference-related to T2, cv1 must be the same
4235 // cv-qualification as, or greater cv-qualification than,
4236 // cv2; otherwise, the program is ill-formed.
4237 if (RefRelationship == Sema::Ref_Related) {
4238 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4239 // we would be reference-compatible or reference-compatible with
4240 // added qualification. But that wasn't the case, so the reference
4241 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004242 //
4243 // Note that we only want to check address spaces and cvr-qualifiers here.
4244 // ObjC GC and lifetime qualifiers aren't important.
4245 Qualifiers T1Quals = T1.getQualifiers();
4246 Qualifiers T2Quals = T2.getQualifiers();
4247 T1Quals.removeObjCGCAttr();
4248 T1Quals.removeObjCLifetime();
4249 T2Quals.removeObjCGCAttr();
4250 T2Quals.removeObjCLifetime();
4251 if (!T1Quals.compatiblyIncludes(T2Quals))
4252 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004253 }
4254
4255 // If at least one of the types is a class type, the types are not
4256 // related, and we aren't allowed any user conversions, the
4257 // reference binding fails. This case is important for breaking
4258 // recursion, since TryImplicitConversion below will attempt to
4259 // create a temporary through the use of a copy constructor.
4260 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4261 (T1->isRecordType() || T2->isRecordType()))
4262 return ICS;
4263
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004264 // If T1 is reference-related to T2 and the reference is an rvalue
4265 // reference, the initializer expression shall not be an lvalue.
4266 if (RefRelationship >= Sema::Ref_Related &&
4267 isRValRef && Init->Classify(S.Context).isLValue())
4268 return ICS;
4269
Douglas Gregorabe183d2010-04-13 16:31:36 +00004270 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004271 // When a parameter of reference type is not bound directly to
4272 // an argument expression, the conversion sequence is the one
4273 // required to convert the argument expression to the
4274 // underlying type of the reference according to
4275 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4276 // to copy-initializing a temporary of the underlying type with
4277 // the argument expression. Any difference in top-level
4278 // cv-qualification is subsumed by the initialization itself
4279 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004280 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4281 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004282 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004283 /*CStyle=*/false,
4284 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004285
4286 // Of course, that's still a reference binding.
4287 if (ICS.isStandard()) {
4288 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004289 ICS.Standard.IsLvalueReference = !isRValRef;
4290 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4291 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004292 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004293 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004294 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004295 // Don't allow rvalue references to bind to lvalues.
4296 if (DeclType->isRValueReferenceType()) {
4297 if (const ReferenceType *RefType
4298 = ICS.UserDefined.ConversionFunction->getResultType()
4299 ->getAs<LValueReferenceType>()) {
4300 if (!RefType->getPointeeType()->isFunctionType()) {
4301 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4302 DeclType);
4303 return ICS;
4304 }
4305 }
4306 }
4307
Douglas Gregorabe183d2010-04-13 16:31:36 +00004308 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004309 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4310 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4311 ICS.UserDefined.After.BindsToRvalue = true;
4312 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4313 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004314 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004315
Douglas Gregorabe183d2010-04-13 16:31:36 +00004316 return ICS;
4317}
4318
Sebastian Redl5405b812011-10-16 18:19:34 +00004319static ImplicitConversionSequence
4320TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4321 bool SuppressUserConversions,
4322 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004323 bool AllowObjCWritebackConversion,
4324 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004325
4326/// TryListConversion - Try to copy-initialize a value of type ToType from the
4327/// initializer list From.
4328static ImplicitConversionSequence
4329TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4330 bool SuppressUserConversions,
4331 bool InOverloadResolution,
4332 bool AllowObjCWritebackConversion) {
4333 // C++11 [over.ics.list]p1:
4334 // When an argument is an initializer list, it is not an expression and
4335 // special rules apply for converting it to a parameter type.
4336
4337 ImplicitConversionSequence Result;
4338 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004339 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004340
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004341 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004342 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004343 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004344 return Result;
4345
Sebastian Redl5405b812011-10-16 18:19:34 +00004346 // C++11 [over.ics.list]p2:
4347 // If the parameter type is std::initializer_list<X> or "array of X" and
4348 // all the elements can be implicitly converted to X, the implicit
4349 // conversion sequence is the worst conversion necessary to convert an
4350 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004351 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004352 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004353 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004354 X = S.Context.getBaseElementType(ToType);
4355 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004356 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004357 if (!X.isNull()) {
4358 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4359 Expr *Init = From->getInit(i);
4360 ImplicitConversionSequence ICS =
4361 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4362 InOverloadResolution,
4363 AllowObjCWritebackConversion);
4364 // If a single element isn't convertible, fail.
4365 if (ICS.isBad()) {
4366 Result = ICS;
4367 break;
4368 }
4369 // Otherwise, look for the worst conversion.
4370 if (Result.isBad() ||
4371 CompareImplicitConversionSequences(S, ICS, Result) ==
4372 ImplicitConversionSequence::Worse)
4373 Result = ICS;
4374 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004375
4376 // For an empty list, we won't have computed any conversion sequence.
4377 // Introduce the identity conversion sequence.
4378 if (From->getNumInits() == 0) {
4379 Result.setStandard();
4380 Result.Standard.setAsIdentityConversion();
4381 Result.Standard.setFromType(ToType);
4382 Result.Standard.setAllToTypes(ToType);
4383 }
4384
Sebastian Redlfe592282012-01-17 22:49:48 +00004385 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004386 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004387 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004388 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004389
4390 // C++11 [over.ics.list]p3:
4391 // Otherwise, if the parameter is a non-aggregate class X and overload
4392 // resolution chooses a single best constructor [...] the implicit
4393 // conversion sequence is a user-defined conversion sequence. If multiple
4394 // constructors are viable but none is better than the others, the
4395 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004396 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4397 // This function can deal with initializer lists.
4398 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4399 /*AllowExplicit=*/false,
4400 InOverloadResolution, /*CStyle=*/false,
4401 AllowObjCWritebackConversion);
4402 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004403 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004404 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004405
4406 // C++11 [over.ics.list]p4:
4407 // Otherwise, if the parameter has an aggregate type which can be
4408 // initialized from the initializer list [...] the implicit conversion
4409 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004410 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004411 // Type is an aggregate, argument is an init list. At this point it comes
4412 // down to checking whether the initialization works.
4413 // FIXME: Find out whether this parameter is consumed or not.
4414 InitializedEntity Entity =
4415 InitializedEntity::InitializeParameter(S.Context, ToType,
4416 /*Consumed=*/false);
4417 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4418 Result.setUserDefined();
4419 Result.UserDefined.Before.setAsIdentityConversion();
4420 // Initializer lists don't have a type.
4421 Result.UserDefined.Before.setFromType(QualType());
4422 Result.UserDefined.Before.setAllToTypes(QualType());
4423
4424 Result.UserDefined.After.setAsIdentityConversion();
4425 Result.UserDefined.After.setFromType(ToType);
4426 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004427 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004428 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004429 return Result;
4430 }
4431
4432 // C++11 [over.ics.list]p5:
4433 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004434 if (ToType->isReferenceType()) {
4435 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4436 // mention initializer lists in any way. So we go by what list-
4437 // initialization would do and try to extrapolate from that.
4438
4439 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4440
4441 // If the initializer list has a single element that is reference-related
4442 // to the parameter type, we initialize the reference from that.
4443 if (From->getNumInits() == 1) {
4444 Expr *Init = From->getInit(0);
4445
4446 QualType T2 = Init->getType();
4447
4448 // If the initializer is the address of an overloaded function, try
4449 // to resolve the overloaded function. If all goes well, T2 is the
4450 // type of the resulting function.
4451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452 DeclAccessPair Found;
4453 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4454 Init, ToType, false, Found))
4455 T2 = Fn->getType();
4456 }
4457
4458 // Compute some basic properties of the types and the initializer.
4459 bool dummy1 = false;
4460 bool dummy2 = false;
4461 bool dummy3 = false;
4462 Sema::ReferenceCompareResult RefRelationship
4463 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4464 dummy2, dummy3);
4465
4466 if (RefRelationship >= Sema::Ref_Related)
4467 return TryReferenceInit(S, Init, ToType,
4468 /*FIXME:*/From->getLocStart(),
4469 SuppressUserConversions,
4470 /*AllowExplicit=*/false);
4471 }
4472
4473 // Otherwise, we bind the reference to a temporary created from the
4474 // initializer list.
4475 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4476 InOverloadResolution,
4477 AllowObjCWritebackConversion);
4478 if (Result.isFailure())
4479 return Result;
4480 assert(!Result.isEllipsis() &&
4481 "Sub-initialization cannot result in ellipsis conversion.");
4482
4483 // Can we even bind to a temporary?
4484 if (ToType->isRValueReferenceType() ||
4485 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4486 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4487 Result.UserDefined.After;
4488 SCS.ReferenceBinding = true;
4489 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4490 SCS.BindsToRvalue = true;
4491 SCS.BindsToFunctionLvalue = false;
4492 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4493 SCS.ObjCLifetimeConversionBinding = false;
4494 } else
4495 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4496 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004497 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004498 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004499
4500 // C++11 [over.ics.list]p6:
4501 // Otherwise, if the parameter type is not a class:
4502 if (!ToType->isRecordType()) {
4503 // - if the initializer list has one element, the implicit conversion
4504 // sequence is the one required to convert the element to the
4505 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004506 unsigned NumInits = From->getNumInits();
4507 if (NumInits == 1)
4508 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4509 SuppressUserConversions,
4510 InOverloadResolution,
4511 AllowObjCWritebackConversion);
4512 // - if the initializer list has no elements, the implicit conversion
4513 // sequence is the identity conversion.
4514 else if (NumInits == 0) {
4515 Result.setStandard();
4516 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004517 Result.Standard.setFromType(ToType);
4518 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004519 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004520 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004521 return Result;
4522 }
4523
4524 // C++11 [over.ics.list]p7:
4525 // In all cases other than those enumerated above, no conversion is possible
4526 return Result;
4527}
4528
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004529/// TryCopyInitialization - Try to copy-initialize a value of type
4530/// ToType from the expression From. Return the implicit conversion
4531/// sequence required to pass this argument, which may be a bad
4532/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004533/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004534/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004535static ImplicitConversionSequence
4536TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004538 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004539 bool AllowObjCWritebackConversion,
4540 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004541 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4542 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4543 InOverloadResolution,AllowObjCWritebackConversion);
4544
Douglas Gregorabe183d2010-04-13 16:31:36 +00004545 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004546 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004547 /*FIXME:*/From->getLocStart(),
4548 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004549 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004550
John McCall120d63c2010-08-24 20:38:10 +00004551 return TryImplicitConversion(S, From, ToType,
4552 SuppressUserConversions,
4553 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004554 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004555 /*CStyle=*/false,
4556 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004557}
4558
Anna Zaksf3546ee2011-07-28 19:46:48 +00004559static bool TryCopyInitialization(const CanQualType FromQTy,
4560 const CanQualType ToQTy,
4561 Sema &S,
4562 SourceLocation Loc,
4563 ExprValueKind FromVK) {
4564 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4565 ImplicitConversionSequence ICS =
4566 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4567
4568 return !ICS.isBad();
4569}
4570
Douglas Gregor96176b32008-11-18 23:14:02 +00004571/// TryObjectArgumentInitialization - Try to initialize the object
4572/// parameter of the given member function (@c Method) from the
4573/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004574static ImplicitConversionSequence
4575TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004576 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004577 CXXMethodDecl *Method,
4578 CXXRecordDecl *ActingContext) {
4579 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004580 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4581 // const volatile object.
4582 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4583 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004584 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004585
4586 // Set up the conversion sequence as a "bad" conversion, to allow us
4587 // to exit early.
4588 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004589
4590 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004591 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004592 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004593 FromType = PT->getPointeeType();
4594
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004595 // When we had a pointer, it's implicitly dereferenced, so we
4596 // better have an lvalue.
4597 assert(FromClassification.isLValue());
4598 }
4599
Anders Carlssona552f7c2009-05-01 18:34:30 +00004600 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004601
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004602 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004603 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004604 // parameter is
4605 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004606 // - "lvalue reference to cv X" for functions declared without a
4607 // ref-qualifier or with the & ref-qualifier
4608 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004609 // ref-qualifier
4610 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004612 // cv-qualification on the member function declaration.
4613 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004614 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004615 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004616 // (C++ [over.match.funcs]p5). We perform a simplified version of
4617 // reference binding here, that allows class rvalues to bind to
4618 // non-constant references.
4619
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004620 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004621 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004623 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004624 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004625 ICS.setBad(BadConversionSequence::bad_qualifiers,
4626 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004627 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004628 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004629
4630 // Check that we have either the same type or a derived type. It
4631 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004632 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004633 ImplicitConversionKind SecondKind;
4634 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4635 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004636 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004637 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004638 else {
John McCallb1bdc622010-02-25 01:37:24 +00004639 ICS.setBad(BadConversionSequence::unrelated_class,
4640 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004641 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004642 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004643
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004644 // Check the ref-qualifier.
4645 switch (Method->getRefQualifier()) {
4646 case RQ_None:
4647 // Do nothing; we don't care about lvalueness or rvalueness.
4648 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004649
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004650 case RQ_LValue:
4651 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4652 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004654 ImplicitParamType);
4655 return ICS;
4656 }
4657 break;
4658
4659 case RQ_RValue:
4660 if (!FromClassification.isRValue()) {
4661 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004663 ImplicitParamType);
4664 return ICS;
4665 }
4666 break;
4667 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004668
Douglas Gregor96176b32008-11-18 23:14:02 +00004669 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004670 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004671 ICS.Standard.setAsIdentityConversion();
4672 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004673 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004674 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004675 ICS.Standard.ReferenceBinding = true;
4676 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004678 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004679 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4680 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4681 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004682 return ICS;
4683}
4684
4685/// PerformObjectArgumentInitialization - Perform initialization of
4686/// the implicit object parameter for the given Method with the given
4687/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004688ExprResult
4689Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004691 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004692 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004693 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004694 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004695 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004697 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004698 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004699 FromRecordType = PT->getPointeeType();
4700 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004701 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004702 } else {
4703 FromRecordType = From->getType();
4704 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004705 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004706 }
4707
John McCall701c89e2009-12-03 04:06:58 +00004708 // Note that we always use the true parent context when performing
4709 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004710 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004711 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4712 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004713 if (ICS.isBad()) {
4714 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4715 Qualifiers FromQs = FromRecordType.getQualifiers();
4716 Qualifiers ToQs = DestType.getQualifiers();
4717 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4718 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004719 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004720 diag::err_member_function_call_bad_cvr)
4721 << Method->getDeclName() << FromRecordType << (CVR - 1)
4722 << From->getSourceRange();
4723 Diag(Method->getLocation(), diag::note_previous_decl)
4724 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004725 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004726 }
4727 }
4728
Daniel Dunbar96a00142012-03-09 18:35:03 +00004729 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004730 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004731 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004732 }
Mike Stump1eb44332009-09-09 15:08:12 +00004733
John Wiegley429bb272011-04-08 18:41:53 +00004734 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4735 ExprResult FromRes =
4736 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4737 if (FromRes.isInvalid())
4738 return ExprError();
4739 From = FromRes.take();
4740 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004741
Douglas Gregor5fccd362010-03-03 23:55:11 +00004742 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004743 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004744 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004745 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004746}
4747
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004748/// TryContextuallyConvertToBool - Attempt to contextually convert the
4749/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004750static ImplicitConversionSequence
4751TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004752 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004753 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004754 // FIXME: Are these flags correct?
4755 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004756 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004757 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004758 /*CStyle=*/false,
4759 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004760}
4761
4762/// PerformContextuallyConvertToBool - Perform a contextual conversion
4763/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004764ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004765 if (checkPlaceholderForOverload(*this, From))
4766 return ExprError();
4767
John McCall120d63c2010-08-24 20:38:10 +00004768 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004769 if (!ICS.isBad())
4770 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004771
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004772 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004773 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004774 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004775 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004776 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004777}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004778
Richard Smith8ef7b202012-01-18 23:55:52 +00004779/// Check that the specified conversion is permitted in a converted constant
4780/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4781/// is acceptable.
4782static bool CheckConvertedConstantConversions(Sema &S,
4783 StandardConversionSequence &SCS) {
4784 // Since we know that the target type is an integral or unscoped enumeration
4785 // type, most conversion kinds are impossible. All possible First and Third
4786 // conversions are fine.
4787 switch (SCS.Second) {
4788 case ICK_Identity:
4789 case ICK_Integral_Promotion:
4790 case ICK_Integral_Conversion:
4791 return true;
4792
4793 case ICK_Boolean_Conversion:
4794 // Conversion from an integral or unscoped enumeration type to bool is
4795 // classified as ICK_Boolean_Conversion, but it's also an integral
4796 // conversion, so it's permitted in a converted constant expression.
4797 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4798 SCS.getToType(2)->isBooleanType();
4799
4800 case ICK_Floating_Integral:
4801 case ICK_Complex_Real:
4802 return false;
4803
4804 case ICK_Lvalue_To_Rvalue:
4805 case ICK_Array_To_Pointer:
4806 case ICK_Function_To_Pointer:
4807 case ICK_NoReturn_Adjustment:
4808 case ICK_Qualification:
4809 case ICK_Compatible_Conversion:
4810 case ICK_Vector_Conversion:
4811 case ICK_Vector_Splat:
4812 case ICK_Derived_To_Base:
4813 case ICK_Pointer_Conversion:
4814 case ICK_Pointer_Member:
4815 case ICK_Block_Pointer_Conversion:
4816 case ICK_Writeback_Conversion:
4817 case ICK_Floating_Promotion:
4818 case ICK_Complex_Promotion:
4819 case ICK_Complex_Conversion:
4820 case ICK_Floating_Conversion:
4821 case ICK_TransparentUnionConversion:
4822 llvm_unreachable("unexpected second conversion kind");
4823
4824 case ICK_Num_Conversion_Kinds:
4825 break;
4826 }
4827
4828 llvm_unreachable("unknown conversion kind");
4829}
4830
4831/// CheckConvertedConstantExpression - Check that the expression From is a
4832/// converted constant expression of type T, perform the conversion and produce
4833/// the converted expression, per C++11 [expr.const]p3.
4834ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4835 llvm::APSInt &Value,
4836 CCEKind CCE) {
4837 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4838 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4839
4840 if (checkPlaceholderForOverload(*this, From))
4841 return ExprError();
4842
4843 // C++11 [expr.const]p3 with proposed wording fixes:
4844 // A converted constant expression of type T is a core constant expression,
4845 // implicitly converted to a prvalue of type T, where the converted
4846 // expression is a literal constant expression and the implicit conversion
4847 // sequence contains only user-defined conversions, lvalue-to-rvalue
4848 // conversions, integral promotions, and integral conversions other than
4849 // narrowing conversions.
4850 ImplicitConversionSequence ICS =
4851 TryImplicitConversion(From, T,
4852 /*SuppressUserConversions=*/false,
4853 /*AllowExplicit=*/false,
4854 /*InOverloadResolution=*/false,
4855 /*CStyle=*/false,
4856 /*AllowObjcWritebackConversion=*/false);
4857 StandardConversionSequence *SCS = 0;
4858 switch (ICS.getKind()) {
4859 case ImplicitConversionSequence::StandardConversion:
4860 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004861 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004862 diag::err_typecheck_converted_constant_expression_disallowed)
4863 << From->getType() << From->getSourceRange() << T;
4864 SCS = &ICS.Standard;
4865 break;
4866 case ImplicitConversionSequence::UserDefinedConversion:
4867 // We are converting from class type to an integral or enumeration type, so
4868 // the Before sequence must be trivial.
4869 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004870 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004871 diag::err_typecheck_converted_constant_expression_disallowed)
4872 << From->getType() << From->getSourceRange() << T;
4873 SCS = &ICS.UserDefined.After;
4874 break;
4875 case ImplicitConversionSequence::AmbiguousConversion:
4876 case ImplicitConversionSequence::BadConversion:
4877 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004878 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004879 diag::err_typecheck_converted_constant_expression)
4880 << From->getType() << From->getSourceRange() << T;
4881 return ExprError();
4882
4883 case ImplicitConversionSequence::EllipsisConversion:
4884 llvm_unreachable("ellipsis conversion in converted constant expression");
4885 }
4886
4887 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4888 if (Result.isInvalid())
4889 return Result;
4890
4891 // Check for a narrowing implicit conversion.
4892 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004893 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004894 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4895 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004896 case NK_Variable_Narrowing:
4897 // Implicit conversion to a narrower type, and the value is not a constant
4898 // expression. We'll diagnose this in a moment.
4899 case NK_Not_Narrowing:
4900 break;
4901
4902 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004903 Diag(From->getLocStart(),
4904 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4905 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004906 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004907 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004908 break;
4909
4910 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004911 Diag(From->getLocStart(),
4912 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4913 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004914 << CCE << /*Constant*/0 << From->getType() << T;
4915 break;
4916 }
4917
4918 // Check the expression is a constant expression.
4919 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4920 Expr::EvalResult Eval;
4921 Eval.Diag = &Notes;
4922
4923 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4924 // The expression can't be folded, so we can't keep it at this position in
4925 // the AST.
4926 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004927 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004928 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004929
4930 if (Notes.empty()) {
4931 // It's a constant expression.
4932 return Result;
4933 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004934 }
4935
4936 // It's not a constant expression. Produce an appropriate diagnostic.
4937 if (Notes.size() == 1 &&
4938 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4939 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4940 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004941 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004942 << CCE << From->getSourceRange();
4943 for (unsigned I = 0; I < Notes.size(); ++I)
4944 Diag(Notes[I].first, Notes[I].second);
4945 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004946 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004947}
4948
John McCall0bcc9bc2011-09-09 06:11:02 +00004949/// dropPointerConversions - If the given standard conversion sequence
4950/// involves any pointer conversions, remove them. This may change
4951/// the result type of the conversion sequence.
4952static void dropPointerConversion(StandardConversionSequence &SCS) {
4953 if (SCS.Second == ICK_Pointer_Conversion) {
4954 SCS.Second = ICK_Identity;
4955 SCS.Third = ICK_Identity;
4956 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4957 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004958}
John McCall120d63c2010-08-24 20:38:10 +00004959
John McCall0bcc9bc2011-09-09 06:11:02 +00004960/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4961/// convert the expression From to an Objective-C pointer type.
4962static ImplicitConversionSequence
4963TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4964 // Do an implicit conversion to 'id'.
4965 QualType Ty = S.Context.getObjCIdType();
4966 ImplicitConversionSequence ICS
4967 = TryImplicitConversion(S, From, Ty,
4968 // FIXME: Are these flags correct?
4969 /*SuppressUserConversions=*/false,
4970 /*AllowExplicit=*/true,
4971 /*InOverloadResolution=*/false,
4972 /*CStyle=*/false,
4973 /*AllowObjCWritebackConversion=*/false);
4974
4975 // Strip off any final conversions to 'id'.
4976 switch (ICS.getKind()) {
4977 case ImplicitConversionSequence::BadConversion:
4978 case ImplicitConversionSequence::AmbiguousConversion:
4979 case ImplicitConversionSequence::EllipsisConversion:
4980 break;
4981
4982 case ImplicitConversionSequence::UserDefinedConversion:
4983 dropPointerConversion(ICS.UserDefined.After);
4984 break;
4985
4986 case ImplicitConversionSequence::StandardConversion:
4987 dropPointerConversion(ICS.Standard);
4988 break;
4989 }
4990
4991 return ICS;
4992}
4993
4994/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4995/// conversion of the expression From to an Objective-C pointer type.
4996ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004997 if (checkPlaceholderForOverload(*this, From))
4998 return ExprError();
4999
John McCallc12c5bb2010-05-15 11:32:37 +00005000 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005001 ImplicitConversionSequence ICS =
5002 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005003 if (!ICS.isBad())
5004 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005005 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005006}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005007
Richard Smithf39aec12012-02-04 07:07:42 +00005008/// Determine whether the provided type is an integral type, or an enumeration
5009/// type of a permitted flavor.
5010static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5011 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5012 : T->isIntegralOrUnscopedEnumerationType();
5013}
5014
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005016/// enumeration type.
5017///
5018/// This routine will attempt to convert an expression of class type to an
5019/// integral or enumeration type, if that class type only has a single
5020/// conversion to an integral or enumeration type.
5021///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005022/// \param Loc The source location of the construct that requires the
5023/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005024///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005025/// \param FromE The expression we're converting from.
5026///
5027/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5028/// have integral or enumeration type.
5029///
5030/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5031/// incomplete class type.
5032///
5033/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5034/// explicit conversion function (because no implicit conversion functions
5035/// were available). This is a recovery mode.
5036///
5037/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5038/// showing which conversion was picked.
5039///
5040/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5041/// conversion function that could convert to integral or enumeration type.
5042///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005043/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005044/// usable conversion function.
5045///
5046/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5047/// function, which may be an extension in this case.
5048///
Richard Smithf39aec12012-02-04 07:07:42 +00005049/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5050/// enumerations should be considered.
5051///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005052/// \returns The expression, converted to an integral or enumeration type if
5053/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005054ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005055Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005056 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005057 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005058 // We can't perform any more checking for type-dependent expressions.
5059 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005060 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005061
Eli Friedmanceccab92012-01-26 00:26:18 +00005062 // Process placeholders immediately.
5063 if (From->hasPlaceholderType()) {
5064 ExprResult result = CheckPlaceholderExpr(From);
5065 if (result.isInvalid()) return result;
5066 From = result.take();
5067 }
5068
Douglas Gregorc30614b2010-06-29 23:17:37 +00005069 // If the expression already has integral or enumeration type, we're golden.
5070 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005071 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005072 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005073
5074 // FIXME: Check for missing '()' if T is a function type?
5075
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005076 // 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 +00005077 // expression of integral or enumeration type.
5078 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005079 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005080 if (!Diagnoser.Suppress)
5081 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005082 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005084
Douglas Gregorc30614b2010-06-29 23:17:37 +00005085 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005086 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005087 ICEConvertDiagnoser &Diagnoser;
5088 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005089
Douglas Gregorab41fe92012-05-04 22:38:52 +00005090 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5091 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005092
5093 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005094 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005095 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005096 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005097
5098 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005099 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005100
Douglas Gregorc30614b2010-06-29 23:17:37 +00005101 // Look for a conversion to an integral or enumeration type.
5102 UnresolvedSet<4> ViableConversions;
5103 UnresolvedSet<4> ExplicitConversions;
5104 const UnresolvedSetImpl *Conversions
5105 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005106
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005107 bool HadMultipleCandidates = (Conversions->size() > 1);
5108
Douglas Gregorc30614b2010-06-29 23:17:37 +00005109 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005110 E = Conversions->end();
5111 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005112 ++I) {
5113 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005114 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5115 if (isIntegralOrEnumerationType(
5116 Conversion->getConversionType().getNonReferenceType(),
5117 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005118 if (Conversion->isExplicit())
5119 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5120 else
5121 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5122 }
Richard Smithf39aec12012-02-04 07:07:42 +00005123 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005125
Douglas Gregorc30614b2010-06-29 23:17:37 +00005126 switch (ViableConversions.size()) {
5127 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005128 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005129 DeclAccessPair Found = ExplicitConversions[0];
5130 CXXConversionDecl *Conversion
5131 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132
Douglas Gregorc30614b2010-06-29 23:17:37 +00005133 // The user probably meant to invoke the given explicit
5134 // conversion; use it.
5135 QualType ConvTy
5136 = Conversion->getConversionType().getNonReferenceType();
5137 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005138 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139
Douglas Gregorab41fe92012-05-04 22:38:52 +00005140 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005141 << FixItHint::CreateInsertion(From->getLocStart(),
5142 "static_cast<" + TypeStr + ">(")
5143 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5144 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005145 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005146
5147 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005148 // explicit conversion function.
5149 if (isSFINAEContext())
5150 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005151
Douglas Gregorc30614b2010-06-29 23:17:37 +00005152 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005153 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5154 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005155 if (Result.isInvalid())
5156 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005157 // Record usage of conversion in an implicit cast.
5158 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5159 CK_UserDefinedConversion,
5160 Result.get(), 0,
5161 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005162 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005163
Douglas Gregorc30614b2010-06-29 23:17:37 +00005164 // We'll complain below about a non-integral condition type.
5165 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005166
Douglas Gregorc30614b2010-06-29 23:17:37 +00005167 case 1: {
5168 // Apply this conversion.
5169 DeclAccessPair Found = ViableConversions[0];
5170 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005171
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005172 CXXConversionDecl *Conversion
5173 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5174 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005176 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005177 if (isSFINAEContext())
5178 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005179
Douglas Gregorab41fe92012-05-04 22:38:52 +00005180 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5181 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005183
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005184 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5185 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005186 if (Result.isInvalid())
5187 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005188 // Record usage of conversion in an implicit cast.
5189 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5190 CK_UserDefinedConversion,
5191 Result.get(), 0,
5192 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005193 break;
5194 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005195
Douglas Gregorc30614b2010-06-29 23:17:37 +00005196 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005197 if (Diagnoser.Suppress)
5198 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005199
Douglas Gregorab41fe92012-05-04 22:38:52 +00005200 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005201 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5202 CXXConversionDecl *Conv
5203 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5204 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005205 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005206 }
John McCall9ae2f072010-08-23 23:25:46 +00005207 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005209
Richard Smith282e7e62012-02-04 09:53:13 +00005210 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005211 !Diagnoser.Suppress) {
5212 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5213 << From->getSourceRange();
5214 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215
Eli Friedmanceccab92012-01-26 00:26:18 +00005216 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005217}
5218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005219/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005220/// candidate functions, using the given function call arguments. If
5221/// @p SuppressUserConversions, then don't allow user-defined
5222/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005223///
James Dennett699c9042012-06-15 07:13:21 +00005224/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005225/// based on an incomplete set of function arguments. This feature is used by
5226/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005227void
5228Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005229 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005230 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005231 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005232 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005233 bool PartialOverloading,
5234 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005235 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005236 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005237 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005238 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005239 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Douglas Gregor88a35142008-12-22 05:46:06 +00005241 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005242 if (!isa<CXXConstructorDecl>(Method)) {
5243 // If we get here, it's because we're calling a member function
5244 // that is named without a member access expression (e.g.,
5245 // "this->f") that was either written explicitly or created
5246 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005247 // function, e.g., X::f(). We use an empty type for the implied
5248 // object argument (C++ [over.call.func]p3), and the acting context
5249 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005250 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005251 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005252 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005253 return;
5254 }
5255 // We treat a constructor like a non-member function, since its object
5256 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005257 }
5258
Douglas Gregorfd476482009-11-13 23:59:09 +00005259 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005260 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005261
Douglas Gregor7edfb692009-11-23 12:27:39 +00005262 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005263 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005264
Douglas Gregor66724ea2009-11-14 01:20:54 +00005265 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5266 // C++ [class.copy]p3:
5267 // A member function template is never instantiated to perform the copy
5268 // of a class object to an object of its class type.
5269 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005270 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005271 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005272 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5273 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005274 return;
5275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005276
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005277 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005278 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005279 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005280 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005281 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005282 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005283 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005284 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005285
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005286 unsigned NumArgsInProto = Proto->getNumArgs();
5287
5288 // (C++ 13.3.2p2): A candidate function having fewer than m
5289 // parameters is viable only if it has an ellipsis in its parameter
5290 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005291 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005292 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005293 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005294 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005295 return;
5296 }
5297
5298 // (C++ 13.3.2p2): A candidate function having more than m parameters
5299 // is viable only if the (m+1)st parameter has a default argument
5300 // (8.3.6). For the purposes of overload resolution, the
5301 // parameter list is truncated on the right, so that there are
5302 // exactly m parameters.
5303 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005304 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005305 // Not enough arguments.
5306 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005307 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005308 return;
5309 }
5310
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005311 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005312 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005313 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5314 if (CheckCUDATarget(Caller, Function)) {
5315 Candidate.Viable = false;
5316 Candidate.FailureKind = ovl_fail_bad_target;
5317 return;
5318 }
5319
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005320 // Determine the implicit conversion sequences for each of the
5321 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005322 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005323 if (ArgIdx < NumArgsInProto) {
5324 // (C++ 13.3.2p3): for F to be a viable function, there shall
5325 // exist for each argument an implicit conversion sequence
5326 // (13.3.3.1) that converts that argument to the corresponding
5327 // parameter of F.
5328 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005329 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005330 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005331 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005332 /*InOverloadResolution=*/true,
5333 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005334 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005335 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005336 if (Candidate.Conversions[ArgIdx].isBad()) {
5337 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005338 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005339 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005340 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005341 } else {
5342 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5343 // argument for which there is no corresponding parameter is
5344 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005345 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005346 }
5347 }
5348}
5349
Douglas Gregor063daf62009-03-13 18:40:31 +00005350/// \brief Add all of the function declarations in the given function set to
5351/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005352void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005353 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005354 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005355 bool SuppressUserConversions,
5356 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005357 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005358 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005360 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005361 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005362 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005363 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005364 Args.slice(1), CandidateSet,
5365 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005366 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005367 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005368 SuppressUserConversions);
5369 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005370 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005371 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5372 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005373 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005374 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005375 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005376 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005377 Args[0]->Classify(Context), Args.slice(1),
5378 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005379 else
John McCall9aa472c2010-03-19 07:35:19 +00005380 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005381 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005382 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005383 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005384 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005385}
5386
John McCall314be4e2009-11-17 07:50:12 +00005387/// AddMethodCandidate - Adds a named decl (which is some kind of
5388/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005389void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005390 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005391 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005392 Expr **Args, unsigned NumArgs,
5393 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005394 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005395 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005396 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005397
5398 if (isa<UsingShadowDecl>(Decl))
5399 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005400
John McCall314be4e2009-11-17 07:50:12 +00005401 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5402 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5403 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005404 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5405 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005406 ObjectType, ObjectClassification,
5407 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005408 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005409 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005410 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005411 ObjectType, ObjectClassification,
5412 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005413 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005414 }
5415}
5416
Douglas Gregor96176b32008-11-18 23:14:02 +00005417/// AddMethodCandidate - Adds the given C++ member function to the set
5418/// of candidate functions, using the given function call arguments
5419/// and the object argument (@c Object). For example, in a call
5420/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5421/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5422/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005423/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005424void
John McCall9aa472c2010-03-19 07:35:19 +00005425Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005426 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005427 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005428 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005429 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005430 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005431 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005432 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005433 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005434 assert(!isa<CXXConstructorDecl>(Method) &&
5435 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005436
Douglas Gregor3f396022009-09-28 04:47:19 +00005437 if (!CandidateSet.isNewCandidate(Method))
5438 return;
5439
Douglas Gregor7edfb692009-11-23 12:27:39 +00005440 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005441 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005442
Douglas Gregor96176b32008-11-18 23:14:02 +00005443 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005444 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005445 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005446 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005447 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005448 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005449 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005450
5451 unsigned NumArgsInProto = Proto->getNumArgs();
5452
5453 // (C++ 13.3.2p2): A candidate function having fewer than m
5454 // parameters is viable only if it has an ellipsis in its parameter
5455 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005456 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005457 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005458 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005459 return;
5460 }
5461
5462 // (C++ 13.3.2p2): A candidate function having more than m parameters
5463 // is viable only if the (m+1)st parameter has a default argument
5464 // (8.3.6). For the purposes of overload resolution, the
5465 // parameter list is truncated on the right, so that there are
5466 // exactly m parameters.
5467 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005468 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005469 // Not enough arguments.
5470 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005471 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005472 return;
5473 }
5474
5475 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005476
John McCall701c89e2009-12-03 04:06:58 +00005477 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005478 // The implicit object argument is ignored.
5479 Candidate.IgnoreObjectArgument = true;
5480 else {
5481 // Determine the implicit conversion sequence for the object
5482 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005483 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005484 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5485 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005486 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005487 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005488 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005489 return;
5490 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005491 }
5492
5493 // Determine the implicit conversion sequences for each of the
5494 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005496 if (ArgIdx < NumArgsInProto) {
5497 // (C++ 13.3.2p3): for F to be a viable function, there shall
5498 // exist for each argument an implicit conversion sequence
5499 // (13.3.3.1) that converts that argument to the corresponding
5500 // parameter of F.
5501 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005502 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005503 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005504 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005505 /*InOverloadResolution=*/true,
5506 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005507 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005508 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005509 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005510 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005511 break;
5512 }
5513 } else {
5514 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5515 // argument for which there is no corresponding parameter is
5516 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005517 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005518 }
5519 }
5520}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005521
Douglas Gregor6b906862009-08-21 00:16:32 +00005522/// \brief Add a C++ member function template as a candidate to the candidate
5523/// set, using template argument deduction to produce an appropriate member
5524/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005525void
Douglas Gregor6b906862009-08-21 00:16:32 +00005526Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005527 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005528 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005529 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005530 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005531 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005532 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005533 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005534 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005535 if (!CandidateSet.isNewCandidate(MethodTmpl))
5536 return;
5537
Douglas Gregor6b906862009-08-21 00:16:32 +00005538 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005539 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005540 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005541 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005542 // candidate functions in the usual way.113) A given name can refer to one
5543 // or more function templates and also to a set of overloaded non-template
5544 // functions. In such a case, the candidate functions generated from each
5545 // function template are combined with the set of non-template candidate
5546 // functions.
John McCall5769d612010-02-08 23:07:23 +00005547 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005548 FunctionDecl *Specialization = 0;
5549 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005550 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5551 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005552 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005553 Candidate.FoundDecl = FoundDecl;
5554 Candidate.Function = MethodTmpl->getTemplatedDecl();
5555 Candidate.Viable = false;
5556 Candidate.FailureKind = ovl_fail_bad_deduction;
5557 Candidate.IsSurrogate = false;
5558 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005559 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005560 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005561 Info);
5562 return;
5563 }
Mike Stump1eb44332009-09-09 15:08:12 +00005564
Douglas Gregor6b906862009-08-21 00:16:32 +00005565 // Add the function template specialization produced by template argument
5566 // deduction as a candidate.
5567 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005568 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005569 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005570 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005571 ActingContext, ObjectType, ObjectClassification, Args,
5572 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005573}
5574
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005575/// \brief Add a C++ function template specialization as a candidate
5576/// in the candidate set, using template argument deduction to produce
5577/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005578void
Douglas Gregore53060f2009-06-25 22:08:12 +00005579Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005580 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005581 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005582 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005583 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005584 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005585 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5586 return;
5587
Douglas Gregore53060f2009-06-25 22:08:12 +00005588 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005589 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005590 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005591 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005592 // candidate functions in the usual way.113) A given name can refer to one
5593 // or more function templates and also to a set of overloaded non-template
5594 // functions. In such a case, the candidate functions generated from each
5595 // function template are combined with the set of non-template candidate
5596 // functions.
John McCall5769d612010-02-08 23:07:23 +00005597 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005598 FunctionDecl *Specialization = 0;
5599 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005600 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5601 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005602 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005603 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005604 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5605 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005606 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005607 Candidate.IsSurrogate = false;
5608 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005609 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005610 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005611 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005612 return;
5613 }
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Douglas Gregore53060f2009-06-25 22:08:12 +00005615 // Add the function template specialization produced by template argument
5616 // deduction as a candidate.
5617 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005618 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005619 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005620}
Mike Stump1eb44332009-09-09 15:08:12 +00005621
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005622/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005623/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005624/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005625/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005626/// (which may or may not be the same type as the type that the
5627/// conversion function produces).
5628void
5629Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005630 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005631 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005632 Expr *From, QualType ToType,
5633 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005634 assert(!Conversion->getDescribedFunctionTemplate() &&
5635 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005636 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005637 if (!CandidateSet.isNewCandidate(Conversion))
5638 return;
5639
Douglas Gregor7edfb692009-11-23 12:27:39 +00005640 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005641 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005642
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005643 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005644 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005645 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005646 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005647 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005648 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005649 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005650 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005651 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005652 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005653 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005654
Douglas Gregorbca39322010-08-19 15:37:02 +00005655 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005656 // For conversion functions, the function is considered to be a member of
5657 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005658 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005659 //
5660 // Determine the implicit conversion sequence for the implicit
5661 // object parameter.
5662 QualType ImplicitParamType = From->getType();
5663 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5664 ImplicitParamType = FromPtrType->getPointeeType();
5665 CXXRecordDecl *ConversionContext
5666 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005668 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005669 = TryObjectArgumentInitialization(*this, From->getType(),
5670 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005671 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005672
John McCall1d318332010-01-12 00:44:57 +00005673 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005674 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005675 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005676 return;
5677 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005678
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005679 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005680 // derived to base as such conversions are given Conversion Rank. They only
5681 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5682 QualType FromCanon
5683 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5684 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5685 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5686 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005687 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005688 return;
5689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005690
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005691 // To determine what the conversion from the result of calling the
5692 // conversion function to the type we're eventually trying to
5693 // convert to (ToType), we need to synthesize a call to the
5694 // conversion function and attempt copy initialization from it. This
5695 // makes sure that we get the right semantics with respect to
5696 // lvalues/rvalues and the type. Fortunately, we can allocate this
5697 // call on the stack and we don't need its arguments to be
5698 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005699 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005700 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005701 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5702 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005703 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005704 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Richard Smith87c1f1f2011-07-13 22:53:21 +00005706 QualType ConversionType = Conversion->getConversionType();
5707 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005708 Candidate.Viable = false;
5709 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5710 return;
5711 }
5712
Richard Smith87c1f1f2011-07-13 22:53:21 +00005713 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005714
Mike Stump1eb44332009-09-09 15:08:12 +00005715 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005716 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5717 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005718 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005719 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005720 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005721 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005722 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005723 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005724 /*InOverloadResolution=*/false,
5725 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005726
John McCall1d318332010-01-12 00:44:57 +00005727 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005728 case ImplicitConversionSequence::StandardConversion:
5729 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005730
Douglas Gregorc520c842010-04-12 23:42:09 +00005731 // C++ [over.ics.user]p3:
5732 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005734 // shall have exact match rank.
5735 if (Conversion->getPrimaryTemplate() &&
5736 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5737 Candidate.Viable = false;
5738 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005741 // C++0x [dcl.init.ref]p5:
5742 // In the second case, if the reference is an rvalue reference and
5743 // the second standard conversion sequence of the user-defined
5744 // conversion sequence includes an lvalue-to-rvalue conversion, the
5745 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005747 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5748 Candidate.Viable = false;
5749 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5750 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005751 break;
5752
5753 case ImplicitConversionSequence::BadConversion:
5754 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005755 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005756 break;
5757
5758 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005759 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005760 "Can only end up with a standard conversion sequence or failure");
5761 }
5762}
5763
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005764/// \brief Adds a conversion function template specialization
5765/// candidate to the overload set, using template argument deduction
5766/// to deduce the template arguments of the conversion function
5767/// template from the type that we are converting to (C++
5768/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005769void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005770Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005771 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005772 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005773 Expr *From, QualType ToType,
5774 OverloadCandidateSet &CandidateSet) {
5775 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5776 "Only conversion function templates permitted here");
5777
Douglas Gregor3f396022009-09-28 04:47:19 +00005778 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5779 return;
5780
John McCall5769d612010-02-08 23:07:23 +00005781 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005782 CXXConversionDecl *Specialization = 0;
5783 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005784 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005785 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005786 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005787 Candidate.FoundDecl = FoundDecl;
5788 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5789 Candidate.Viable = false;
5790 Candidate.FailureKind = ovl_fail_bad_deduction;
5791 Candidate.IsSurrogate = false;
5792 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005793 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005794 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005795 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005796 return;
5797 }
Mike Stump1eb44332009-09-09 15:08:12 +00005798
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005799 // Add the conversion function template specialization produced by
5800 // template argument deduction as a candidate.
5801 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005802 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005803 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005804}
5805
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005806/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5807/// converts the given @c Object to a function pointer via the
5808/// conversion function @c Conversion, and then attempts to call it
5809/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5810/// the type of function that we'll eventually be calling.
5811void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005812 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005813 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005814 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005815 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005816 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005817 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005818 if (!CandidateSet.isNewCandidate(Conversion))
5819 return;
5820
Douglas Gregor7edfb692009-11-23 12:27:39 +00005821 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005822 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005823
Ahmed Charles13a140c2012-02-25 11:00:22 +00005824 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005825 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005826 Candidate.Function = 0;
5827 Candidate.Surrogate = Conversion;
5828 Candidate.Viable = true;
5829 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005830 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005831 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005832
5833 // Determine the implicit conversion sequence for the implicit
5834 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005835 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005836 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005837 Object->Classify(Context),
5838 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005839 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005840 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005841 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005842 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005843 return;
5844 }
5845
5846 // The first conversion is actually a user-defined conversion whose
5847 // first conversion is ObjectInit's standard conversion (which is
5848 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005849 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005850 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005851 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005852 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005853 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005854 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005855 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005856 = Candidate.Conversions[0].UserDefined.Before;
5857 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5858
Mike Stump1eb44332009-09-09 15:08:12 +00005859 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005860 unsigned NumArgsInProto = Proto->getNumArgs();
5861
5862 // (C++ 13.3.2p2): A candidate function having fewer than m
5863 // parameters is viable only if it has an ellipsis in its parameter
5864 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005865 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005866 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005867 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005868 return;
5869 }
5870
5871 // Function types don't have any default arguments, so just check if
5872 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005873 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 // Not enough arguments.
5875 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005876 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005877 return;
5878 }
5879
5880 // Determine the implicit conversion sequences for each of the
5881 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005882 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005883 if (ArgIdx < NumArgsInProto) {
5884 // (C++ 13.3.2p3): for F to be a viable function, there shall
5885 // exist for each argument an implicit conversion sequence
5886 // (13.3.3.1) that converts that argument to the corresponding
5887 // parameter of F.
5888 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005889 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005890 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005891 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005892 /*InOverloadResolution=*/false,
5893 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005894 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005895 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005896 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005897 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005898 break;
5899 }
5900 } else {
5901 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5902 // argument for which there is no corresponding parameter is
5903 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005904 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005905 }
5906 }
5907}
5908
Douglas Gregor063daf62009-03-13 18:40:31 +00005909/// \brief Add overload candidates for overloaded operators that are
5910/// member functions.
5911///
5912/// Add the overloaded operator candidates that are member functions
5913/// for the operator Op that was used in an operator expression such
5914/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5915/// CandidateSet will store the added overload candidates. (C++
5916/// [over.match.oper]).
5917void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5918 SourceLocation OpLoc,
5919 Expr **Args, unsigned NumArgs,
5920 OverloadCandidateSet& CandidateSet,
5921 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005922 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5923
5924 // C++ [over.match.oper]p3:
5925 // For a unary operator @ with an operand of a type whose
5926 // cv-unqualified version is T1, and for a binary operator @ with
5927 // a left operand of a type whose cv-unqualified version is T1 and
5928 // a right operand of a type whose cv-unqualified version is T2,
5929 // three sets of candidate functions, designated member
5930 // candidates, non-member candidates and built-in candidates, are
5931 // constructed as follows:
5932 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005933
5934 // -- If T1 is a class type, the set of member candidates is the
5935 // result of the qualified lookup of T1::operator@
5936 // (13.3.1.1.1); otherwise, the set of member candidates is
5937 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005938 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005939 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005940 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005941 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005942
John McCalla24dc2e2009-11-17 02:14:36 +00005943 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5944 LookupQualifiedName(Operators, T1Rec->getDecl());
5945 Operators.suppressDiagnostics();
5946
Mike Stump1eb44332009-09-09 15:08:12 +00005947 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005948 OperEnd = Operators.end();
5949 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005950 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005951 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005953 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005954 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005955 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005956}
5957
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005958/// AddBuiltinCandidate - Add a candidate for a built-in
5959/// operator. ResultTy and ParamTys are the result and parameter types
5960/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005961/// arguments being passed to the candidate. IsAssignmentOperator
5962/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005963/// operator. NumContextualBoolArguments is the number of arguments
5964/// (at the beginning of the argument list) that will be contextually
5965/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005966void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005967 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005968 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005969 bool IsAssignmentOperator,
5970 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005971 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005972 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005973
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005974 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005975 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005976 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005977 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005978 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005979 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005980 Candidate.BuiltinTypes.ResultTy = ResultTy;
5981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5982 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5983
5984 // Determine the implicit conversion sequences for each of the
5985 // arguments.
5986 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005987 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005988 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005989 // C++ [over.match.oper]p4:
5990 // For the built-in assignment operators, conversions of the
5991 // left operand are restricted as follows:
5992 // -- no temporaries are introduced to hold the left operand, and
5993 // -- no user-defined conversions are applied to the left
5994 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005995 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005996 //
5997 // We block these conversions by turning off user-defined
5998 // conversions, since that is the only way that initialization of
5999 // a reference to a non-class type can occur from something that
6000 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006001 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006002 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006003 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006004 Candidate.Conversions[ArgIdx]
6005 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006006 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006007 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006008 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006009 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006010 /*InOverloadResolution=*/false,
6011 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006012 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006013 }
John McCall1d318332010-01-12 00:44:57 +00006014 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006015 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006016 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006017 break;
6018 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006019 }
6020}
6021
6022/// BuiltinCandidateTypeSet - A set of types that will be used for the
6023/// candidate operator functions for built-in operators (C++
6024/// [over.built]). The types are separated into pointer types and
6025/// enumeration types.
6026class BuiltinCandidateTypeSet {
6027 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006028 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006029
6030 /// PointerTypes - The set of pointer types that will be used in the
6031 /// built-in candidates.
6032 TypeSet PointerTypes;
6033
Sebastian Redl78eb8742009-04-19 21:53:20 +00006034 /// MemberPointerTypes - The set of member pointer types that will be
6035 /// used in the built-in candidates.
6036 TypeSet MemberPointerTypes;
6037
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006038 /// EnumerationTypes - The set of enumeration types that will be
6039 /// used in the built-in candidates.
6040 TypeSet EnumerationTypes;
6041
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006042 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006043 /// candidates.
6044 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006045
6046 /// \brief A flag indicating non-record types are viable candidates
6047 bool HasNonRecordTypes;
6048
6049 /// \brief A flag indicating whether either arithmetic or enumeration types
6050 /// were present in the candidate set.
6051 bool HasArithmeticOrEnumeralTypes;
6052
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006053 /// \brief A flag indicating whether the nullptr type was present in the
6054 /// candidate set.
6055 bool HasNullPtrType;
6056
Douglas Gregor5842ba92009-08-24 15:23:48 +00006057 /// Sema - The semantic analysis instance where we are building the
6058 /// candidate type set.
6059 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006060
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 /// Context - The AST context in which we will build the type sets.
6062 ASTContext &Context;
6063
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006064 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6065 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006066 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006067
6068public:
6069 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006070 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006071
Mike Stump1eb44332009-09-09 15:08:12 +00006072 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006073 : HasNonRecordTypes(false),
6074 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006075 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006076 SemaRef(SemaRef),
6077 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006078
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006079 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006080 SourceLocation Loc,
6081 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006082 bool AllowExplicitConversions,
6083 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006084
6085 /// pointer_begin - First pointer type found;
6086 iterator pointer_begin() { return PointerTypes.begin(); }
6087
Sebastian Redl78eb8742009-04-19 21:53:20 +00006088 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006089 iterator pointer_end() { return PointerTypes.end(); }
6090
Sebastian Redl78eb8742009-04-19 21:53:20 +00006091 /// member_pointer_begin - First member pointer type found;
6092 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6093
6094 /// member_pointer_end - Past the last member pointer type found;
6095 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6096
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006097 /// enumeration_begin - First enumeration type found;
6098 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6099
Sebastian Redl78eb8742009-04-19 21:53:20 +00006100 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006101 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006102
Douglas Gregor26bcf672010-05-19 03:21:00 +00006103 iterator vector_begin() { return VectorTypes.begin(); }
6104 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006105
6106 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6107 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006108 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006109};
6110
Sebastian Redl78eb8742009-04-19 21:53:20 +00006111/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006112/// the set of pointer types along with any more-qualified variants of
6113/// that type. For example, if @p Ty is "int const *", this routine
6114/// will add "int const *", "int const volatile *", "int const
6115/// restrict *", and "int const volatile restrict *" to the set of
6116/// pointer types. Returns true if the add of @p Ty itself succeeded,
6117/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006118///
6119/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006120bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006121BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6122 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006123
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006124 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006125 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006126 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006127
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006128 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006129 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006130 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006131 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006132 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6133 PointeeTy = PTy->getPointeeType();
6134 buildObjCPtr = true;
6135 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006136 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006137 }
6138
Sebastian Redla9efada2009-11-18 20:39:26 +00006139 // Don't add qualified variants of arrays. For one, they're not allowed
6140 // (the qualifier would sink to the element type), and for another, the
6141 // only overload situation where it matters is subscript or pointer +- int,
6142 // and those shouldn't have qualifier variants anyway.
6143 if (PointeeTy->isArrayType())
6144 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006145
John McCall0953e762009-09-24 19:53:00 +00006146 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006147 bool hasVolatile = VisibleQuals.hasVolatile();
6148 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006149
John McCall0953e762009-09-24 19:53:00 +00006150 // Iterate through all strict supersets of BaseCVR.
6151 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6152 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006153 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006154 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006155
6156 // Skip over restrict if no restrict found anywhere in the types, or if
6157 // the type cannot be restrict-qualified.
6158 if ((CVR & Qualifiers::Restrict) &&
6159 (!hasRestrict ||
6160 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6161 continue;
6162
6163 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006164 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006165
6166 // Build qualified pointer type.
6167 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006168 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006169 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006170 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006171 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6172
6173 // Insert qualified pointer type.
6174 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006175 }
6176
6177 return true;
6178}
6179
Sebastian Redl78eb8742009-04-19 21:53:20 +00006180/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6181/// to the set of pointer types along with any more-qualified variants of
6182/// that type. For example, if @p Ty is "int const *", this routine
6183/// will add "int const *", "int const volatile *", "int const
6184/// restrict *", and "int const volatile restrict *" to the set of
6185/// pointer types. Returns true if the add of @p Ty itself succeeded,
6186/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006187///
6188/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006189bool
6190BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6191 QualType Ty) {
6192 // Insert this type.
6193 if (!MemberPointerTypes.insert(Ty))
6194 return false;
6195
John McCall0953e762009-09-24 19:53:00 +00006196 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6197 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006198
John McCall0953e762009-09-24 19:53:00 +00006199 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006200 // Don't add qualified variants of arrays. For one, they're not allowed
6201 // (the qualifier would sink to the element type), and for another, the
6202 // only overload situation where it matters is subscript or pointer +- int,
6203 // and those shouldn't have qualifier variants anyway.
6204 if (PointeeTy->isArrayType())
6205 return true;
John McCall0953e762009-09-24 19:53:00 +00006206 const Type *ClassTy = PointerTy->getClass();
6207
6208 // Iterate through all strict supersets of the pointee type's CVR
6209 // qualifiers.
6210 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6211 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6212 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006213
John McCall0953e762009-09-24 19:53:00 +00006214 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006215 MemberPointerTypes.insert(
6216 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006217 }
6218
6219 return true;
6220}
6221
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006222/// AddTypesConvertedFrom - Add each of the types to which the type @p
6223/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006224/// primarily interested in pointer types and enumeration types. We also
6225/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006226/// AllowUserConversions is true if we should look at the conversion
6227/// functions of a class type, and AllowExplicitConversions if we
6228/// should also include the explicit conversion functions of a class
6229/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006230void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006231BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006232 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006233 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006234 bool AllowExplicitConversions,
6235 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006236 // Only deal with canonical types.
6237 Ty = Context.getCanonicalType(Ty);
6238
6239 // Look through reference types; they aren't part of the type of an
6240 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006241 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006242 Ty = RefTy->getPointeeType();
6243
John McCall3b657512011-01-19 10:06:00 +00006244 // If we're dealing with an array type, decay to the pointer.
6245 if (Ty->isArrayType())
6246 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6247
6248 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006249 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006250
Chandler Carruth6a577462010-12-13 01:44:01 +00006251 // Flag if we ever add a non-record type.
6252 const RecordType *TyRec = Ty->getAs<RecordType>();
6253 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6254
Chandler Carruth6a577462010-12-13 01:44:01 +00006255 // Flag if we encounter an arithmetic type.
6256 HasArithmeticOrEnumeralTypes =
6257 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6258
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006259 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6260 PointerTypes.insert(Ty);
6261 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006262 // Insert our type, and its more-qualified variants, into the set
6263 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006264 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006265 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006266 } else if (Ty->isMemberPointerType()) {
6267 // Member pointers are far easier, since the pointee can't be converted.
6268 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6269 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006270 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006271 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006272 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006273 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006274 // We treat vector types as arithmetic types in many contexts as an
6275 // extension.
6276 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006277 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006278 } else if (Ty->isNullPtrType()) {
6279 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006280 } else if (AllowUserConversions && TyRec) {
6281 // No conversion functions in incomplete types.
6282 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6283 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006284
Chandler Carruth6a577462010-12-13 01:44:01 +00006285 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6286 const UnresolvedSetImpl *Conversions
6287 = ClassDecl->getVisibleConversionFunctions();
6288 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6289 E = Conversions->end(); I != E; ++I) {
6290 NamedDecl *D = I.getDecl();
6291 if (isa<UsingShadowDecl>(D))
6292 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006293
Chandler Carruth6a577462010-12-13 01:44:01 +00006294 // Skip conversion function templates; they don't tell us anything
6295 // about which builtin types we can convert to.
6296 if (isa<FunctionTemplateDecl>(D))
6297 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006298
Chandler Carruth6a577462010-12-13 01:44:01 +00006299 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6300 if (AllowExplicitConversions || !Conv->isExplicit()) {
6301 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6302 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006303 }
6304 }
6305 }
6306}
6307
Douglas Gregor19b7b152009-08-24 13:43:27 +00006308/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6309/// the volatile- and non-volatile-qualified assignment operators for the
6310/// given type to the candidate set.
6311static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6312 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006313 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006314 unsigned NumArgs,
6315 OverloadCandidateSet &CandidateSet) {
6316 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006317
Douglas Gregor19b7b152009-08-24 13:43:27 +00006318 // T& operator=(T&, T)
6319 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6320 ParamTypes[1] = T;
6321 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6322 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006323
Douglas Gregor19b7b152009-08-24 13:43:27 +00006324 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6325 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006326 ParamTypes[0]
6327 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006328 ParamTypes[1] = T;
6329 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006330 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006331 }
6332}
Mike Stump1eb44332009-09-09 15:08:12 +00006333
Sebastian Redl9994a342009-10-25 17:03:50 +00006334/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6335/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006336static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6337 Qualifiers VRQuals;
6338 const RecordType *TyRec;
6339 if (const MemberPointerType *RHSMPType =
6340 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006341 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006342 else
6343 TyRec = ArgExpr->getType()->getAs<RecordType>();
6344 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006345 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006346 VRQuals.addVolatile();
6347 VRQuals.addRestrict();
6348 return VRQuals;
6349 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006350
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006351 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006352 if (!ClassDecl->hasDefinition())
6353 return VRQuals;
6354
John McCalleec51cf2010-01-20 00:46:10 +00006355 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006356 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006357
John McCalleec51cf2010-01-20 00:46:10 +00006358 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006359 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006360 NamedDecl *D = I.getDecl();
6361 if (isa<UsingShadowDecl>(D))
6362 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6363 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006364 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6365 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6366 CanTy = ResTypeRef->getPointeeType();
6367 // Need to go down the pointer/mempointer chain and add qualifiers
6368 // as see them.
6369 bool done = false;
6370 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006371 if (CanTy.isRestrictQualified())
6372 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006373 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6374 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006375 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006376 CanTy->getAs<MemberPointerType>())
6377 CanTy = ResTypeMPtr->getPointeeType();
6378 else
6379 done = true;
6380 if (CanTy.isVolatileQualified())
6381 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006382 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6383 return VRQuals;
6384 }
6385 }
6386 }
6387 return VRQuals;
6388}
John McCall00071ec2010-11-13 05:51:15 +00006389
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006390namespace {
John McCall00071ec2010-11-13 05:51:15 +00006391
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006392/// \brief Helper class to manage the addition of builtin operator overload
6393/// candidates. It provides shared state and utility methods used throughout
6394/// the process, as well as a helper method to add each group of builtin
6395/// operator overloads from the standard to a candidate set.
6396class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006397 // Common instance state available to all overload candidate addition methods.
6398 Sema &S;
6399 Expr **Args;
6400 unsigned NumArgs;
6401 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006402 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006403 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006404 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006405
Chandler Carruth6d695582010-12-12 10:35:00 +00006406 // Define some constants used to index and iterate over the arithemetic types
6407 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006408 // The "promoted arithmetic types" are the arithmetic
6409 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006410 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006411 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006412 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006413 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006414 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006415 LastPromotedArithmeticType = 11;
6416 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006417
Chandler Carruth6d695582010-12-12 10:35:00 +00006418 /// \brief Get the canonical type for a given arithmetic type index.
6419 CanQualType getArithmeticType(unsigned index) {
6420 assert(index < NumArithmeticTypes);
6421 static CanQualType ASTContext::* const
6422 ArithmeticTypes[NumArithmeticTypes] = {
6423 // Start of promoted types.
6424 &ASTContext::FloatTy,
6425 &ASTContext::DoubleTy,
6426 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006427
Chandler Carruth6d695582010-12-12 10:35:00 +00006428 // Start of integral types.
6429 &ASTContext::IntTy,
6430 &ASTContext::LongTy,
6431 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006432 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006433 &ASTContext::UnsignedIntTy,
6434 &ASTContext::UnsignedLongTy,
6435 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006436 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006437 // End of promoted types.
6438
6439 &ASTContext::BoolTy,
6440 &ASTContext::CharTy,
6441 &ASTContext::WCharTy,
6442 &ASTContext::Char16Ty,
6443 &ASTContext::Char32Ty,
6444 &ASTContext::SignedCharTy,
6445 &ASTContext::ShortTy,
6446 &ASTContext::UnsignedCharTy,
6447 &ASTContext::UnsignedShortTy,
6448 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006449 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006450 };
6451 return S.Context.*ArithmeticTypes[index];
6452 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006453
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006454 /// \brief Gets the canonical type resulting from the usual arithemetic
6455 /// converions for the given arithmetic types.
6456 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6457 // Accelerator table for performing the usual arithmetic conversions.
6458 // The rules are basically:
6459 // - if either is floating-point, use the wider floating-point
6460 // - if same signedness, use the higher rank
6461 // - if same size, use unsigned of the higher rank
6462 // - use the larger type
6463 // These rules, together with the axiom that higher ranks are
6464 // never smaller, are sufficient to precompute all of these results
6465 // *except* when dealing with signed types of higher rank.
6466 // (we could precompute SLL x UI for all known platforms, but it's
6467 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006468 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006469 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006470 Dep=-1,
6471 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006472 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006473 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006474 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006475/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6476/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6477/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6478/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6479/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6480/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6481/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6482/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6483/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6484/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6485/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006486 };
6487
6488 assert(L < LastPromotedArithmeticType);
6489 assert(R < LastPromotedArithmeticType);
6490 int Idx = ConversionsTable[L][R];
6491
6492 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006493 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006494
6495 // Slow path: we need to compare widths.
6496 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006497 CanQualType LT = getArithmeticType(L),
6498 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006499 unsigned LW = S.Context.getIntWidth(LT),
6500 RW = S.Context.getIntWidth(RT);
6501
6502 // If they're different widths, use the signed type.
6503 if (LW > RW) return LT;
6504 else if (LW < RW) return RT;
6505
6506 // Otherwise, use the unsigned type of the signed type's rank.
6507 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6508 assert(L == SLL || R == SLL);
6509 return S.Context.UnsignedLongLongTy;
6510 }
6511
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006512 /// \brief Helper method to factor out the common pattern of adding overloads
6513 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006514 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006515 bool HasVolatile,
6516 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006517 QualType ParamTypes[2] = {
6518 S.Context.getLValueReferenceType(CandidateTy),
6519 S.Context.IntTy
6520 };
6521
6522 // Non-volatile version.
6523 if (NumArgs == 1)
6524 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6525 else
6526 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6527
6528 // Use a heuristic to reduce number of builtin candidates in the set:
6529 // add volatile version only if there are conversions to a volatile type.
6530 if (HasVolatile) {
6531 ParamTypes[0] =
6532 S.Context.getLValueReferenceType(
6533 S.Context.getVolatileType(CandidateTy));
6534 if (NumArgs == 1)
6535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6536 else
6537 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6538 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006539
6540 // Add restrict version only if there are conversions to a restrict type
6541 // and our candidate type is a non-restrict-qualified pointer.
6542 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6543 !CandidateTy.isRestrictQualified()) {
6544 ParamTypes[0]
6545 = S.Context.getLValueReferenceType(
6546 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6547 if (NumArgs == 1)
6548 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6549 else
6550 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6551
6552 if (HasVolatile) {
6553 ParamTypes[0]
6554 = S.Context.getLValueReferenceType(
6555 S.Context.getCVRQualifiedType(CandidateTy,
6556 (Qualifiers::Volatile |
6557 Qualifiers::Restrict)));
6558 if (NumArgs == 1)
6559 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6560 CandidateSet);
6561 else
6562 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6563 }
6564 }
6565
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006566 }
6567
6568public:
6569 BuiltinOperatorOverloadBuilder(
6570 Sema &S, Expr **Args, unsigned NumArgs,
6571 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006572 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006573 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006574 OverloadCandidateSet &CandidateSet)
6575 : S(S), Args(Args), NumArgs(NumArgs),
6576 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006577 HasArithmeticOrEnumeralCandidateType(
6578 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006579 CandidateTypes(CandidateTypes),
6580 CandidateSet(CandidateSet) {
6581 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006582 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006583 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006584 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006585 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006586 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006587 assert(getArithmeticType(FirstPromotedArithmeticType)
6588 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006589 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006590 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006591 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006592 "Invalid last promoted arithmetic type");
6593 }
6594
6595 // C++ [over.built]p3:
6596 //
6597 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6598 // is either volatile or empty, there exist candidate operator
6599 // functions of the form
6600 //
6601 // VQ T& operator++(VQ T&);
6602 // T operator++(VQ T&, int);
6603 //
6604 // C++ [over.built]p4:
6605 //
6606 // For every pair (T, VQ), where T is an arithmetic type other
6607 // than bool, and VQ is either volatile or empty, there exist
6608 // candidate operator functions of the form
6609 //
6610 // VQ T& operator--(VQ T&);
6611 // T operator--(VQ T&, int);
6612 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006613 if (!HasArithmeticOrEnumeralCandidateType)
6614 return;
6615
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006616 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6617 Arith < NumArithmeticTypes; ++Arith) {
6618 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006619 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006620 VisibleTypeConversionsQuals.hasVolatile(),
6621 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006622 }
6623 }
6624
6625 // C++ [over.built]p5:
6626 //
6627 // For every pair (T, VQ), where T is a cv-qualified or
6628 // cv-unqualified object type, and VQ is either volatile or
6629 // empty, there exist candidate operator functions of the form
6630 //
6631 // T*VQ& operator++(T*VQ&);
6632 // T*VQ& operator--(T*VQ&);
6633 // T* operator++(T*VQ&, int);
6634 // T* operator--(T*VQ&, int);
6635 void addPlusPlusMinusMinusPointerOverloads() {
6636 for (BuiltinCandidateTypeSet::iterator
6637 Ptr = CandidateTypes[0].pointer_begin(),
6638 PtrEnd = CandidateTypes[0].pointer_end();
6639 Ptr != PtrEnd; ++Ptr) {
6640 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006641 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006642 continue;
6643
6644 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006645 (!(*Ptr).isVolatileQualified() &&
6646 VisibleTypeConversionsQuals.hasVolatile()),
6647 (!(*Ptr).isRestrictQualified() &&
6648 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006649 }
6650 }
6651
6652 // C++ [over.built]p6:
6653 // For every cv-qualified or cv-unqualified object type T, there
6654 // exist candidate operator functions of the form
6655 //
6656 // T& operator*(T*);
6657 //
6658 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006659 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006660 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006661 // T& operator*(T*);
6662 void addUnaryStarPointerOverloads() {
6663 for (BuiltinCandidateTypeSet::iterator
6664 Ptr = CandidateTypes[0].pointer_begin(),
6665 PtrEnd = CandidateTypes[0].pointer_end();
6666 Ptr != PtrEnd; ++Ptr) {
6667 QualType ParamTy = *Ptr;
6668 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006669 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6670 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006671
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006672 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6673 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6674 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006675
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006676 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6677 &ParamTy, Args, 1, CandidateSet);
6678 }
6679 }
6680
6681 // C++ [over.built]p9:
6682 // For every promoted arithmetic type T, there exist candidate
6683 // operator functions of the form
6684 //
6685 // T operator+(T);
6686 // T operator-(T);
6687 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006688 if (!HasArithmeticOrEnumeralCandidateType)
6689 return;
6690
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006691 for (unsigned Arith = FirstPromotedArithmeticType;
6692 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006693 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006694 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6695 }
6696
6697 // Extension: We also add these operators for vector types.
6698 for (BuiltinCandidateTypeSet::iterator
6699 Vec = CandidateTypes[0].vector_begin(),
6700 VecEnd = CandidateTypes[0].vector_end();
6701 Vec != VecEnd; ++Vec) {
6702 QualType VecTy = *Vec;
6703 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6704 }
6705 }
6706
6707 // C++ [over.built]p8:
6708 // For every type T, there exist candidate operator functions of
6709 // the form
6710 //
6711 // T* operator+(T*);
6712 void addUnaryPlusPointerOverloads() {
6713 for (BuiltinCandidateTypeSet::iterator
6714 Ptr = CandidateTypes[0].pointer_begin(),
6715 PtrEnd = CandidateTypes[0].pointer_end();
6716 Ptr != PtrEnd; ++Ptr) {
6717 QualType ParamTy = *Ptr;
6718 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6719 }
6720 }
6721
6722 // C++ [over.built]p10:
6723 // For every promoted integral type T, there exist candidate
6724 // operator functions of the form
6725 //
6726 // T operator~(T);
6727 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006728 if (!HasArithmeticOrEnumeralCandidateType)
6729 return;
6730
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006731 for (unsigned Int = FirstPromotedIntegralType;
6732 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006733 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006734 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6735 }
6736
6737 // Extension: We also add this operator for vector types.
6738 for (BuiltinCandidateTypeSet::iterator
6739 Vec = CandidateTypes[0].vector_begin(),
6740 VecEnd = CandidateTypes[0].vector_end();
6741 Vec != VecEnd; ++Vec) {
6742 QualType VecTy = *Vec;
6743 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6744 }
6745 }
6746
6747 // C++ [over.match.oper]p16:
6748 // For every pointer to member type T, there exist candidate operator
6749 // functions of the form
6750 //
6751 // bool operator==(T,T);
6752 // bool operator!=(T,T);
6753 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6754 /// Set of (canonical) types that we've already handled.
6755 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6756
6757 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6758 for (BuiltinCandidateTypeSet::iterator
6759 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6760 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6761 MemPtr != MemPtrEnd;
6762 ++MemPtr) {
6763 // Don't add the same builtin candidate twice.
6764 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6765 continue;
6766
6767 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6768 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6769 CandidateSet);
6770 }
6771 }
6772 }
6773
6774 // C++ [over.built]p15:
6775 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006776 // For every T, where T is an enumeration type, a pointer type, or
6777 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006778 //
6779 // bool operator<(T, T);
6780 // bool operator>(T, T);
6781 // bool operator<=(T, T);
6782 // bool operator>=(T, T);
6783 // bool operator==(T, T);
6784 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006785 void addRelationalPointerOrEnumeralOverloads() {
6786 // C++ [over.built]p1:
6787 // If there is a user-written candidate with the same name and parameter
6788 // types as a built-in candidate operator function, the built-in operator
6789 // function is hidden and is not included in the set of candidate
6790 // functions.
6791 //
6792 // The text is actually in a note, but if we don't implement it then we end
6793 // up with ambiguities when the user provides an overloaded operator for
6794 // an enumeration type. Note that only enumeration types have this problem,
6795 // so we track which enumeration types we've seen operators for. Also, the
6796 // only other overloaded operator with enumeration argumenst, operator=,
6797 // cannot be overloaded for enumeration types, so this is the only place
6798 // where we must suppress candidates like this.
6799 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6800 UserDefinedBinaryOperators;
6801
6802 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6803 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6804 CandidateTypes[ArgIdx].enumeration_end()) {
6805 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6806 CEnd = CandidateSet.end();
6807 C != CEnd; ++C) {
6808 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6809 continue;
6810
6811 QualType FirstParamType =
6812 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6813 QualType SecondParamType =
6814 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6815
6816 // Skip if either parameter isn't of enumeral type.
6817 if (!FirstParamType->isEnumeralType() ||
6818 !SecondParamType->isEnumeralType())
6819 continue;
6820
6821 // Add this operator to the set of known user-defined operators.
6822 UserDefinedBinaryOperators.insert(
6823 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6824 S.Context.getCanonicalType(SecondParamType)));
6825 }
6826 }
6827 }
6828
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006829 /// Set of (canonical) types that we've already handled.
6830 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6831
6832 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6833 for (BuiltinCandidateTypeSet::iterator
6834 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6835 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6836 Ptr != PtrEnd; ++Ptr) {
6837 // Don't add the same builtin candidate twice.
6838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6839 continue;
6840
6841 QualType ParamTypes[2] = { *Ptr, *Ptr };
6842 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6843 CandidateSet);
6844 }
6845 for (BuiltinCandidateTypeSet::iterator
6846 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6847 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6848 Enum != EnumEnd; ++Enum) {
6849 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6850
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006851 // Don't add the same builtin candidate twice, or if a user defined
6852 // candidate exists.
6853 if (!AddedTypes.insert(CanonType) ||
6854 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6855 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006856 continue;
6857
6858 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006859 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6860 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006861 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006862
6863 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6864 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6865 if (AddedTypes.insert(NullPtrTy) &&
6866 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6867 NullPtrTy))) {
6868 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6869 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6870 CandidateSet);
6871 }
6872 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006873 }
6874 }
6875
6876 // C++ [over.built]p13:
6877 //
6878 // For every cv-qualified or cv-unqualified object type T
6879 // there exist candidate operator functions of the form
6880 //
6881 // T* operator+(T*, ptrdiff_t);
6882 // T& operator[](T*, ptrdiff_t); [BELOW]
6883 // T* operator-(T*, ptrdiff_t);
6884 // T* operator+(ptrdiff_t, T*);
6885 // T& operator[](ptrdiff_t, T*); [BELOW]
6886 //
6887 // C++ [over.built]p14:
6888 //
6889 // For every T, where T is a pointer to object type, there
6890 // exist candidate operator functions of the form
6891 //
6892 // ptrdiff_t operator-(T, T);
6893 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6894 /// Set of (canonical) types that we've already handled.
6895 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6896
6897 for (int Arg = 0; Arg < 2; ++Arg) {
6898 QualType AsymetricParamTypes[2] = {
6899 S.Context.getPointerDiffType(),
6900 S.Context.getPointerDiffType(),
6901 };
6902 for (BuiltinCandidateTypeSet::iterator
6903 Ptr = CandidateTypes[Arg].pointer_begin(),
6904 PtrEnd = CandidateTypes[Arg].pointer_end();
6905 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006906 QualType PointeeTy = (*Ptr)->getPointeeType();
6907 if (!PointeeTy->isObjectType())
6908 continue;
6909
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006910 AsymetricParamTypes[Arg] = *Ptr;
6911 if (Arg == 0 || Op == OO_Plus) {
6912 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6913 // T* operator+(ptrdiff_t, T*);
6914 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6915 CandidateSet);
6916 }
6917 if (Op == OO_Minus) {
6918 // ptrdiff_t operator-(T, T);
6919 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6920 continue;
6921
6922 QualType ParamTypes[2] = { *Ptr, *Ptr };
6923 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6924 Args, 2, CandidateSet);
6925 }
6926 }
6927 }
6928 }
6929
6930 // C++ [over.built]p12:
6931 //
6932 // For every pair of promoted arithmetic types L and R, there
6933 // exist candidate operator functions of the form
6934 //
6935 // LR operator*(L, R);
6936 // LR operator/(L, R);
6937 // LR operator+(L, R);
6938 // LR operator-(L, R);
6939 // bool operator<(L, R);
6940 // bool operator>(L, R);
6941 // bool operator<=(L, R);
6942 // bool operator>=(L, R);
6943 // bool operator==(L, R);
6944 // bool operator!=(L, R);
6945 //
6946 // where LR is the result of the usual arithmetic conversions
6947 // between types L and R.
6948 //
6949 // C++ [over.built]p24:
6950 //
6951 // For every pair of promoted arithmetic types L and R, there exist
6952 // candidate operator functions of the form
6953 //
6954 // LR operator?(bool, L, R);
6955 //
6956 // where LR is the result of the usual arithmetic conversions
6957 // between types L and R.
6958 // Our candidates ignore the first parameter.
6959 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006960 if (!HasArithmeticOrEnumeralCandidateType)
6961 return;
6962
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006963 for (unsigned Left = FirstPromotedArithmeticType;
6964 Left < LastPromotedArithmeticType; ++Left) {
6965 for (unsigned Right = FirstPromotedArithmeticType;
6966 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006967 QualType LandR[2] = { getArithmeticType(Left),
6968 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006969 QualType Result =
6970 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006971 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006972 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6973 }
6974 }
6975
6976 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6977 // conditional operator for vector types.
6978 for (BuiltinCandidateTypeSet::iterator
6979 Vec1 = CandidateTypes[0].vector_begin(),
6980 Vec1End = CandidateTypes[0].vector_end();
6981 Vec1 != Vec1End; ++Vec1) {
6982 for (BuiltinCandidateTypeSet::iterator
6983 Vec2 = CandidateTypes[1].vector_begin(),
6984 Vec2End = CandidateTypes[1].vector_end();
6985 Vec2 != Vec2End; ++Vec2) {
6986 QualType LandR[2] = { *Vec1, *Vec2 };
6987 QualType Result = S.Context.BoolTy;
6988 if (!isComparison) {
6989 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6990 Result = *Vec1;
6991 else
6992 Result = *Vec2;
6993 }
6994
6995 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6996 }
6997 }
6998 }
6999
7000 // C++ [over.built]p17:
7001 //
7002 // For every pair of promoted integral types L and R, there
7003 // exist candidate operator functions of the form
7004 //
7005 // LR operator%(L, R);
7006 // LR operator&(L, R);
7007 // LR operator^(L, R);
7008 // LR operator|(L, R);
7009 // L operator<<(L, R);
7010 // L operator>>(L, R);
7011 //
7012 // where LR is the result of the usual arithmetic conversions
7013 // between types L and R.
7014 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007015 if (!HasArithmeticOrEnumeralCandidateType)
7016 return;
7017
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007018 for (unsigned Left = FirstPromotedIntegralType;
7019 Left < LastPromotedIntegralType; ++Left) {
7020 for (unsigned Right = FirstPromotedIntegralType;
7021 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007022 QualType LandR[2] = { getArithmeticType(Left),
7023 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007024 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7025 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007026 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007027 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7028 }
7029 }
7030 }
7031
7032 // C++ [over.built]p20:
7033 //
7034 // For every pair (T, VQ), where T is an enumeration or
7035 // pointer to member type and VQ is either volatile or
7036 // empty, there exist candidate operator functions of the form
7037 //
7038 // VQ T& operator=(VQ T&, T);
7039 void addAssignmentMemberPointerOrEnumeralOverloads() {
7040 /// Set of (canonical) types that we've already handled.
7041 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7042
7043 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7044 for (BuiltinCandidateTypeSet::iterator
7045 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7046 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7047 Enum != EnumEnd; ++Enum) {
7048 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7049 continue;
7050
7051 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7052 CandidateSet);
7053 }
7054
7055 for (BuiltinCandidateTypeSet::iterator
7056 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7057 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7058 MemPtr != MemPtrEnd; ++MemPtr) {
7059 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7060 continue;
7061
7062 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7063 CandidateSet);
7064 }
7065 }
7066 }
7067
7068 // C++ [over.built]p19:
7069 //
7070 // For every pair (T, VQ), where T is any type and VQ is either
7071 // volatile or empty, there exist candidate operator functions
7072 // of the form
7073 //
7074 // T*VQ& operator=(T*VQ&, T*);
7075 //
7076 // C++ [over.built]p21:
7077 //
7078 // For every pair (T, VQ), where T is a cv-qualified or
7079 // cv-unqualified object type and VQ is either volatile or
7080 // empty, there exist candidate operator functions of the form
7081 //
7082 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7083 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7084 void addAssignmentPointerOverloads(bool isEqualOp) {
7085 /// Set of (canonical) types that we've already handled.
7086 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7087
7088 for (BuiltinCandidateTypeSet::iterator
7089 Ptr = CandidateTypes[0].pointer_begin(),
7090 PtrEnd = CandidateTypes[0].pointer_end();
7091 Ptr != PtrEnd; ++Ptr) {
7092 // If this is operator=, keep track of the builtin candidates we added.
7093 if (isEqualOp)
7094 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007095 else if (!(*Ptr)->getPointeeType()->isObjectType())
7096 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007097
7098 // non-volatile version
7099 QualType ParamTypes[2] = {
7100 S.Context.getLValueReferenceType(*Ptr),
7101 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7102 };
7103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7104 /*IsAssigmentOperator=*/ isEqualOp);
7105
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007106 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7107 VisibleTypeConversionsQuals.hasVolatile();
7108 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007109 // volatile version
7110 ParamTypes[0] =
7111 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7113 /*IsAssigmentOperator=*/isEqualOp);
7114 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007115
7116 if (!(*Ptr).isRestrictQualified() &&
7117 VisibleTypeConversionsQuals.hasRestrict()) {
7118 // restrict version
7119 ParamTypes[0]
7120 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7122 /*IsAssigmentOperator=*/isEqualOp);
7123
7124 if (NeedVolatile) {
7125 // volatile restrict version
7126 ParamTypes[0]
7127 = S.Context.getLValueReferenceType(
7128 S.Context.getCVRQualifiedType(*Ptr,
7129 (Qualifiers::Volatile |
7130 Qualifiers::Restrict)));
7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7132 CandidateSet,
7133 /*IsAssigmentOperator=*/isEqualOp);
7134 }
7135 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007136 }
7137
7138 if (isEqualOp) {
7139 for (BuiltinCandidateTypeSet::iterator
7140 Ptr = CandidateTypes[1].pointer_begin(),
7141 PtrEnd = CandidateTypes[1].pointer_end();
7142 Ptr != PtrEnd; ++Ptr) {
7143 // Make sure we don't add the same candidate twice.
7144 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7145 continue;
7146
Chandler Carruth6df868e2010-12-12 08:17:55 +00007147 QualType ParamTypes[2] = {
7148 S.Context.getLValueReferenceType(*Ptr),
7149 *Ptr,
7150 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007151
7152 // non-volatile version
7153 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7154 /*IsAssigmentOperator=*/true);
7155
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007156 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7157 VisibleTypeConversionsQuals.hasVolatile();
7158 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007159 // volatile version
7160 ParamTypes[0] =
7161 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7163 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007164 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007165
7166 if (!(*Ptr).isRestrictQualified() &&
7167 VisibleTypeConversionsQuals.hasRestrict()) {
7168 // restrict version
7169 ParamTypes[0]
7170 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7172 CandidateSet, /*IsAssigmentOperator=*/true);
7173
7174 if (NeedVolatile) {
7175 // volatile restrict version
7176 ParamTypes[0]
7177 = S.Context.getLValueReferenceType(
7178 S.Context.getCVRQualifiedType(*Ptr,
7179 (Qualifiers::Volatile |
7180 Qualifiers::Restrict)));
7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7182 CandidateSet, /*IsAssigmentOperator=*/true);
7183
7184 }
7185 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007186 }
7187 }
7188 }
7189
7190 // C++ [over.built]p18:
7191 //
7192 // For every triple (L, VQ, R), where L is an arithmetic type,
7193 // VQ is either volatile or empty, and R is a promoted
7194 // arithmetic type, there exist candidate operator functions of
7195 // the form
7196 //
7197 // VQ L& operator=(VQ L&, R);
7198 // VQ L& operator*=(VQ L&, R);
7199 // VQ L& operator/=(VQ L&, R);
7200 // VQ L& operator+=(VQ L&, R);
7201 // VQ L& operator-=(VQ L&, R);
7202 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007203 if (!HasArithmeticOrEnumeralCandidateType)
7204 return;
7205
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007206 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7207 for (unsigned Right = FirstPromotedArithmeticType;
7208 Right < LastPromotedArithmeticType; ++Right) {
7209 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007210 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007211
7212 // Add this built-in operator as a candidate (VQ is empty).
7213 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007214 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007215 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7216 /*IsAssigmentOperator=*/isEqualOp);
7217
7218 // Add this built-in operator as a candidate (VQ is 'volatile').
7219 if (VisibleTypeConversionsQuals.hasVolatile()) {
7220 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007221 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007222 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007223 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7224 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 /*IsAssigmentOperator=*/isEqualOp);
7226 }
7227 }
7228 }
7229
7230 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7231 for (BuiltinCandidateTypeSet::iterator
7232 Vec1 = CandidateTypes[0].vector_begin(),
7233 Vec1End = CandidateTypes[0].vector_end();
7234 Vec1 != Vec1End; ++Vec1) {
7235 for (BuiltinCandidateTypeSet::iterator
7236 Vec2 = CandidateTypes[1].vector_begin(),
7237 Vec2End = CandidateTypes[1].vector_end();
7238 Vec2 != Vec2End; ++Vec2) {
7239 QualType ParamTypes[2];
7240 ParamTypes[1] = *Vec2;
7241 // Add this built-in operator as a candidate (VQ is empty).
7242 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7243 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7244 /*IsAssigmentOperator=*/isEqualOp);
7245
7246 // Add this built-in operator as a candidate (VQ is 'volatile').
7247 if (VisibleTypeConversionsQuals.hasVolatile()) {
7248 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7249 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007250 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7251 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007252 /*IsAssigmentOperator=*/isEqualOp);
7253 }
7254 }
7255 }
7256 }
7257
7258 // C++ [over.built]p22:
7259 //
7260 // For every triple (L, VQ, R), where L is an integral type, VQ
7261 // is either volatile or empty, and R is a promoted integral
7262 // type, there exist candidate operator functions of the form
7263 //
7264 // VQ L& operator%=(VQ L&, R);
7265 // VQ L& operator<<=(VQ L&, R);
7266 // VQ L& operator>>=(VQ L&, R);
7267 // VQ L& operator&=(VQ L&, R);
7268 // VQ L& operator^=(VQ L&, R);
7269 // VQ L& operator|=(VQ L&, R);
7270 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007271 if (!HasArithmeticOrEnumeralCandidateType)
7272 return;
7273
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007274 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7275 for (unsigned Right = FirstPromotedIntegralType;
7276 Right < LastPromotedIntegralType; ++Right) {
7277 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007278 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007279
7280 // Add this built-in operator as a candidate (VQ is empty).
7281 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007282 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7284 if (VisibleTypeConversionsQuals.hasVolatile()) {
7285 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007286 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007287 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7288 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7290 CandidateSet);
7291 }
7292 }
7293 }
7294 }
7295
7296 // C++ [over.operator]p23:
7297 //
7298 // There also exist candidate operator functions of the form
7299 //
7300 // bool operator!(bool);
7301 // bool operator&&(bool, bool);
7302 // bool operator||(bool, bool);
7303 void addExclaimOverload() {
7304 QualType ParamTy = S.Context.BoolTy;
7305 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7306 /*IsAssignmentOperator=*/false,
7307 /*NumContextualBoolArguments=*/1);
7308 }
7309 void addAmpAmpOrPipePipeOverload() {
7310 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7311 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7312 /*IsAssignmentOperator=*/false,
7313 /*NumContextualBoolArguments=*/2);
7314 }
7315
7316 // C++ [over.built]p13:
7317 //
7318 // For every cv-qualified or cv-unqualified object type T there
7319 // exist candidate operator functions of the form
7320 //
7321 // T* operator+(T*, ptrdiff_t); [ABOVE]
7322 // T& operator[](T*, ptrdiff_t);
7323 // T* operator-(T*, ptrdiff_t); [ABOVE]
7324 // T* operator+(ptrdiff_t, T*); [ABOVE]
7325 // T& operator[](ptrdiff_t, T*);
7326 void addSubscriptOverloads() {
7327 for (BuiltinCandidateTypeSet::iterator
7328 Ptr = CandidateTypes[0].pointer_begin(),
7329 PtrEnd = CandidateTypes[0].pointer_end();
7330 Ptr != PtrEnd; ++Ptr) {
7331 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7332 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007333 if (!PointeeType->isObjectType())
7334 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007335
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007336 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7337
7338 // T& operator[](T*, ptrdiff_t)
7339 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7340 }
7341
7342 for (BuiltinCandidateTypeSet::iterator
7343 Ptr = CandidateTypes[1].pointer_begin(),
7344 PtrEnd = CandidateTypes[1].pointer_end();
7345 Ptr != PtrEnd; ++Ptr) {
7346 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7347 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007348 if (!PointeeType->isObjectType())
7349 continue;
7350
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007351 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7352
7353 // T& operator[](ptrdiff_t, T*)
7354 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7355 }
7356 }
7357
7358 // C++ [over.built]p11:
7359 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7360 // C1 is the same type as C2 or is a derived class of C2, T is an object
7361 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7362 // there exist candidate operator functions of the form
7363 //
7364 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7365 //
7366 // where CV12 is the union of CV1 and CV2.
7367 void addArrowStarOverloads() {
7368 for (BuiltinCandidateTypeSet::iterator
7369 Ptr = CandidateTypes[0].pointer_begin(),
7370 PtrEnd = CandidateTypes[0].pointer_end();
7371 Ptr != PtrEnd; ++Ptr) {
7372 QualType C1Ty = (*Ptr);
7373 QualType C1;
7374 QualifierCollector Q1;
7375 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7376 if (!isa<RecordType>(C1))
7377 continue;
7378 // heuristic to reduce number of builtin candidates in the set.
7379 // Add volatile/restrict version only if there are conversions to a
7380 // volatile/restrict type.
7381 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7382 continue;
7383 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7384 continue;
7385 for (BuiltinCandidateTypeSet::iterator
7386 MemPtr = CandidateTypes[1].member_pointer_begin(),
7387 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7388 MemPtr != MemPtrEnd; ++MemPtr) {
7389 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7390 QualType C2 = QualType(mptr->getClass(), 0);
7391 C2 = C2.getUnqualifiedType();
7392 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7393 break;
7394 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7395 // build CV12 T&
7396 QualType T = mptr->getPointeeType();
7397 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7398 T.isVolatileQualified())
7399 continue;
7400 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7401 T.isRestrictQualified())
7402 continue;
7403 T = Q1.apply(S.Context, T);
7404 QualType ResultTy = S.Context.getLValueReferenceType(T);
7405 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7406 }
7407 }
7408 }
7409
7410 // Note that we don't consider the first argument, since it has been
7411 // contextually converted to bool long ago. The candidates below are
7412 // therefore added as binary.
7413 //
7414 // C++ [over.built]p25:
7415 // For every type T, where T is a pointer, pointer-to-member, or scoped
7416 // enumeration type, there exist candidate operator functions of the form
7417 //
7418 // T operator?(bool, T, T);
7419 //
7420 void addConditionalOperatorOverloads() {
7421 /// Set of (canonical) types that we've already handled.
7422 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7423
7424 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7425 for (BuiltinCandidateTypeSet::iterator
7426 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7427 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7428 Ptr != PtrEnd; ++Ptr) {
7429 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7430 continue;
7431
7432 QualType ParamTypes[2] = { *Ptr, *Ptr };
7433 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7434 }
7435
7436 for (BuiltinCandidateTypeSet::iterator
7437 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7438 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7439 MemPtr != MemPtrEnd; ++MemPtr) {
7440 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7441 continue;
7442
7443 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7444 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7445 }
7446
David Blaikie4e4d0842012-03-11 07:00:24 +00007447 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007448 for (BuiltinCandidateTypeSet::iterator
7449 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7450 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7451 Enum != EnumEnd; ++Enum) {
7452 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7453 continue;
7454
7455 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7456 continue;
7457
7458 QualType ParamTypes[2] = { *Enum, *Enum };
7459 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7460 }
7461 }
7462 }
7463 }
7464};
7465
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007466} // end anonymous namespace
7467
7468/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7469/// operator overloads to the candidate set (C++ [over.built]), based
7470/// on the operator @p Op and the arguments given. For example, if the
7471/// operator is a binary '+', this routine might add "int
7472/// operator+(int, int)" to cover integer addition.
7473void
7474Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7475 SourceLocation OpLoc,
7476 Expr **Args, unsigned NumArgs,
7477 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007478 // Find all of the types that the arguments can convert to, but only
7479 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007480 // that make use of these types. Also record whether we encounter non-record
7481 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007482 Qualifiers VisibleTypeConversionsQuals;
7483 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007484 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7485 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007486
7487 bool HasNonRecordCandidateType = false;
7488 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007489 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007490 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7491 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7492 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7493 OpLoc,
7494 true,
7495 (Op == OO_Exclaim ||
7496 Op == OO_AmpAmp ||
7497 Op == OO_PipePipe),
7498 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007499 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7500 CandidateTypes[ArgIdx].hasNonRecordTypes();
7501 HasArithmeticOrEnumeralCandidateType =
7502 HasArithmeticOrEnumeralCandidateType ||
7503 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007504 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007505
Chandler Carruth6a577462010-12-13 01:44:01 +00007506 // Exit early when no non-record types have been added to the candidate set
7507 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007508 //
7509 // We can't exit early for !, ||, or &&, since there we have always have
7510 // 'bool' overloads.
7511 if (!HasNonRecordCandidateType &&
7512 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007513 return;
7514
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007515 // Setup an object to manage the common state for building overloads.
7516 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7517 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007518 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007519 CandidateTypes, CandidateSet);
7520
7521 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007522 switch (Op) {
7523 case OO_None:
7524 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007525 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007526
Chandler Carruthabb71842010-12-12 08:51:33 +00007527 case OO_New:
7528 case OO_Delete:
7529 case OO_Array_New:
7530 case OO_Array_Delete:
7531 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007532 llvm_unreachable(
7533 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007534
7535 case OO_Comma:
7536 case OO_Arrow:
7537 // C++ [over.match.oper]p3:
7538 // -- For the operator ',', the unary operator '&', or the
7539 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007540 break;
7541
7542 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007543 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007544 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007545 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007546
7547 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007548 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007549 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007550 } else {
7551 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7552 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7553 }
Douglas Gregor74253732008-11-19 15:42:04 +00007554 break;
7555
Chandler Carruthabb71842010-12-12 08:51:33 +00007556 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007557 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007558 OpBuilder.addUnaryStarPointerOverloads();
7559 else
7560 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7561 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562
Chandler Carruthabb71842010-12-12 08:51:33 +00007563 case OO_Slash:
7564 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007565 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007566
7567 case OO_PlusPlus:
7568 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007569 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7570 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007571 break;
7572
Douglas Gregor19b7b152009-08-24 13:43:27 +00007573 case OO_EqualEqual:
7574 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007575 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007576 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007577
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007578 case OO_Less:
7579 case OO_Greater:
7580 case OO_LessEqual:
7581 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007582 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007583 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7584 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007585
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007586 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007587 case OO_Caret:
7588 case OO_Pipe:
7589 case OO_LessLess:
7590 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007591 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007592 break;
7593
Chandler Carruthabb71842010-12-12 08:51:33 +00007594 case OO_Amp: // '&' is either unary or binary
7595 if (NumArgs == 1)
7596 // C++ [over.match.oper]p3:
7597 // -- For the operator ',', the unary operator '&', or the
7598 // operator '->', the built-in candidates set is empty.
7599 break;
7600
7601 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7602 break;
7603
7604 case OO_Tilde:
7605 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7606 break;
7607
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007608 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007609 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007610 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007611
7612 case OO_PlusEqual:
7613 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007614 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007615 // Fall through.
7616
7617 case OO_StarEqual:
7618 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007619 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007620 break;
7621
7622 case OO_PercentEqual:
7623 case OO_LessLessEqual:
7624 case OO_GreaterGreaterEqual:
7625 case OO_AmpEqual:
7626 case OO_CaretEqual:
7627 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007628 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629 break;
7630
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007631 case OO_Exclaim:
7632 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007633 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007634
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007635 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007636 case OO_PipePipe:
7637 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007638 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007639
7640 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007642 break;
7643
7644 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007645 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007646 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007647
7648 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007649 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007650 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7651 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007652 }
7653}
7654
Douglas Gregorfa047642009-02-04 00:32:51 +00007655/// \brief Add function candidates found via argument-dependent lookup
7656/// to the set of overloading candidates.
7657///
7658/// This routine performs argument-dependent name lookup based on the
7659/// given function name (which may also be an operator name) and adds
7660/// all of the overload candidates found by ADL to the overload
7661/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007662void
Douglas Gregorfa047642009-02-04 00:32:51 +00007663Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007664 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007665 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007666 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007667 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007668 bool PartialOverloading,
7669 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007670 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007671
John McCalla113e722010-01-26 06:04:06 +00007672 // FIXME: This approach for uniquing ADL results (and removing
7673 // redundant candidates from the set) relies on pointer-equality,
7674 // which means we need to key off the canonical decl. However,
7675 // always going back to the canonical decl might not get us the
7676 // right set of default arguments. What default arguments are
7677 // we supposed to consider on ADL candidates, anyway?
7678
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007679 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007680 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007681 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007682
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007683 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007684 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7685 CandEnd = CandidateSet.end();
7686 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007687 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007688 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007689 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007690 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007691 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007692
7693 // For each of the ADL candidates we found, add it to the overload
7694 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007695 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007696 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007697 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007698 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007699 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007700
Ahmed Charles13a140c2012-02-25 11:00:22 +00007701 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7702 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007703 } else
John McCall6e266892010-01-26 03:27:55 +00007704 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007705 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007706 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007707 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007708}
7709
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007710/// isBetterOverloadCandidate - Determines whether the first overload
7711/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007712bool
John McCall120d63c2010-08-24 20:38:10 +00007713isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007714 const OverloadCandidate &Cand1,
7715 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007716 SourceLocation Loc,
7717 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007718 // Define viable functions to be better candidates than non-viable
7719 // functions.
7720 if (!Cand2.Viable)
7721 return Cand1.Viable;
7722 else if (!Cand1.Viable)
7723 return false;
7724
Douglas Gregor88a35142008-12-22 05:46:06 +00007725 // C++ [over.match.best]p1:
7726 //
7727 // -- if F is a static member function, ICS1(F) is defined such
7728 // that ICS1(F) is neither better nor worse than ICS1(G) for
7729 // any function G, and, symmetrically, ICS1(G) is neither
7730 // better nor worse than ICS1(F).
7731 unsigned StartArg = 0;
7732 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7733 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007734
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007735 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007736 // A viable function F1 is defined to be a better function than another
7737 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007738 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007739 unsigned NumArgs = Cand1.NumConversions;
7740 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007741 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007742 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007743 switch (CompareImplicitConversionSequences(S,
7744 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007745 Cand2.Conversions[ArgIdx])) {
7746 case ImplicitConversionSequence::Better:
7747 // Cand1 has a better conversion sequence.
7748 HasBetterConversion = true;
7749 break;
7750
7751 case ImplicitConversionSequence::Worse:
7752 // Cand1 can't be better than Cand2.
7753 return false;
7754
7755 case ImplicitConversionSequence::Indistinguishable:
7756 // Do nothing.
7757 break;
7758 }
7759 }
7760
Mike Stump1eb44332009-09-09 15:08:12 +00007761 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007762 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007763 if (HasBetterConversion)
7764 return true;
7765
Mike Stump1eb44332009-09-09 15:08:12 +00007766 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007767 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007768 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007769 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7770 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007771
7772 // -- F1 and F2 are function template specializations, and the function
7773 // template for F1 is more specialized than the template for F2
7774 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007775 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007776 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007777 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007778 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007779 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7780 Cand2.Function->getPrimaryTemplate(),
7781 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007782 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007783 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007784 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007785 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007787
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007788 // -- the context is an initialization by user-defined conversion
7789 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7790 // from the return type of F1 to the destination type (i.e.,
7791 // the type of the entity being initialized) is a better
7792 // conversion sequence than the standard conversion sequence
7793 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007794 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007795 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007796 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007797 // First check whether we prefer one of the conversion functions over the
7798 // other. This only distinguishes the results in non-standard, extension
7799 // cases such as the conversion from a lambda closure type to a function
7800 // pointer or block.
7801 ImplicitConversionSequence::CompareKind FuncResult
7802 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7803 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7804 return FuncResult;
7805
John McCall120d63c2010-08-24 20:38:10 +00007806 switch (CompareStandardConversionSequences(S,
7807 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007808 Cand2.FinalConversion)) {
7809 case ImplicitConversionSequence::Better:
7810 // Cand1 has a better conversion sequence.
7811 return true;
7812
7813 case ImplicitConversionSequence::Worse:
7814 // Cand1 can't be better than Cand2.
7815 return false;
7816
7817 case ImplicitConversionSequence::Indistinguishable:
7818 // Do nothing
7819 break;
7820 }
7821 }
7822
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007823 return false;
7824}
7825
Mike Stump1eb44332009-09-09 15:08:12 +00007826/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007827/// within an overload candidate set.
7828///
7829/// \param CandidateSet the set of candidate functions.
7830///
7831/// \param Loc the location of the function name (or operator symbol) for
7832/// which overload resolution occurs.
7833///
Mike Stump1eb44332009-09-09 15:08:12 +00007834/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007835/// function, Best points to the candidate function found.
7836///
7837/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007838OverloadingResult
7839OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007840 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007841 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007842 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007843 Best = end();
7844 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7845 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007846 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007847 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007848 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007849 }
7850
7851 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007852 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007853 return OR_No_Viable_Function;
7854
7855 // Make sure that this function is better than every other viable
7856 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007857 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007858 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007859 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007860 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007861 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007862 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007863 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007864 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007865 }
Mike Stump1eb44332009-09-09 15:08:12 +00007866
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007867 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007868 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007869 (Best->Function->isDeleted() ||
7870 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007871 return OR_Deleted;
7872
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007873 return OR_Success;
7874}
7875
John McCall3c80f572010-01-12 02:15:36 +00007876namespace {
7877
7878enum OverloadCandidateKind {
7879 oc_function,
7880 oc_method,
7881 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007882 oc_function_template,
7883 oc_method_template,
7884 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007885 oc_implicit_default_constructor,
7886 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007887 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007888 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007889 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007890 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007891};
7892
John McCall220ccbf2010-01-13 00:25:19 +00007893OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7894 FunctionDecl *Fn,
7895 std::string &Description) {
7896 bool isTemplate = false;
7897
7898 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7899 isTemplate = true;
7900 Description = S.getTemplateArgumentBindingsText(
7901 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7902 }
John McCallb1622a12010-01-06 09:43:14 +00007903
7904 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007905 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007906 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007907
Sebastian Redlf677ea32011-02-05 19:23:19 +00007908 if (Ctor->getInheritedConstructor())
7909 return oc_implicit_inherited_constructor;
7910
Sean Hunt82713172011-05-25 23:16:36 +00007911 if (Ctor->isDefaultConstructor())
7912 return oc_implicit_default_constructor;
7913
7914 if (Ctor->isMoveConstructor())
7915 return oc_implicit_move_constructor;
7916
7917 assert(Ctor->isCopyConstructor() &&
7918 "unexpected sort of implicit constructor");
7919 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007920 }
7921
7922 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7923 // This actually gets spelled 'candidate function' for now, but
7924 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007925 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007926 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007927
Sean Hunt82713172011-05-25 23:16:36 +00007928 if (Meth->isMoveAssignmentOperator())
7929 return oc_implicit_move_assignment;
7930
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007931 if (Meth->isCopyAssignmentOperator())
7932 return oc_implicit_copy_assignment;
7933
7934 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7935 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007936 }
7937
John McCall220ccbf2010-01-13 00:25:19 +00007938 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007939}
7940
Sebastian Redlf677ea32011-02-05 19:23:19 +00007941void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7942 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7943 if (!Ctor) return;
7944
7945 Ctor = Ctor->getInheritedConstructor();
7946 if (!Ctor) return;
7947
7948 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7949}
7950
John McCall3c80f572010-01-12 02:15:36 +00007951} // end anonymous namespace
7952
7953// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007954void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007955 std::string FnDesc;
7956 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007957 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7958 << (unsigned) K << FnDesc;
7959 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7960 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007961 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007962}
7963
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007964//Notes the location of all overload candidates designated through
7965// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007966void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007967 assert(OverloadedExpr->getType() == Context.OverloadTy);
7968
7969 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7970 OverloadExpr *OvlExpr = Ovl.Expression;
7971
7972 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7973 IEnd = OvlExpr->decls_end();
7974 I != IEnd; ++I) {
7975 if (FunctionTemplateDecl *FunTmpl =
7976 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007977 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007978 } else if (FunctionDecl *Fun
7979 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007980 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007981 }
7982 }
7983}
7984
John McCall1d318332010-01-12 00:44:57 +00007985/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7986/// "lead" diagnostic; it will be given two arguments, the source and
7987/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007988void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7989 Sema &S,
7990 SourceLocation CaretLoc,
7991 const PartialDiagnostic &PDiag) const {
7992 S.Diag(CaretLoc, PDiag)
7993 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007994 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007995 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7996 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007997 }
John McCall81201622010-01-08 04:41:39 +00007998}
7999
John McCall1d318332010-01-12 00:44:57 +00008000namespace {
8001
John McCalladbb8f82010-01-13 09:16:55 +00008002void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8003 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8004 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008005 assert(Cand->Function && "for now, candidate must be a function");
8006 FunctionDecl *Fn = Cand->Function;
8007
8008 // There's a conversion slot for the object argument if this is a
8009 // non-constructor method. Note that 'I' corresponds the
8010 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008011 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008012 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008013 if (I == 0)
8014 isObjectArgument = true;
8015 else
8016 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008017 }
8018
John McCall220ccbf2010-01-13 00:25:19 +00008019 std::string FnDesc;
8020 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8021
John McCalladbb8f82010-01-13 09:16:55 +00008022 Expr *FromExpr = Conv.Bad.FromExpr;
8023 QualType FromTy = Conv.Bad.getFromType();
8024 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008025
John McCall5920dbb2010-02-02 02:42:52 +00008026 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008027 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008028 Expr *E = FromExpr->IgnoreParens();
8029 if (isa<UnaryOperator>(E))
8030 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008031 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008032
8033 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8034 << (unsigned) FnKind << FnDesc
8035 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8036 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008037 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008038 return;
8039 }
8040
John McCall258b2032010-01-23 08:10:49 +00008041 // Do some hand-waving analysis to see if the non-viability is due
8042 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008043 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8044 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8045 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8046 CToTy = RT->getPointeeType();
8047 else {
8048 // TODO: detect and diagnose the full richness of const mismatches.
8049 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8050 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8051 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8052 }
8053
8054 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8055 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008056 Qualifiers FromQs = CFromTy.getQualifiers();
8057 Qualifiers ToQs = CToTy.getQualifiers();
8058
8059 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8061 << (unsigned) FnKind << FnDesc
8062 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8063 << FromTy
8064 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8065 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008066 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008067 return;
8068 }
8069
John McCallf85e1932011-06-15 23:02:42 +00008070 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008072 << (unsigned) FnKind << FnDesc
8073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8074 << FromTy
8075 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8076 << (unsigned) isObjectArgument << I+1;
8077 MaybeEmitInheritedConstructorNote(S, Fn);
8078 return;
8079 }
8080
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008081 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8083 << (unsigned) FnKind << FnDesc
8084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8085 << FromTy
8086 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8087 << (unsigned) isObjectArgument << I+1;
8088 MaybeEmitInheritedConstructorNote(S, Fn);
8089 return;
8090 }
8091
John McCall651f3ee2010-01-14 03:28:57 +00008092 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8093 assert(CVR && "unexpected qualifiers mismatch");
8094
8095 if (isObjectArgument) {
8096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8097 << (unsigned) FnKind << FnDesc
8098 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8099 << FromTy << (CVR - 1);
8100 } else {
8101 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8102 << (unsigned) FnKind << FnDesc
8103 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8104 << FromTy << (CVR - 1) << I+1;
8105 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008106 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008107 return;
8108 }
8109
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008110 // Special diagnostic for failure to convert an initializer list, since
8111 // telling the user that it has type void is not useful.
8112 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8114 << (unsigned) FnKind << FnDesc
8115 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8116 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8117 MaybeEmitInheritedConstructorNote(S, Fn);
8118 return;
8119 }
8120
John McCall258b2032010-01-23 08:10:49 +00008121 // Diagnose references or pointers to incomplete types differently,
8122 // since it's far from impossible that the incompleteness triggered
8123 // the failure.
8124 QualType TempFromTy = FromTy.getNonReferenceType();
8125 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8126 TempFromTy = PTy->getPointeeType();
8127 if (TempFromTy->isIncompleteType()) {
8128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8129 << (unsigned) FnKind << FnDesc
8130 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8131 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008132 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008133 return;
8134 }
8135
Douglas Gregor85789812010-06-30 23:01:39 +00008136 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008137 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008138 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8139 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8140 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8141 FromPtrTy->getPointeeType()) &&
8142 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8143 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008144 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008145 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008146 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008147 }
8148 } else if (const ObjCObjectPointerType *FromPtrTy
8149 = FromTy->getAs<ObjCObjectPointerType>()) {
8150 if (const ObjCObjectPointerType *ToPtrTy
8151 = ToTy->getAs<ObjCObjectPointerType>())
8152 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8153 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8154 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8155 FromPtrTy->getPointeeType()) &&
8156 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008157 BaseToDerivedConversion = 2;
8158 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008159 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8160 !FromTy->isIncompleteType() &&
8161 !ToRefTy->getPointeeType()->isIncompleteType() &&
8162 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8163 BaseToDerivedConversion = 3;
8164 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8165 ToTy.getNonReferenceType().getCanonicalType() ==
8166 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008167 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8168 << (unsigned) FnKind << FnDesc
8169 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8170 << (unsigned) isObjectArgument << I + 1;
8171 MaybeEmitInheritedConstructorNote(S, Fn);
8172 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008173 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008175
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008176 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008177 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008178 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008179 << (unsigned) FnKind << FnDesc
8180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008181 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008182 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008183 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008184 return;
8185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008186
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008187 if (isa<ObjCObjectPointerType>(CFromTy) &&
8188 isa<PointerType>(CToTy)) {
8189 Qualifiers FromQs = CFromTy.getQualifiers();
8190 Qualifiers ToQs = CToTy.getQualifiers();
8191 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8193 << (unsigned) FnKind << FnDesc
8194 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8195 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8196 MaybeEmitInheritedConstructorNote(S, Fn);
8197 return;
8198 }
8199 }
8200
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008201 // Emit the generic diagnostic and, optionally, add the hints to it.
8202 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8203 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008205 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8206 << (unsigned) (Cand->Fix.Kind);
8207
8208 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008209 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8210 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008211 FDiag << *HI;
8212 S.Diag(Fn->getLocation(), FDiag);
8213
Sebastian Redlf677ea32011-02-05 19:23:19 +00008214 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008215}
8216
8217void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8218 unsigned NumFormalArgs) {
8219 // TODO: treat calls to a missing default constructor as a special case
8220
8221 FunctionDecl *Fn = Cand->Function;
8222 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8223
8224 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008225
Douglas Gregor439d3c32011-05-05 00:13:13 +00008226 // With invalid overloaded operators, it's possible that we think we
8227 // have an arity mismatch when it fact it looks like we have the
8228 // right number of arguments, because only overloaded operators have
8229 // the weird behavior of overloading member and non-member functions.
8230 // Just don't report anything.
8231 if (Fn->isInvalidDecl() &&
8232 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8233 return;
8234
John McCalladbb8f82010-01-13 09:16:55 +00008235 // at least / at most / exactly
8236 unsigned mode, modeCount;
8237 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008238 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8239 (Cand->FailureKind == ovl_fail_bad_deduction &&
8240 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008241 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008242 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008243 mode = 0; // "at least"
8244 else
8245 mode = 2; // "exactly"
8246 modeCount = MinParams;
8247 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008248 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8249 (Cand->FailureKind == ovl_fail_bad_deduction &&
8250 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008251 if (MinParams != FnTy->getNumArgs())
8252 mode = 1; // "at most"
8253 else
8254 mode = 2; // "exactly"
8255 modeCount = FnTy->getNumArgs();
8256 }
8257
8258 std::string Description;
8259 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8260
Richard Smithf7b80562012-05-11 05:16:41 +00008261 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8262 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8263 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8264 << Fn->getParamDecl(0) << NumFormalArgs;
8265 else
8266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8267 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8268 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008269 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008270}
8271
John McCall342fec42010-02-01 18:53:26 +00008272/// Diagnose a failed template-argument deduction.
8273void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008274 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008275 FunctionDecl *Fn = Cand->Function; // pattern
8276
Douglas Gregora9333192010-05-08 17:41:32 +00008277 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008278 NamedDecl *ParamD;
8279 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8280 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8281 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008282 switch (Cand->DeductionFailure.Result) {
8283 case Sema::TDK_Success:
8284 llvm_unreachable("TDK_success while diagnosing bad deduction");
8285
8286 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008287 assert(ParamD && "no parameter found for incomplete deduction result");
8288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8289 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008290 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008291 return;
8292 }
8293
John McCall57e97782010-08-05 09:05:08 +00008294 case Sema::TDK_Underqualified: {
8295 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8296 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8297
8298 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8299
8300 // Param will have been canonicalized, but it should just be a
8301 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008302 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008303 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008304 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008305 assert(S.Context.hasSameType(Param, NonCanonParam));
8306
8307 // Arg has also been canonicalized, but there's nothing we can do
8308 // about that. It also doesn't matter as much, because it won't
8309 // have any template parameters in it (because deduction isn't
8310 // done on dependent types).
8311 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8312
8313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8314 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008315 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008316 return;
8317 }
8318
8319 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008320 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008321 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008322 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008323 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008324 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008325 which = 1;
8326 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008327 which = 2;
8328 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008329
Douglas Gregora9333192010-05-08 17:41:32 +00008330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008331 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008332 << *Cand->DeductionFailure.getFirstArg()
8333 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008334 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008335 return;
8336 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008337
Douglas Gregorf1a84452010-05-08 19:15:54 +00008338 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008339 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008340 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008341 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008342 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8343 << ParamD->getDeclName();
8344 else {
8345 int index = 0;
8346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8347 index = TTP->getIndex();
8348 else if (NonTypeTemplateParmDecl *NTTP
8349 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8350 index = NTTP->getIndex();
8351 else
8352 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008353 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008354 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8355 << (index + 1);
8356 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008357 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008358 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008359
Douglas Gregora18592e2010-05-08 18:13:28 +00008360 case Sema::TDK_TooManyArguments:
8361 case Sema::TDK_TooFewArguments:
8362 DiagnoseArityMismatch(S, Cand, NumArgs);
8363 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008364
8365 case Sema::TDK_InstantiationDepth:
8366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008367 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008368 return;
8369
8370 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008371 // Format the template argument list into the argument string.
8372 llvm::SmallString<128> TemplateArgString;
8373 if (TemplateArgumentList *Args =
8374 Cand->DeductionFailure.getTemplateArgumentList()) {
8375 TemplateArgString = " ";
8376 TemplateArgString += S.getTemplateArgumentBindingsText(
8377 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8378 }
8379
Richard Smith4493c0a2012-05-09 05:17:00 +00008380 // If this candidate was disabled by enable_if, say so.
8381 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8382 if (PDiag && PDiag->second.getDiagID() ==
8383 diag::err_typename_nested_not_found_enable_if) {
8384 // FIXME: Use the source range of the condition, and the fully-qualified
8385 // name of the enable_if template. These are both present in PDiag.
8386 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8387 << "'enable_if'" << TemplateArgString;
8388 return;
8389 }
8390
Richard Smithb8590f32012-05-07 09:03:25 +00008391 // Format the SFINAE diagnostic into the argument string.
8392 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8393 // formatted message in another diagnostic.
8394 llvm::SmallString<128> SFINAEArgString;
8395 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008396 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008397 SFINAEArgString = ": ";
8398 R = SourceRange(PDiag->first, PDiag->first);
8399 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8400 }
8401
Douglas Gregorec20f462010-05-08 20:07:26 +00008402 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008403 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008404 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008405 return;
8406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008407
John McCall342fec42010-02-01 18:53:26 +00008408 // TODO: diagnose these individually, then kill off
8409 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008410 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008411 case Sema::TDK_FailedOverloadResolution:
8412 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008413 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008414 return;
8415 }
8416}
8417
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008418/// CUDA: diagnose an invalid call across targets.
8419void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8420 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8421 FunctionDecl *Callee = Cand->Function;
8422
8423 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8424 CalleeTarget = S.IdentifyCUDATarget(Callee);
8425
8426 std::string FnDesc;
8427 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8428
8429 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8430 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8431}
8432
John McCall342fec42010-02-01 18:53:26 +00008433/// Generates a 'note' diagnostic for an overload candidate. We've
8434/// already generated a primary error at the call site.
8435///
8436/// It really does need to be a single diagnostic with its caret
8437/// pointed at the candidate declaration. Yes, this creates some
8438/// major challenges of technical writing. Yes, this makes pointing
8439/// out problems with specific arguments quite awkward. It's still
8440/// better than generating twenty screens of text for every failed
8441/// overload.
8442///
8443/// It would be great to be able to express per-candidate problems
8444/// more richly for those diagnostic clients that cared, but we'd
8445/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008446void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008447 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008448 FunctionDecl *Fn = Cand->Function;
8449
John McCall81201622010-01-08 04:41:39 +00008450 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008451 if (Cand->Viable && (Fn->isDeleted() ||
8452 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008453 std::string FnDesc;
8454 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008455
8456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008457 << FnKind << FnDesc
8458 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008459 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008460 return;
John McCall81201622010-01-08 04:41:39 +00008461 }
8462
John McCall220ccbf2010-01-13 00:25:19 +00008463 // We don't really have anything else to say about viable candidates.
8464 if (Cand->Viable) {
8465 S.NoteOverloadCandidate(Fn);
8466 return;
8467 }
John McCall1d318332010-01-12 00:44:57 +00008468
John McCalladbb8f82010-01-13 09:16:55 +00008469 switch (Cand->FailureKind) {
8470 case ovl_fail_too_many_arguments:
8471 case ovl_fail_too_few_arguments:
8472 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008473
John McCalladbb8f82010-01-13 09:16:55 +00008474 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008475 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008476
John McCall717e8912010-01-23 05:17:32 +00008477 case ovl_fail_trivial_conversion:
8478 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008479 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008480 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008481
John McCallb1bdc622010-02-25 01:37:24 +00008482 case ovl_fail_bad_conversion: {
8483 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008484 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008485 if (Cand->Conversions[I].isBad())
8486 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008487
John McCalladbb8f82010-01-13 09:16:55 +00008488 // FIXME: this currently happens when we're called from SemaInit
8489 // when user-conversion overload fails. Figure out how to handle
8490 // those conditions and diagnose them well.
8491 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008492 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008493
8494 case ovl_fail_bad_target:
8495 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008496 }
John McCalla1d7d622010-01-08 00:58:21 +00008497}
8498
8499void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8500 // Desugar the type of the surrogate down to a function type,
8501 // retaining as many typedefs as possible while still showing
8502 // the function type (and, therefore, its parameter types).
8503 QualType FnType = Cand->Surrogate->getConversionType();
8504 bool isLValueReference = false;
8505 bool isRValueReference = false;
8506 bool isPointer = false;
8507 if (const LValueReferenceType *FnTypeRef =
8508 FnType->getAs<LValueReferenceType>()) {
8509 FnType = FnTypeRef->getPointeeType();
8510 isLValueReference = true;
8511 } else if (const RValueReferenceType *FnTypeRef =
8512 FnType->getAs<RValueReferenceType>()) {
8513 FnType = FnTypeRef->getPointeeType();
8514 isRValueReference = true;
8515 }
8516 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8517 FnType = FnTypePtr->getPointeeType();
8518 isPointer = true;
8519 }
8520 // Desugar down to a function type.
8521 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8522 // Reconstruct the pointer/reference as appropriate.
8523 if (isPointer) FnType = S.Context.getPointerType(FnType);
8524 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8525 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8526
8527 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8528 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008529 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008530}
8531
8532void NoteBuiltinOperatorCandidate(Sema &S,
8533 const char *Opc,
8534 SourceLocation OpLoc,
8535 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008536 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008537 std::string TypeStr("operator");
8538 TypeStr += Opc;
8539 TypeStr += "(";
8540 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008541 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008542 TypeStr += ")";
8543 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8544 } else {
8545 TypeStr += ", ";
8546 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8547 TypeStr += ")";
8548 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8549 }
8550}
8551
8552void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8553 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008554 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008555 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8556 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008557 if (ICS.isBad()) break; // all meaningless after first invalid
8558 if (!ICS.isAmbiguous()) continue;
8559
John McCall120d63c2010-08-24 20:38:10 +00008560 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008561 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008562 }
8563}
8564
John McCall1b77e732010-01-15 23:32:50 +00008565SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8566 if (Cand->Function)
8567 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008568 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008569 return Cand->Surrogate->getLocation();
8570 return SourceLocation();
8571}
8572
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008573static unsigned
8574RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008575 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008576 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008577 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008578
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008579 case Sema::TDK_Incomplete:
8580 return 1;
8581
8582 case Sema::TDK_Underqualified:
8583 case Sema::TDK_Inconsistent:
8584 return 2;
8585
8586 case Sema::TDK_SubstitutionFailure:
8587 case Sema::TDK_NonDeducedMismatch:
8588 return 3;
8589
8590 case Sema::TDK_InstantiationDepth:
8591 case Sema::TDK_FailedOverloadResolution:
8592 return 4;
8593
8594 case Sema::TDK_InvalidExplicitArguments:
8595 return 5;
8596
8597 case Sema::TDK_TooManyArguments:
8598 case Sema::TDK_TooFewArguments:
8599 return 6;
8600 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008601 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008602}
8603
John McCallbf65c0b2010-01-12 00:48:53 +00008604struct CompareOverloadCandidatesForDisplay {
8605 Sema &S;
8606 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008607
8608 bool operator()(const OverloadCandidate *L,
8609 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008610 // Fast-path this check.
8611 if (L == R) return false;
8612
John McCall81201622010-01-08 04:41:39 +00008613 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008614 if (L->Viable) {
8615 if (!R->Viable) return true;
8616
8617 // TODO: introduce a tri-valued comparison for overload
8618 // candidates. Would be more worthwhile if we had a sort
8619 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008620 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8621 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008622 } else if (R->Viable)
8623 return false;
John McCall81201622010-01-08 04:41:39 +00008624
John McCall1b77e732010-01-15 23:32:50 +00008625 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008626
John McCall1b77e732010-01-15 23:32:50 +00008627 // Criteria by which we can sort non-viable candidates:
8628 if (!L->Viable) {
8629 // 1. Arity mismatches come after other candidates.
8630 if (L->FailureKind == ovl_fail_too_many_arguments ||
8631 L->FailureKind == ovl_fail_too_few_arguments)
8632 return false;
8633 if (R->FailureKind == ovl_fail_too_many_arguments ||
8634 R->FailureKind == ovl_fail_too_few_arguments)
8635 return true;
John McCall81201622010-01-08 04:41:39 +00008636
John McCall717e8912010-01-23 05:17:32 +00008637 // 2. Bad conversions come first and are ordered by the number
8638 // of bad conversions and quality of good conversions.
8639 if (L->FailureKind == ovl_fail_bad_conversion) {
8640 if (R->FailureKind != ovl_fail_bad_conversion)
8641 return true;
8642
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008643 // The conversion that can be fixed with a smaller number of changes,
8644 // comes first.
8645 unsigned numLFixes = L->Fix.NumConversionsFixed;
8646 unsigned numRFixes = R->Fix.NumConversionsFixed;
8647 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8648 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008649 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008650 if (numLFixes < numRFixes)
8651 return true;
8652 else
8653 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008654 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008655
John McCall717e8912010-01-23 05:17:32 +00008656 // If there's any ordering between the defined conversions...
8657 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008658 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008659
8660 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008661 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008662 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008663 switch (CompareImplicitConversionSequences(S,
8664 L->Conversions[I],
8665 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008666 case ImplicitConversionSequence::Better:
8667 leftBetter++;
8668 break;
8669
8670 case ImplicitConversionSequence::Worse:
8671 leftBetter--;
8672 break;
8673
8674 case ImplicitConversionSequence::Indistinguishable:
8675 break;
8676 }
8677 }
8678 if (leftBetter > 0) return true;
8679 if (leftBetter < 0) return false;
8680
8681 } else if (R->FailureKind == ovl_fail_bad_conversion)
8682 return false;
8683
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008684 if (L->FailureKind == ovl_fail_bad_deduction) {
8685 if (R->FailureKind != ovl_fail_bad_deduction)
8686 return true;
8687
8688 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8689 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008690 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008691 } else if (R->FailureKind == ovl_fail_bad_deduction)
8692 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008693
John McCall1b77e732010-01-15 23:32:50 +00008694 // TODO: others?
8695 }
8696
8697 // Sort everything else by location.
8698 SourceLocation LLoc = GetLocationForCandidate(L);
8699 SourceLocation RLoc = GetLocationForCandidate(R);
8700
8701 // Put candidates without locations (e.g. builtins) at the end.
8702 if (LLoc.isInvalid()) return false;
8703 if (RLoc.isInvalid()) return true;
8704
8705 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008706 }
8707};
8708
John McCall717e8912010-01-23 05:17:32 +00008709/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008710/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008711void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008712 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008713 assert(!Cand->Viable);
8714
8715 // Don't do anything on failures other than bad conversion.
8716 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8717
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008718 // We only want the FixIts if all the arguments can be corrected.
8719 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008720 // Use a implicit copy initialization to check conversion fixes.
8721 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008722
John McCall717e8912010-01-23 05:17:32 +00008723 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008724 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008725 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008726 while (true) {
8727 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8728 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008729 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008730 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008731 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008732 }
John McCall717e8912010-01-23 05:17:32 +00008733 }
8734
8735 if (ConvIdx == ConvCount)
8736 return;
8737
John McCallb1bdc622010-02-25 01:37:24 +00008738 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8739 "remaining conversion is initialized?");
8740
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008741 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008742 // operation somehow.
8743 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008744
8745 const FunctionProtoType* Proto;
8746 unsigned ArgIdx = ConvIdx;
8747
8748 if (Cand->IsSurrogate) {
8749 QualType ConvType
8750 = Cand->Surrogate->getConversionType().getNonReferenceType();
8751 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8752 ConvType = ConvPtrType->getPointeeType();
8753 Proto = ConvType->getAs<FunctionProtoType>();
8754 ArgIdx--;
8755 } else if (Cand->Function) {
8756 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8757 if (isa<CXXMethodDecl>(Cand->Function) &&
8758 !isa<CXXConstructorDecl>(Cand->Function))
8759 ArgIdx--;
8760 } else {
8761 // Builtin binary operator with a bad first conversion.
8762 assert(ConvCount <= 3);
8763 for (; ConvIdx != ConvCount; ++ConvIdx)
8764 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008765 = TryCopyInitialization(S, Args[ConvIdx],
8766 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008767 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008768 /*InOverloadResolution*/ true,
8769 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008770 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008771 return;
8772 }
8773
8774 // Fill in the rest of the conversions.
8775 unsigned NumArgsInProto = Proto->getNumArgs();
8776 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008777 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008778 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008779 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008780 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008781 /*InOverloadResolution=*/true,
8782 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008783 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008784 // Store the FixIt in the candidate if it exists.
8785 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008786 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008787 }
John McCall717e8912010-01-23 05:17:32 +00008788 else
8789 Cand->Conversions[ConvIdx].setEllipsis();
8790 }
8791}
8792
John McCalla1d7d622010-01-08 00:58:21 +00008793} // end anonymous namespace
8794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008795/// PrintOverloadCandidates - When overload resolution fails, prints
8796/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008797/// set.
John McCall120d63c2010-08-24 20:38:10 +00008798void OverloadCandidateSet::NoteCandidates(Sema &S,
8799 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008800 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008801 const char *Opc,
8802 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008803 // Sort the candidates by viability and position. Sorting directly would
8804 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008805 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008806 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8807 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008808 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008809 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008810 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008811 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008812 if (Cand->Function || Cand->IsSurrogate)
8813 Cands.push_back(Cand);
8814 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8815 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008816 }
8817 }
8818
John McCallbf65c0b2010-01-12 00:48:53 +00008819 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008820 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008821
John McCall1d318332010-01-12 00:44:57 +00008822 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008823
Chris Lattner5f9e2722011-07-23 10:55:15 +00008824 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008825 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8826 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008827 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008828 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8829 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008830
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008831 // Set an arbitrary limit on the number of candidate functions we'll spam
8832 // the user with. FIXME: This limit should depend on details of the
8833 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008834 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008835 break;
8836 }
8837 ++CandsShown;
8838
John McCalla1d7d622010-01-08 00:58:21 +00008839 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008840 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008841 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008842 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008843 else {
8844 assert(Cand->Viable &&
8845 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008846 // Generally we only see ambiguities including viable builtin
8847 // operators if overload resolution got screwed up by an
8848 // ambiguous user-defined conversion.
8849 //
8850 // FIXME: It's quite possible for different conversions to see
8851 // different ambiguities, though.
8852 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008853 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008854 ReportedAmbiguousConversions = true;
8855 }
John McCalla1d7d622010-01-08 00:58:21 +00008856
John McCall1d318332010-01-12 00:44:57 +00008857 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008858 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008859 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008860 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008861
8862 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008863 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008864}
8865
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008866// [PossiblyAFunctionType] --> [Return]
8867// NonFunctionType --> NonFunctionType
8868// R (A) --> R(A)
8869// R (*)(A) --> R (A)
8870// R (&)(A) --> R (A)
8871// R (S::*)(A) --> R (A)
8872QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8873 QualType Ret = PossiblyAFunctionType;
8874 if (const PointerType *ToTypePtr =
8875 PossiblyAFunctionType->getAs<PointerType>())
8876 Ret = ToTypePtr->getPointeeType();
8877 else if (const ReferenceType *ToTypeRef =
8878 PossiblyAFunctionType->getAs<ReferenceType>())
8879 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008880 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008881 PossiblyAFunctionType->getAs<MemberPointerType>())
8882 Ret = MemTypePtr->getPointeeType();
8883 Ret =
8884 Context.getCanonicalType(Ret).getUnqualifiedType();
8885 return Ret;
8886}
Douglas Gregor904eed32008-11-10 20:40:00 +00008887
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008888// A helper class to help with address of function resolution
8889// - allows us to avoid passing around all those ugly parameters
8890class AddressOfFunctionResolver
8891{
8892 Sema& S;
8893 Expr* SourceExpr;
8894 const QualType& TargetType;
8895 QualType TargetFunctionType; // Extracted function type from target type
8896
8897 bool Complain;
8898 //DeclAccessPair& ResultFunctionAccessPair;
8899 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008900
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008901 bool TargetTypeIsNonStaticMemberFunction;
8902 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008903
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008904 OverloadExpr::FindResult OvlExprInfo;
8905 OverloadExpr *OvlExpr;
8906 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008907 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008908
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008909public:
8910 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8911 const QualType& TargetType, bool Complain)
8912 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8913 Complain(Complain), Context(S.getASTContext()),
8914 TargetTypeIsNonStaticMemberFunction(
8915 !!TargetType->getAs<MemberPointerType>()),
8916 FoundNonTemplateFunction(false),
8917 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8918 OvlExpr(OvlExprInfo.Expression)
8919 {
8920 ExtractUnqualifiedFunctionTypeFromTargetType();
8921
8922 if (!TargetFunctionType->isFunctionType()) {
8923 if (OvlExpr->hasExplicitTemplateArgs()) {
8924 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008925 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008926 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008927
8928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8929 if (!Method->isStatic()) {
8930 // If the target type is a non-function type and the function
8931 // found is a non-static member function, pretend as if that was
8932 // the target, it's the only possible type to end up with.
8933 TargetTypeIsNonStaticMemberFunction = true;
8934
8935 // And skip adding the function if its not in the proper form.
8936 // We'll diagnose this due to an empty set of functions.
8937 if (!OvlExprInfo.HasFormOfMemberPointer)
8938 return;
8939 }
8940 }
8941
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008942 Matches.push_back(std::make_pair(dap,Fn));
8943 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008944 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008945 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008946 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008947
8948 if (OvlExpr->hasExplicitTemplateArgs())
8949 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008950
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008951 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8952 // C++ [over.over]p4:
8953 // If more than one function is selected, [...]
8954 if (Matches.size() > 1) {
8955 if (FoundNonTemplateFunction)
8956 EliminateAllTemplateMatches();
8957 else
8958 EliminateAllExceptMostSpecializedTemplate();
8959 }
8960 }
8961 }
8962
8963private:
8964 bool isTargetTypeAFunction() const {
8965 return TargetFunctionType->isFunctionType();
8966 }
8967
8968 // [ToType] [Return]
8969
8970 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8971 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8972 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8973 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8974 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8975 }
8976
8977 // return true if any matching specializations were found
8978 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8979 const DeclAccessPair& CurAccessFunPair) {
8980 if (CXXMethodDecl *Method
8981 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8982 // Skip non-static function templates when converting to pointer, and
8983 // static when converting to member pointer.
8984 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8985 return false;
8986 }
8987 else if (TargetTypeIsNonStaticMemberFunction)
8988 return false;
8989
8990 // C++ [over.over]p2:
8991 // If the name is a function template, template argument deduction is
8992 // done (14.8.2.2), and if the argument deduction succeeds, the
8993 // resulting template argument list is used to generate a single
8994 // function template specialization, which is added to the set of
8995 // overloaded functions considered.
8996 FunctionDecl *Specialization = 0;
8997 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8998 if (Sema::TemplateDeductionResult Result
8999 = S.DeduceTemplateArguments(FunctionTemplate,
9000 &OvlExplicitTemplateArgs,
9001 TargetFunctionType, Specialization,
9002 Info)) {
9003 // FIXME: make a note of the failed deduction for diagnostics.
9004 (void)Result;
9005 return false;
9006 }
9007
9008 // Template argument deduction ensures that we have an exact match.
9009 // This function template specicalization works.
9010 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9011 assert(TargetFunctionType
9012 == Context.getCanonicalType(Specialization->getType()));
9013 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9014 return true;
9015 }
9016
9017 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9018 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009019 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009020 // Skip non-static functions when converting to pointer, and static
9021 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009022 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9023 return false;
9024 }
9025 else if (TargetTypeIsNonStaticMemberFunction)
9026 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009027
Chandler Carruthbd647292009-12-29 06:17:27 +00009028 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009029 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009030 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9031 if (S.CheckCUDATarget(Caller, FunDecl))
9032 return false;
9033
Douglas Gregor43c79c22009-12-09 00:47:37 +00009034 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009035 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9036 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009037 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9038 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009039 Matches.push_back(std::make_pair(CurAccessFunPair,
9040 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009041 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009042 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009043 }
Mike Stump1eb44332009-09-09 15:08:12 +00009044 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009045
9046 return false;
9047 }
9048
9049 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9050 bool Ret = false;
9051
9052 // If the overload expression doesn't have the form of a pointer to
9053 // member, don't try to convert it to a pointer-to-member type.
9054 if (IsInvalidFormOfPointerToMemberFunction())
9055 return false;
9056
9057 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9058 E = OvlExpr->decls_end();
9059 I != E; ++I) {
9060 // Look through any using declarations to find the underlying function.
9061 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9062
9063 // C++ [over.over]p3:
9064 // Non-member functions and static member functions match
9065 // targets of type "pointer-to-function" or "reference-to-function."
9066 // Nonstatic member functions match targets of
9067 // type "pointer-to-member-function."
9068 // Note that according to DR 247, the containing class does not matter.
9069 if (FunctionTemplateDecl *FunctionTemplate
9070 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9071 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9072 Ret = true;
9073 }
9074 // If we have explicit template arguments supplied, skip non-templates.
9075 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9076 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9077 Ret = true;
9078 }
9079 assert(Ret || Matches.empty());
9080 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009081 }
9082
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009083 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009084 // [...] and any given function template specialization F1 is
9085 // eliminated if the set contains a second function template
9086 // specialization whose function template is more specialized
9087 // than the function template of F1 according to the partial
9088 // ordering rules of 14.5.5.2.
9089
9090 // The algorithm specified above is quadratic. We instead use a
9091 // two-pass algorithm (similar to the one used to identify the
9092 // best viable function in an overload set) that identifies the
9093 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009094
9095 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9096 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9097 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009098
John McCallc373d482010-01-27 01:50:18 +00009099 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009100 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9101 TPOC_Other, 0, SourceExpr->getLocStart(),
9102 S.PDiag(),
9103 S.PDiag(diag::err_addr_ovl_ambiguous)
9104 << Matches[0].second->getDeclName(),
9105 S.PDiag(diag::note_ovl_candidate)
9106 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009107 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009108
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009109 if (Result != MatchesCopy.end()) {
9110 // Make it the first and only element
9111 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9112 Matches[0].second = cast<FunctionDecl>(*Result);
9113 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009114 }
9115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009116
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009117 void EliminateAllTemplateMatches() {
9118 // [...] any function template specializations in the set are
9119 // eliminated if the set also contains a non-template function, [...]
9120 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9121 if (Matches[I].second->getPrimaryTemplate() == 0)
9122 ++I;
9123 else {
9124 Matches[I] = Matches[--N];
9125 Matches.set_size(N);
9126 }
9127 }
9128 }
9129
9130public:
9131 void ComplainNoMatchesFound() const {
9132 assert(Matches.empty());
9133 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9134 << OvlExpr->getName() << TargetFunctionType
9135 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009136 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009137 }
9138
9139 bool IsInvalidFormOfPointerToMemberFunction() const {
9140 return TargetTypeIsNonStaticMemberFunction &&
9141 !OvlExprInfo.HasFormOfMemberPointer;
9142 }
9143
9144 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9145 // TODO: Should we condition this on whether any functions might
9146 // have matched, or is it more appropriate to do that in callers?
9147 // TODO: a fixit wouldn't hurt.
9148 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9149 << TargetType << OvlExpr->getSourceRange();
9150 }
9151
9152 void ComplainOfInvalidConversion() const {
9153 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9154 << OvlExpr->getName() << TargetType;
9155 }
9156
9157 void ComplainMultipleMatchesFound() const {
9158 assert(Matches.size() > 1);
9159 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9160 << OvlExpr->getName()
9161 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009162 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009163 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009164
9165 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9166
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009167 int getNumMatches() const { return Matches.size(); }
9168
9169 FunctionDecl* getMatchingFunctionDecl() const {
9170 if (Matches.size() != 1) return 0;
9171 return Matches[0].second;
9172 }
9173
9174 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9175 if (Matches.size() != 1) return 0;
9176 return &Matches[0].first;
9177 }
9178};
9179
9180/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9181/// an overloaded function (C++ [over.over]), where @p From is an
9182/// expression with overloaded function type and @p ToType is the type
9183/// we're trying to resolve to. For example:
9184///
9185/// @code
9186/// int f(double);
9187/// int f(int);
9188///
9189/// int (*pfd)(double) = f; // selects f(double)
9190/// @endcode
9191///
9192/// This routine returns the resulting FunctionDecl if it could be
9193/// resolved, and NULL otherwise. When @p Complain is true, this
9194/// routine will emit diagnostics if there is an error.
9195FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009196Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9197 QualType TargetType,
9198 bool Complain,
9199 DeclAccessPair &FoundResult,
9200 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009201 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009202
9203 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9204 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009205 int NumMatches = Resolver.getNumMatches();
9206 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009207 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009208 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9209 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9210 else
9211 Resolver.ComplainNoMatchesFound();
9212 }
9213 else if (NumMatches > 1 && Complain)
9214 Resolver.ComplainMultipleMatchesFound();
9215 else if (NumMatches == 1) {
9216 Fn = Resolver.getMatchingFunctionDecl();
9217 assert(Fn);
9218 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009219 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009220 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009221 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009222 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009223
9224 if (pHadMultipleCandidates)
9225 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009226 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009227}
9228
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009229/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009230/// resolve that overloaded function expression down to a single function.
9231///
9232/// This routine can only resolve template-ids that refer to a single function
9233/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009234/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009235/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009236FunctionDecl *
9237Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9238 bool Complain,
9239 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009240 // C++ [over.over]p1:
9241 // [...] [Note: any redundant set of parentheses surrounding the
9242 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009243 // C++ [over.over]p1:
9244 // [...] The overloaded function name can be preceded by the &
9245 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009246
Douglas Gregor4b52e252009-12-21 23:17:24 +00009247 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009248 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009249 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009250
9251 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009252 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009253
Douglas Gregor4b52e252009-12-21 23:17:24 +00009254 // Look through all of the overloaded functions, searching for one
9255 // whose type matches exactly.
9256 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009257 for (UnresolvedSetIterator I = ovl->decls_begin(),
9258 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009259 // C++0x [temp.arg.explicit]p3:
9260 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009261 // where deduction is not done, if a template argument list is
9262 // specified and it, along with any default template arguments,
9263 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009264 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009265 FunctionTemplateDecl *FunctionTemplate
9266 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009267
Douglas Gregor4b52e252009-12-21 23:17:24 +00009268 // C++ [over.over]p2:
9269 // If the name is a function template, template argument deduction is
9270 // done (14.8.2.2), and if the argument deduction succeeds, the
9271 // resulting template argument list is used to generate a single
9272 // function template specialization, which is added to the set of
9273 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009274 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009275 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009276 if (TemplateDeductionResult Result
9277 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9278 Specialization, Info)) {
9279 // FIXME: make a note of the failed deduction for diagnostics.
9280 (void)Result;
9281 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009282 }
9283
John McCall864c0412011-04-26 20:42:42 +00009284 assert(Specialization && "no specialization and no error?");
9285
Douglas Gregor4b52e252009-12-21 23:17:24 +00009286 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009287 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009288 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009289 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9290 << ovl->getName();
9291 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009292 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009293 return 0;
John McCall864c0412011-04-26 20:42:42 +00009294 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295
John McCall864c0412011-04-26 20:42:42 +00009296 Matched = Specialization;
9297 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009298 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009299
Douglas Gregor4b52e252009-12-21 23:17:24 +00009300 return Matched;
9301}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009302
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009303
9304
9305
John McCall6dbba4f2011-10-11 23:14:30 +00009306// Resolve and fix an overloaded expression that can be resolved
9307// because it identifies a single function template specialization.
9308//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009309// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009310//
9311// Return true if it was logically possible to so resolve the
9312// expression, regardless of whether or not it succeeded. Always
9313// returns true if 'complain' is set.
9314bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9315 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9316 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009317 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009318 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009319 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009320
John McCall6dbba4f2011-10-11 23:14:30 +00009321 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009322
John McCall864c0412011-04-26 20:42:42 +00009323 DeclAccessPair found;
9324 ExprResult SingleFunctionExpression;
9325 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9326 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009327 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009328 SrcExpr = ExprError();
9329 return true;
9330 }
John McCall864c0412011-04-26 20:42:42 +00009331
9332 // It is only correct to resolve to an instance method if we're
9333 // resolving a form that's permitted to be a pointer to member.
9334 // Otherwise we'll end up making a bound member expression, which
9335 // is illegal in all the contexts we resolve like this.
9336 if (!ovl.HasFormOfMemberPointer &&
9337 isa<CXXMethodDecl>(fn) &&
9338 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009339 if (!complain) return false;
9340
9341 Diag(ovl.Expression->getExprLoc(),
9342 diag::err_bound_member_function)
9343 << 0 << ovl.Expression->getSourceRange();
9344
9345 // TODO: I believe we only end up here if there's a mix of
9346 // static and non-static candidates (otherwise the expression
9347 // would have 'bound member' type, not 'overload' type).
9348 // Ideally we would note which candidate was chosen and why
9349 // the static candidates were rejected.
9350 SrcExpr = ExprError();
9351 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009352 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009353
John McCall864c0412011-04-26 20:42:42 +00009354 // Fix the expresion to refer to 'fn'.
9355 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009356 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009357
9358 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009359 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009360 SingleFunctionExpression =
9361 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009362 if (SingleFunctionExpression.isInvalid()) {
9363 SrcExpr = ExprError();
9364 return true;
9365 }
9366 }
John McCall864c0412011-04-26 20:42:42 +00009367 }
9368
9369 if (!SingleFunctionExpression.isUsable()) {
9370 if (complain) {
9371 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9372 << ovl.Expression->getName()
9373 << DestTypeForComplaining
9374 << OpRangeForComplaining
9375 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009376 NoteAllOverloadCandidates(SrcExpr.get());
9377
9378 SrcExpr = ExprError();
9379 return true;
9380 }
9381
9382 return false;
John McCall864c0412011-04-26 20:42:42 +00009383 }
9384
John McCall6dbba4f2011-10-11 23:14:30 +00009385 SrcExpr = SingleFunctionExpression;
9386 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009387}
9388
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009389/// \brief Add a single candidate to the overload set.
9390static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009391 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009392 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009393 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009394 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009395 bool PartialOverloading,
9396 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009397 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009398 if (isa<UsingShadowDecl>(Callee))
9399 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9400
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009401 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009402 if (ExplicitTemplateArgs) {
9403 assert(!KnownValid && "Explicit template arguments?");
9404 return;
9405 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009406 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9407 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009408 return;
John McCallba135432009-11-21 08:51:07 +00009409 }
9410
9411 if (FunctionTemplateDecl *FuncTemplate
9412 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009413 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009414 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009415 return;
9416 }
9417
Richard Smith2ced0442011-06-26 22:19:54 +00009418 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009419}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009420
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009421/// \brief Add the overload candidates named by callee and/or found by argument
9422/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009423void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009424 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009425 OverloadCandidateSet &CandidateSet,
9426 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009427
9428#ifndef NDEBUG
9429 // Verify that ArgumentDependentLookup is consistent with the rules
9430 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009431 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009432 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9433 // and let Y be the lookup set produced by argument dependent
9434 // lookup (defined as follows). If X contains
9435 //
9436 // -- a declaration of a class member, or
9437 //
9438 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009439 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009440 //
9441 // -- a declaration that is neither a function or a function
9442 // template
9443 //
9444 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009445
John McCall3b4294e2009-12-16 12:17:52 +00009446 if (ULE->requiresADL()) {
9447 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9448 E = ULE->decls_end(); I != E; ++I) {
9449 assert(!(*I)->getDeclContext()->isRecord());
9450 assert(isa<UsingShadowDecl>(*I) ||
9451 !(*I)->getDeclContext()->isFunctionOrMethod());
9452 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009453 }
9454 }
9455#endif
9456
John McCall3b4294e2009-12-16 12:17:52 +00009457 // It would be nice to avoid this copy.
9458 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009459 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009460 if (ULE->hasExplicitTemplateArgs()) {
9461 ULE->copyTemplateArgumentsInto(TABuffer);
9462 ExplicitTemplateArgs = &TABuffer;
9463 }
9464
9465 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9466 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009467 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9468 CandidateSet, PartialOverloading,
9469 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009470
John McCall3b4294e2009-12-16 12:17:52 +00009471 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009472 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009473 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009474 Args, ExplicitTemplateArgs,
9475 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009476 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009477}
John McCall578b69b2009-12-16 08:11:27 +00009478
Richard Smithf50e88a2011-06-05 22:42:48 +00009479/// Attempt to recover from an ill-formed use of a non-dependent name in a
9480/// template, where the non-dependent name was declared after the template
9481/// was defined. This is common in code written for a compilers which do not
9482/// correctly implement two-stage name lookup.
9483///
9484/// Returns true if a viable candidate was found and a diagnostic was issued.
9485static bool
9486DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9487 const CXXScopeSpec &SS, LookupResult &R,
9488 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009489 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009490 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9491 return false;
9492
9493 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009494 if (DC->isTransparentContext())
9495 continue;
9496
Richard Smithf50e88a2011-06-05 22:42:48 +00009497 SemaRef.LookupQualifiedName(R, DC);
9498
9499 if (!R.empty()) {
9500 R.suppressDiagnostics();
9501
9502 if (isa<CXXRecordDecl>(DC)) {
9503 // Don't diagnose names we find in classes; we get much better
9504 // diagnostics for these from DiagnoseEmptyLookup.
9505 R.clear();
9506 return false;
9507 }
9508
9509 OverloadCandidateSet Candidates(FnLoc);
9510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9511 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009512 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009513 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009514
9515 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009516 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009517 // No viable functions. Don't bother the user with notes for functions
9518 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009519 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009520 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009521 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009522
9523 // Find the namespaces where ADL would have looked, and suggest
9524 // declaring the function there instead.
9525 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9526 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009527 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009528 AssociatedNamespaces,
9529 AssociatedClasses);
9530 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009531 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009532 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009533 for (Sema::AssociatedNamespaceSet::iterator
9534 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009535 end = AssociatedNamespaces.end(); it != end; ++it) {
9536 if (!Std->Encloses(*it))
9537 SuggestedNamespaces.insert(*it);
9538 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009539 } else {
9540 // Lacking the 'std::' namespace, use all of the associated namespaces.
9541 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009542 }
9543
9544 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9545 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009546 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009547 SemaRef.Diag(Best->Function->getLocation(),
9548 diag::note_not_found_by_two_phase_lookup)
9549 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009550 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009551 SemaRef.Diag(Best->Function->getLocation(),
9552 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009553 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009554 } else {
9555 // FIXME: It would be useful to list the associated namespaces here,
9556 // but the diagnostics infrastructure doesn't provide a way to produce
9557 // a localized representation of a list of items.
9558 SemaRef.Diag(Best->Function->getLocation(),
9559 diag::note_not_found_by_two_phase_lookup)
9560 << R.getLookupName() << 2;
9561 }
9562
9563 // Try to recover by calling this function.
9564 return true;
9565 }
9566
9567 R.clear();
9568 }
9569
9570 return false;
9571}
9572
9573/// Attempt to recover from ill-formed use of a non-dependent operator in a
9574/// template, where the non-dependent operator was declared after the template
9575/// was defined.
9576///
9577/// Returns true if a viable candidate was found and a diagnostic was issued.
9578static bool
9579DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9580 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009581 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009582 DeclarationName OpName =
9583 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9584 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9585 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009586 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009587}
9588
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009589namespace {
9590// Callback to limit the allowed keywords and to only accept typo corrections
9591// that are keywords or whose decls refer to functions (or template functions)
9592// that accept the given number of arguments.
9593class RecoveryCallCCC : public CorrectionCandidateCallback {
9594 public:
9595 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9596 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009597 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009598 WantRemainingKeywords = false;
9599 }
9600
9601 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9602 if (!candidate.getCorrectionDecl())
9603 return candidate.isKeyword();
9604
9605 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9606 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9607 FunctionDecl *FD = 0;
9608 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9609 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9610 FD = FTD->getTemplatedDecl();
9611 if (!HasExplicitTemplateArgs && !FD) {
9612 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9613 // If the Decl is neither a function nor a template function,
9614 // determine if it is a pointer or reference to a function. If so,
9615 // check against the number of arguments expected for the pointee.
9616 QualType ValType = cast<ValueDecl>(ND)->getType();
9617 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9618 ValType = ValType->getPointeeType();
9619 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9620 if (FPT->getNumArgs() == NumArgs)
9621 return true;
9622 }
9623 }
9624 if (FD && FD->getNumParams() >= NumArgs &&
9625 FD->getMinRequiredArguments() <= NumArgs)
9626 return true;
9627 }
9628 return false;
9629 }
9630
9631 private:
9632 unsigned NumArgs;
9633 bool HasExplicitTemplateArgs;
9634};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009635
9636// Callback that effectively disabled typo correction
9637class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9638 public:
9639 NoTypoCorrectionCCC() {
9640 WantTypeSpecifiers = false;
9641 WantExpressionKeywords = false;
9642 WantCXXNamedCasts = false;
9643 WantRemainingKeywords = false;
9644 }
9645
9646 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9647 return false;
9648 }
9649};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009650}
9651
John McCall578b69b2009-12-16 08:11:27 +00009652/// Attempts to recover from a call where no functions were found.
9653///
9654/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009655static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009656BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009657 UnresolvedLookupExpr *ULE,
9658 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009659 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009660 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009661 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009662
9663 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009664 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009666
John McCall3b4294e2009-12-16 12:17:52 +00009667 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009668 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009669 if (ULE->hasExplicitTemplateArgs()) {
9670 ULE->copyTemplateArgumentsInto(TABuffer);
9671 ExplicitTemplateArgs = &TABuffer;
9672 }
9673
John McCall578b69b2009-12-16 08:11:27 +00009674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9675 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009676 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009677 NoTypoCorrectionCCC RejectAll;
9678 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9679 (CorrectionCandidateCallback*)&Validator :
9680 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009681 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009682 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009683 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009684 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009685 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009686 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009687
John McCall3b4294e2009-12-16 12:17:52 +00009688 assert(!R.empty() && "lookup results empty despite recovery");
9689
9690 // Build an implicit member call if appropriate. Just drop the
9691 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009692 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009693 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009694 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9695 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009696 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009697 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009698 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009699 else
9700 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9701
9702 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009703 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009704
9705 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009706 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009707 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009708 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009709 MultiExprArg(Args.data(), Args.size()),
9710 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009711}
Douglas Gregord7a95972010-06-08 17:35:15 +00009712
Douglas Gregorf6b89692008-11-26 05:54:23 +00009713/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009714/// (which eventually refers to the declaration Func) and the call
9715/// arguments Args/NumArgs, attempt to resolve the function call down
9716/// to a specific function. If overload resolution succeeds, returns
9717/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009718/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009719/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009720ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009721Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009722 SourceLocation LParenLoc,
9723 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009724 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009725 Expr *ExecConfig,
9726 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009727#ifndef NDEBUG
9728 if (ULE->requiresADL()) {
9729 // To do ADL, we must have found an unqualified name.
9730 assert(!ULE->getQualifier() && "qualified name with ADL");
9731
9732 // We don't perform ADL for implicit declarations of builtins.
9733 // Verify that this was correctly set up.
9734 FunctionDecl *F;
9735 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9736 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9737 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009738 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009739
John McCall3b4294e2009-12-16 12:17:52 +00009740 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009741 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009742 } else
9743 assert(!ULE->isStdAssociatedNamespace() &&
9744 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009745#endif
9746
John McCall5acb0c92011-10-17 18:40:02 +00009747 UnbridgedCastsSet UnbridgedCasts;
9748 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9749 return ExprError();
9750
John McCall5769d612010-02-08 23:07:23 +00009751 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009752
John McCall3b4294e2009-12-16 12:17:52 +00009753 // Add the functions denoted by the callee to the set of candidate
9754 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009755 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9756 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009757
9758 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009759 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9760 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009761 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009762 // In Microsoft mode, if we are inside a template class member function then
9763 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009764 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009765 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009766 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009767 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009768 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9769 Context.DependentTy, VK_RValue,
9770 RParenLoc);
9771 CE->setTypeDependent(true);
9772 return Owned(CE);
9773 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009774 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9775 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009776 RParenLoc, /*EmptyLookup=*/true,
9777 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009778 }
John McCall578b69b2009-12-16 08:11:27 +00009779
John McCall5acb0c92011-10-17 18:40:02 +00009780 UnbridgedCasts.restore();
9781
Douglas Gregorf6b89692008-11-26 05:54:23 +00009782 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009783 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009784 case OR_Success: {
9785 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009786 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009787 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009788 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009789 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009790 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9791 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009792 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009793
Richard Smithf50e88a2011-06-05 22:42:48 +00009794 case OR_No_Viable_Function: {
9795 // Try to recover by looking for viable functions which the user might
9796 // have meant to call.
9797 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009798 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9799 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009800 /*EmptyLookup=*/false,
9801 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009802 if (!Recovery.isInvalid())
9803 return Recovery;
9804
Daniel Dunbar96a00142012-03-09 18:35:03 +00009805 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009806 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009807 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9809 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009810 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009811 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009812
9813 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009814 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009815 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009816 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9817 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009818 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009819
9820 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009821 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009822 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009823 << Best->Function->isDeleted()
9824 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009825 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009826 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9828 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009829
9830 // We emitted an error for the unvailable/deleted function call but keep
9831 // the call in the AST.
9832 FunctionDecl *FDecl = Best->Function;
9833 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9834 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9835 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009836 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009837 }
9838
Douglas Gregorff331c12010-07-25 18:17:45 +00009839 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009840 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009841}
9842
John McCall6e266892010-01-26 03:27:55 +00009843static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009844 return Functions.size() > 1 ||
9845 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9846}
9847
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009848/// \brief Create a unary operation that may resolve to an overloaded
9849/// operator.
9850///
9851/// \param OpLoc The location of the operator itself (e.g., '*').
9852///
9853/// \param OpcIn The UnaryOperator::Opcode that describes this
9854/// operator.
9855///
9856/// \param Functions The set of non-member functions that will be
9857/// considered by overload resolution. The caller needs to build this
9858/// set based on the context using, e.g.,
9859/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9860/// set should not contain any member functions; those will be added
9861/// by CreateOverloadedUnaryOp().
9862///
9863/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009864ExprResult
John McCall6e266892010-01-26 03:27:55 +00009865Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9866 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009867 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009868 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009869
9870 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9871 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9872 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009873 // TODO: provide better source location info.
9874 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009875
John McCall5acb0c92011-10-17 18:40:02 +00009876 if (checkPlaceholderForOverload(*this, Input))
9877 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009878
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009879 Expr *Args[2] = { Input, 0 };
9880 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009881
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009882 // For post-increment and post-decrement, add the implicit '0' as
9883 // the second argument, so that we know this is a post-increment or
9884 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009885 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009886 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009887 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9888 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009889 NumArgs = 2;
9890 }
9891
9892 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009893 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009894 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009895 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009896 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009897 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009898 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009899
John McCallc373d482010-01-27 01:50:18 +00009900 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009901 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009902 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009903 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009904 /*ADL*/ true, IsOverloaded(Fns),
9905 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009906 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009907 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009908 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009909 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009910 OpLoc));
9911 }
9912
9913 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009914 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009915
9916 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009917 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9918 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009919
9920 // Add operator candidates that are member functions.
9921 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9922
John McCall6e266892010-01-26 03:27:55 +00009923 // Add candidates from ADL.
9924 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009925 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009926 /*ExplicitTemplateArgs*/ 0,
9927 CandidateSet);
9928
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009929 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009930 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009931
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009932 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9933
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009934 // Perform overload resolution.
9935 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009936 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009937 case OR_Success: {
9938 // We found a built-in operator or an overloaded operator.
9939 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009940
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009941 if (FnDecl) {
9942 // We matched an overloaded operator. Build a call to that
9943 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009944
Eli Friedman5f2987c2012-02-02 03:46:19 +00009945 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009946
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009947 // Convert the arguments.
9948 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009949 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009950
John Wiegley429bb272011-04-08 18:41:53 +00009951 ExprResult InputRes =
9952 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9953 Best->FoundDecl, Method);
9954 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009955 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009956 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009957 } else {
9958 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009959 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009960 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009961 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009962 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009963 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009964 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009965 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009966 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009967 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009968 }
9969
John McCallb697e082010-05-06 18:15:07 +00009970 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9971
John McCallf89e55a2010-11-18 06:31:45 +00009972 // Determine the result type.
9973 QualType ResultTy = FnDecl->getResultType();
9974 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9975 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009976
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009977 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009978 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009979 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009980 if (FnExpr.isInvalid())
9981 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009982
Eli Friedman4c3b8962009-11-18 03:58:17 +00009983 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009984 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009985 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009986 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009987
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009988 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009989 FnDecl))
9990 return ExprError();
9991
John McCall9ae2f072010-08-23 23:25:46 +00009992 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009993 } else {
9994 // We matched a built-in operator. Convert the arguments, then
9995 // break out so that we will build the appropriate built-in
9996 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009997 ExprResult InputRes =
9998 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9999 Best->Conversions[0], AA_Passing);
10000 if (InputRes.isInvalid())
10001 return ExprError();
10002 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010003 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010004 }
John Wiegley429bb272011-04-08 18:41:53 +000010005 }
10006
10007 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010008 // This is an erroneous use of an operator which can be overloaded by
10009 // a non-member function. Check for non-member operators which were
10010 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010011 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10012 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010013 // FIXME: Recover by calling the found function.
10014 return ExprError();
10015
John Wiegley429bb272011-04-08 18:41:53 +000010016 // No viable function; fall through to handling this as a
10017 // built-in operator, which will produce an error message for us.
10018 break;
10019
10020 case OR_Ambiguous:
10021 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10022 << UnaryOperator::getOpcodeStr(Opc)
10023 << Input->getType()
10024 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010025 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10026 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010027 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10028 return ExprError();
10029
10030 case OR_Deleted:
10031 Diag(OpLoc, diag::err_ovl_deleted_oper)
10032 << Best->Function->isDeleted()
10033 << UnaryOperator::getOpcodeStr(Opc)
10034 << getDeletedOrUnavailableSuffix(Best->Function)
10035 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010036 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10037 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010038 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010039 return ExprError();
10040 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010041
10042 // Either we found no viable overloaded operator or we matched a
10043 // built-in operator. In either case, fall through to trying to
10044 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010046}
10047
Douglas Gregor063daf62009-03-13 18:40:31 +000010048/// \brief Create a binary operation that may resolve to an overloaded
10049/// operator.
10050///
10051/// \param OpLoc The location of the operator itself (e.g., '+').
10052///
10053/// \param OpcIn The BinaryOperator::Opcode that describes this
10054/// operator.
10055///
10056/// \param Functions The set of non-member functions that will be
10057/// considered by overload resolution. The caller needs to build this
10058/// set based on the context using, e.g.,
10059/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10060/// set should not contain any member functions; those will be added
10061/// by CreateOverloadedBinOp().
10062///
10063/// \param LHS Left-hand argument.
10064/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010065ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010066Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010067 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010068 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010069 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010070 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010071 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010072
10073 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10074 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10075 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10076
10077 // If either side is type-dependent, create an appropriate dependent
10078 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010079 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010080 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010081 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010082 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010083 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010084 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010085 Context.DependentTy,
10086 VK_RValue, OK_Ordinary,
10087 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010088
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010089 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10090 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010091 VK_LValue,
10092 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010093 Context.DependentTy,
10094 Context.DependentTy,
10095 OpLoc));
10096 }
John McCall6e266892010-01-26 03:27:55 +000010097
10098 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010099 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010100 // TODO: provide better source location info in DNLoc component.
10101 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010102 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010103 = UnresolvedLookupExpr::Create(Context, NamingClass,
10104 NestedNameSpecifierLoc(), OpNameInfo,
10105 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010106 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +000010107 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +000010108 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +000010109 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010110 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +000010111 OpLoc));
10112 }
10113
John McCall5acb0c92011-10-17 18:40:02 +000010114 // Always do placeholder-like conversions on the RHS.
10115 if (checkPlaceholderForOverload(*this, Args[1]))
10116 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010117
John McCall3c3b7f92011-10-25 17:37:35 +000010118 // Do placeholder-like conversion on the LHS; note that we should
10119 // not get here with a PseudoObject LHS.
10120 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010121 if (checkPlaceholderForOverload(*this, Args[0]))
10122 return ExprError();
10123
Sebastian Redl275c2b42009-11-18 23:10:33 +000010124 // If this is the assignment operator, we only perform overload resolution
10125 // if the left-hand side is a class or enumeration type. This is actually
10126 // a hack. The standard requires that we do overload resolution between the
10127 // various built-in candidates, but as DR507 points out, this can lead to
10128 // problems. So we do it this way, which pretty much follows what GCC does.
10129 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010130 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010131 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010132
John McCall0e800c92010-12-04 08:14:53 +000010133 // If this is the .* operator, which is not overloadable, just
10134 // create a built-in binary operator.
10135 if (Opc == BO_PtrMemD)
10136 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10137
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010138 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010139 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010140
10141 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010142 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010143
10144 // Add operator candidates that are member functions.
10145 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10146
John McCall6e266892010-01-26 03:27:55 +000010147 // Add candidates from ADL.
10148 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010149 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010150 /*ExplicitTemplateArgs*/ 0,
10151 CandidateSet);
10152
Douglas Gregor063daf62009-03-13 18:40:31 +000010153 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010154 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010155
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010156 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10157
Douglas Gregor063daf62009-03-13 18:40:31 +000010158 // Perform overload resolution.
10159 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010160 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010161 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010162 // We found a built-in operator or an overloaded operator.
10163 FunctionDecl *FnDecl = Best->Function;
10164
10165 if (FnDecl) {
10166 // We matched an overloaded operator. Build a call to that
10167 // operator.
10168
Eli Friedman5f2987c2012-02-02 03:46:19 +000010169 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010170
Douglas Gregor063daf62009-03-13 18:40:31 +000010171 // Convert the arguments.
10172 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010173 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010174 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010175
Chandler Carruth6df868e2010-12-12 08:17:55 +000010176 ExprResult Arg1 =
10177 PerformCopyInitialization(
10178 InitializedEntity::InitializeParameter(Context,
10179 FnDecl->getParamDecl(0)),
10180 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010181 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010182 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010183
John Wiegley429bb272011-04-08 18:41:53 +000010184 ExprResult Arg0 =
10185 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10186 Best->FoundDecl, Method);
10187 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010188 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010189 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010190 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010191 } else {
10192 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010193 ExprResult Arg0 = PerformCopyInitialization(
10194 InitializedEntity::InitializeParameter(Context,
10195 FnDecl->getParamDecl(0)),
10196 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010197 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010198 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010199
Chandler Carruth6df868e2010-12-12 08:17:55 +000010200 ExprResult Arg1 =
10201 PerformCopyInitialization(
10202 InitializedEntity::InitializeParameter(Context,
10203 FnDecl->getParamDecl(1)),
10204 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010205 if (Arg1.isInvalid())
10206 return ExprError();
10207 Args[0] = LHS = Arg0.takeAs<Expr>();
10208 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010209 }
10210
John McCallb697e082010-05-06 18:15:07 +000010211 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10212
John McCallf89e55a2010-11-18 06:31:45 +000010213 // Determine the result type.
10214 QualType ResultTy = FnDecl->getResultType();
10215 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10216 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010217
10218 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010219 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10220 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010221 if (FnExpr.isInvalid())
10222 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010223
John McCall9ae2f072010-08-23 23:25:46 +000010224 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010225 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010226 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010227
10228 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010229 FnDecl))
10230 return ExprError();
10231
John McCall9ae2f072010-08-23 23:25:46 +000010232 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010233 } else {
10234 // We matched a built-in operator. Convert the arguments, then
10235 // break out so that we will build the appropriate built-in
10236 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010237 ExprResult ArgsRes0 =
10238 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10239 Best->Conversions[0], AA_Passing);
10240 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010241 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010242 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010243
John Wiegley429bb272011-04-08 18:41:53 +000010244 ExprResult ArgsRes1 =
10245 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10246 Best->Conversions[1], AA_Passing);
10247 if (ArgsRes1.isInvalid())
10248 return ExprError();
10249 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010250 break;
10251 }
10252 }
10253
Douglas Gregor33074752009-09-30 21:46:01 +000010254 case OR_No_Viable_Function: {
10255 // C++ [over.match.oper]p9:
10256 // If the operator is the operator , [...] and there are no
10257 // viable functions, then the operator is assumed to be the
10258 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010259 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010260 break;
10261
Chandler Carruth6df868e2010-12-12 08:17:55 +000010262 // For class as left operand for assignment or compound assigment
10263 // operator do not fall through to handling in built-in, but report that
10264 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010265 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010266 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010267 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010268 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10269 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010270 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010271 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010272 // This is an erroneous use of an operator which can be overloaded by
10273 // a non-member function. Check for non-member operators which were
10274 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010275 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010276 // FIXME: Recover by calling the found function.
10277 return ExprError();
10278
Douglas Gregor33074752009-09-30 21:46:01 +000010279 // No viable function; try to create a built-in operation, which will
10280 // produce an error. Then, show the non-viable candidates.
10281 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010283 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010284 "C++ binary operator overloading is missing candidates!");
10285 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010286 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010287 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010288 return move(Result);
10289 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010290
10291 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010292 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010293 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010294 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010295 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010296 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010297 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010298 return ExprError();
10299
10300 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010301 if (isImplicitlyDeleted(Best->Function)) {
10302 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10303 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10304 << getSpecialMember(Method)
10305 << BinaryOperator::getOpcodeStr(Opc)
10306 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010307
10308 if (getSpecialMember(Method) != CXXInvalid) {
10309 // The user probably meant to call this special member. Just
10310 // explain why it's deleted.
10311 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010312 return ExprError();
10313 }
10314 } else {
10315 Diag(OpLoc, diag::err_ovl_deleted_oper)
10316 << Best->Function->isDeleted()
10317 << BinaryOperator::getOpcodeStr(Opc)
10318 << getDeletedOrUnavailableSuffix(Best->Function)
10319 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10320 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010321 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010322 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010323 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010324 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010325
Douglas Gregor33074752009-09-30 21:46:01 +000010326 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010327 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010328}
10329
John McCall60d7b3a2010-08-24 06:29:42 +000010330ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010331Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10332 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010333 Expr *Base, Expr *Idx) {
10334 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010335 DeclarationName OpName =
10336 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10337
10338 // If either side is type-dependent, create an appropriate dependent
10339 // expression.
10340 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10341
John McCallc373d482010-01-27 01:50:18 +000010342 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010343 // CHECKME: no 'operator' keyword?
10344 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10345 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010346 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010347 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010348 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010349 /*ADL*/ true, /*Overloaded*/ false,
10350 UnresolvedSetIterator(),
10351 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010352 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010353
Sebastian Redlf322ed62009-10-29 20:17:01 +000010354 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10355 Args, 2,
10356 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010357 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010358 RLoc));
10359 }
10360
John McCall5acb0c92011-10-17 18:40:02 +000010361 // Handle placeholders on both operands.
10362 if (checkPlaceholderForOverload(*this, Args[0]))
10363 return ExprError();
10364 if (checkPlaceholderForOverload(*this, Args[1]))
10365 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010366
Sebastian Redlf322ed62009-10-29 20:17:01 +000010367 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010368 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010369
10370 // Subscript can only be overloaded as a member function.
10371
10372 // Add operator candidates that are member functions.
10373 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10374
10375 // Add builtin operator candidates.
10376 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10377
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10379
Sebastian Redlf322ed62009-10-29 20:17:01 +000010380 // Perform overload resolution.
10381 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010382 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010383 case OR_Success: {
10384 // We found a built-in operator or an overloaded operator.
10385 FunctionDecl *FnDecl = Best->Function;
10386
10387 if (FnDecl) {
10388 // We matched an overloaded operator. Build a call to that
10389 // operator.
10390
Eli Friedman5f2987c2012-02-02 03:46:19 +000010391 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010392
John McCall9aa472c2010-03-19 07:35:19 +000010393 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010394 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010395
Sebastian Redlf322ed62009-10-29 20:17:01 +000010396 // Convert the arguments.
10397 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010398 ExprResult Arg0 =
10399 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10400 Best->FoundDecl, Method);
10401 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010402 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010403 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010404
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010405 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010406 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010407 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010408 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010409 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010410 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010411 Owned(Args[1]));
10412 if (InputInit.isInvalid())
10413 return ExprError();
10414
10415 Args[1] = InputInit.takeAs<Expr>();
10416
Sebastian Redlf322ed62009-10-29 20:17:01 +000010417 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010418 QualType ResultTy = FnDecl->getResultType();
10419 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10420 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010421
10422 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010423 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10424 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010425 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10426 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010427 OpLocInfo.getLoc(),
10428 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010429 if (FnExpr.isInvalid())
10430 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010431
John McCall9ae2f072010-08-23 23:25:46 +000010432 CXXOperatorCallExpr *TheCall =
10433 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010434 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010435 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010436
John McCall9ae2f072010-08-23 23:25:46 +000010437 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010438 FnDecl))
10439 return ExprError();
10440
John McCall9ae2f072010-08-23 23:25:46 +000010441 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010442 } else {
10443 // We matched a built-in operator. Convert the arguments, then
10444 // break out so that we will build the appropriate built-in
10445 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010446 ExprResult ArgsRes0 =
10447 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10448 Best->Conversions[0], AA_Passing);
10449 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010450 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010451 Args[0] = ArgsRes0.take();
10452
10453 ExprResult ArgsRes1 =
10454 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10455 Best->Conversions[1], AA_Passing);
10456 if (ArgsRes1.isInvalid())
10457 return ExprError();
10458 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010459
10460 break;
10461 }
10462 }
10463
10464 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010465 if (CandidateSet.empty())
10466 Diag(LLoc, diag::err_ovl_no_oper)
10467 << Args[0]->getType() << /*subscript*/ 0
10468 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10469 else
10470 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10471 << Args[0]->getType()
10472 << 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);
John McCall1eb3e102010-01-07 02:04:15 +000010475 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010476 }
10477
10478 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010479 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010480 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010481 << Args[0]->getType() << Args[1]->getType()
10482 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010483 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010484 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010485 return ExprError();
10486
10487 case OR_Deleted:
10488 Diag(LLoc, diag::err_ovl_deleted_oper)
10489 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010490 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010491 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010492 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010493 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010494 return ExprError();
10495 }
10496
10497 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010498 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010499}
10500
Douglas Gregor88a35142008-12-22 05:46:06 +000010501/// BuildCallToMemberFunction - Build a call to a member
10502/// function. MemExpr is the expression that refers to the member
10503/// function (and includes the object parameter), Args/NumArgs are the
10504/// arguments to the function call (not including the object
10505/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010506/// expression refers to a non-static member function or an overloaded
10507/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010508ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010509Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10510 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010511 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010512 assert(MemExprE->getType() == Context.BoundMemberTy ||
10513 MemExprE->getType() == Context.OverloadTy);
10514
Douglas Gregor88a35142008-12-22 05:46:06 +000010515 // Dig out the member expression. This holds both the object
10516 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010517 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010518
John McCall864c0412011-04-26 20:42:42 +000010519 // Determine whether this is a call to a pointer-to-member function.
10520 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10521 assert(op->getType() == Context.BoundMemberTy);
10522 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10523
10524 QualType fnType =
10525 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10526
10527 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10528 QualType resultType = proto->getCallResultType(Context);
10529 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10530
10531 // Check that the object type isn't more qualified than the
10532 // member function we're calling.
10533 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10534
10535 QualType objectType = op->getLHS()->getType();
10536 if (op->getOpcode() == BO_PtrMemI)
10537 objectType = objectType->castAs<PointerType>()->getPointeeType();
10538 Qualifiers objectQuals = objectType.getQualifiers();
10539
10540 Qualifiers difference = objectQuals - funcQuals;
10541 difference.removeObjCGCAttr();
10542 difference.removeAddressSpace();
10543 if (difference) {
10544 std::string qualsString = difference.getAsString();
10545 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10546 << fnType.getUnqualifiedType()
10547 << qualsString
10548 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10549 }
10550
10551 CXXMemberCallExpr *call
10552 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10553 resultType, valueKind, RParenLoc);
10554
10555 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010556 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010557 call, 0))
10558 return ExprError();
10559
10560 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10561 return ExprError();
10562
10563 return MaybeBindToTemporary(call);
10564 }
10565
John McCall5acb0c92011-10-17 18:40:02 +000010566 UnbridgedCastsSet UnbridgedCasts;
10567 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10568 return ExprError();
10569
John McCall129e2df2009-11-30 22:42:35 +000010570 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010571 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010572 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010573 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010574 if (isa<MemberExpr>(NakedMemExpr)) {
10575 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010576 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010577 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010578 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010579 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010580 } else {
10581 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010582 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010583
John McCall701c89e2009-12-03 04:06:58 +000010584 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010585 Expr::Classification ObjectClassification
10586 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10587 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010588
Douglas Gregor88a35142008-12-22 05:46:06 +000010589 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010590 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010591
John McCallaa81e162009-12-01 22:10:20 +000010592 // FIXME: avoid copy.
10593 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10594 if (UnresExpr->hasExplicitTemplateArgs()) {
10595 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10596 TemplateArgs = &TemplateArgsBuffer;
10597 }
10598
John McCall129e2df2009-11-30 22:42:35 +000010599 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10600 E = UnresExpr->decls_end(); I != E; ++I) {
10601
John McCall701c89e2009-12-03 04:06:58 +000010602 NamedDecl *Func = *I;
10603 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10604 if (isa<UsingShadowDecl>(Func))
10605 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10606
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010607
Francois Pichetdbee3412011-01-18 05:04:39 +000010608 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010609 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010610 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10611 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010612 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010613 // If explicit template arguments were provided, we can't call a
10614 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010615 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010616 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010617
John McCall9aa472c2010-03-19 07:35:19 +000010618 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010619 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010620 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010621 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010622 } else {
John McCall129e2df2009-11-30 22:42:35 +000010623 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010624 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010625 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010626 llvm::makeArrayRef(Args, NumArgs),
10627 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010628 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010629 }
Douglas Gregordec06662009-08-21 18:42:58 +000010630 }
Mike Stump1eb44332009-09-09 15:08:12 +000010631
John McCall129e2df2009-11-30 22:42:35 +000010632 DeclarationName DeclName = UnresExpr->getMemberName();
10633
John McCall5acb0c92011-10-17 18:40:02 +000010634 UnbridgedCasts.restore();
10635
Douglas Gregor88a35142008-12-22 05:46:06 +000010636 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010637 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010638 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010639 case OR_Success:
10640 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010641 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010642 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010643 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010644 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010645 break;
10646
10647 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010648 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010649 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010650 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10652 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010653 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010654 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010655
10656 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010657 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010658 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010659 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10660 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010661 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010662 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010663
10664 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010665 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010666 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010667 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010668 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010669 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010670 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10671 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010672 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010673 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010674 }
10675
John McCall6bb80172010-03-30 21:47:33 +000010676 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010677
John McCallaa81e162009-12-01 22:10:20 +000010678 // If overload resolution picked a static member, build a
10679 // non-member call based on that function.
10680 if (Method->isStatic()) {
10681 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10682 Args, NumArgs, RParenLoc);
10683 }
10684
John McCall129e2df2009-11-30 22:42:35 +000010685 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010686 }
10687
John McCallf89e55a2010-11-18 06:31:45 +000010688 QualType ResultType = Method->getResultType();
10689 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10690 ResultType = ResultType.getNonLValueExprType(Context);
10691
Douglas Gregor88a35142008-12-22 05:46:06 +000010692 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010693 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010694 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010695 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010696
Anders Carlssoneed3e692009-10-10 00:06:20 +000010697 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010698 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010699 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010700 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010701
Douglas Gregor88a35142008-12-22 05:46:06 +000010702 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010703 // We only need to do this if there was actually an overload; otherwise
10704 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010705 if (!Method->isStatic()) {
10706 ExprResult ObjectArg =
10707 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10708 FoundDecl, Method);
10709 if (ObjectArg.isInvalid())
10710 return ExprError();
10711 MemExpr->setBase(ObjectArg.take());
10712 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010713
10714 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010715 const FunctionProtoType *Proto =
10716 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010717 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010718 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010719 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010720
Eli Friedmane61eb042012-02-18 04:48:30 +000010721 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10722
Richard Smith7d96f612012-06-21 01:08:35 +000010723 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010724 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010725
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010726 if ((isa<CXXConstructorDecl>(CurContext) ||
10727 isa<CXXDestructorDecl>(CurContext)) &&
10728 TheCall->getMethodDecl()->isPure()) {
10729 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10730
Chandler Carruthae198062011-06-27 08:31:58 +000010731 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010732 Diag(MemExpr->getLocStart(),
10733 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10734 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10735 << MD->getParent()->getDeclName();
10736
10737 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010738 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010739 }
John McCall9ae2f072010-08-23 23:25:46 +000010740 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010741}
10742
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010743/// BuildCallToObjectOfClassType - Build a call to an object of class
10744/// type (C++ [over.call.object]), which can end up invoking an
10745/// overloaded function call operator (@c operator()) or performing a
10746/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010747ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010748Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010749 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010750 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010751 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010752 if (checkPlaceholderForOverload(*this, Obj))
10753 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010754 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010755
10756 UnbridgedCastsSet UnbridgedCasts;
10757 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10758 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010759
John Wiegley429bb272011-04-08 18:41:53 +000010760 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10761 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010762
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010763 // C++ [over.call.object]p1:
10764 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010765 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010766 // candidate functions includes at least the function call
10767 // operators of T. The function call operators of T are obtained by
10768 // ordinary lookup of the name operator() in the context of
10769 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010770 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010771 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010772
John Wiegley429bb272011-04-08 18:41:53 +000010773 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010774 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010775 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010776
John McCalla24dc2e2009-11-17 02:14:36 +000010777 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10778 LookupQualifiedName(R, Record->getDecl());
10779 R.suppressDiagnostics();
10780
Douglas Gregor593564b2009-11-15 07:48:03 +000010781 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010782 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010783 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10784 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010785 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010787
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010788 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010789 // In addition, for each (non-explicit in C++0x) conversion function
10790 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010791 //
10792 // operator conversion-type-id () cv-qualifier;
10793 //
10794 // where cv-qualifier is the same cv-qualification as, or a
10795 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010796 // denotes the type "pointer to function of (P1,...,Pn) returning
10797 // R", or the type "reference to pointer to function of
10798 // (P1,...,Pn) returning R", or the type "reference to function
10799 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010800 // is also considered as a candidate function. Similarly,
10801 // surrogate call functions are added to the set of candidate
10802 // functions for each conversion function declared in an
10803 // accessible base class provided the function is not hidden
10804 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010805 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010806 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010807 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010808 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010809 NamedDecl *D = *I;
10810 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10811 if (isa<UsingShadowDecl>(D))
10812 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010813
Douglas Gregor4a27d702009-10-21 06:18:39 +000010814 // Skip over templated conversion functions; they aren't
10815 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010816 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010817 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010818
John McCall701c89e2009-12-03 04:06:58 +000010819 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010820 if (!Conv->isExplicit()) {
10821 // Strip the reference type (if any) and then the pointer type (if
10822 // any) to get down to what might be a function type.
10823 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10824 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10825 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010826
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010827 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10828 {
10829 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010830 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10831 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010832 }
10833 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010834 }
Mike Stump1eb44332009-09-09 15:08:12 +000010835
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010836 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10837
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010838 // Perform overload resolution.
10839 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010840 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010841 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010842 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010843 // Overload resolution succeeded; we'll build the appropriate call
10844 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010845 break;
10846
10847 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010848 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010849 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010850 << Object.get()->getType() << /*call*/ 1
10851 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010852 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010853 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010854 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010855 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10857 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010858 break;
10859
10860 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010861 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010862 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010863 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010864 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10865 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010866 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010867
10868 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010869 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010870 diag::err_ovl_deleted_object_call)
10871 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010872 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010873 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010874 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010875 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10876 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010877 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010878 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010879
Douglas Gregorff331c12010-07-25 18:17:45 +000010880 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010881 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010882
John McCall5acb0c92011-10-17 18:40:02 +000010883 UnbridgedCasts.restore();
10884
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010885 if (Best->Function == 0) {
10886 // Since there is no function declaration, this is one of the
10887 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010888 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010889 = cast<CXXConversionDecl>(
10890 Best->Conversions[0].UserDefined.ConversionFunction);
10891
John Wiegley429bb272011-04-08 18:41:53 +000010892 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010893 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010894
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010895 // We selected one of the surrogate functions that converts the
10896 // object parameter to a function pointer. Perform the conversion
10897 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010898
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010899 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010900 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010901 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10902 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010903 if (Call.isInvalid())
10904 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010905 // Record usage of conversion in an implicit cast.
10906 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10907 CK_UserDefinedConversion,
10908 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010909
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010910 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010911 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010912 }
10913
Eli Friedman5f2987c2012-02-02 03:46:19 +000010914 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010915 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010916 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010917
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010918 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10919 // that calls this method, using Object for the implicit object
10920 // parameter and passing along the remaining arguments.
10921 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010922 const FunctionProtoType *Proto =
10923 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010924
10925 unsigned NumArgsInProto = Proto->getNumArgs();
10926 unsigned NumArgsToCheck = NumArgs;
10927
10928 // Build the full argument list for the method call (the
10929 // implicit object parameter is placed at the beginning of the
10930 // list).
10931 Expr **MethodArgs;
10932 if (NumArgs < NumArgsInProto) {
10933 NumArgsToCheck = NumArgsInProto;
10934 MethodArgs = new Expr*[NumArgsInProto + 1];
10935 } else {
10936 MethodArgs = new Expr*[NumArgs + 1];
10937 }
John Wiegley429bb272011-04-08 18:41:53 +000010938 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010939 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10940 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010941
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010942 DeclarationNameInfo OpLocInfo(
10943 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10944 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010945 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010946 HadMultipleCandidates,
10947 OpLocInfo.getLoc(),
10948 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010949 if (NewFn.isInvalid())
10950 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010951
10952 // Once we've built TheCall, all of the expressions are properly
10953 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010954 QualType ResultTy = Method->getResultType();
10955 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10956 ResultTy = ResultTy.getNonLValueExprType(Context);
10957
John McCall9ae2f072010-08-23 23:25:46 +000010958 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010959 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010960 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010961 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010962 delete [] MethodArgs;
10963
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010964 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010965 Method))
10966 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010967
Douglas Gregor518fda12009-01-13 05:10:00 +000010968 // We may have default arguments. If so, we need to allocate more
10969 // slots in the call for them.
10970 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010971 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010972 else if (NumArgs > NumArgsInProto)
10973 NumArgsToCheck = NumArgsInProto;
10974
Chris Lattner312531a2009-04-12 08:11:20 +000010975 bool IsError = false;
10976
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010977 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010978 ExprResult ObjRes =
10979 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10980 Best->FoundDecl, Method);
10981 if (ObjRes.isInvalid())
10982 IsError = true;
10983 else
10984 Object = move(ObjRes);
10985 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010986
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010987 // Check the argument types.
10988 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010989 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010990 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010991 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010992
Douglas Gregor518fda12009-01-13 05:10:00 +000010993 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010994
John McCall60d7b3a2010-08-24 06:29:42 +000010995 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010996 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010997 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010998 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010999 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011000
Anders Carlsson3faa4862010-01-29 18:43:53 +000011001 IsError |= InputInit.isInvalid();
11002 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011003 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011004 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011005 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11006 if (DefArg.isInvalid()) {
11007 IsError = true;
11008 break;
11009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011010
Douglas Gregord47c47d2009-11-09 19:27:57 +000011011 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011012 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011013
11014 TheCall->setArg(i + 1, Arg);
11015 }
11016
11017 // If this is a variadic call, handle args passed through "...".
11018 if (Proto->isVariadic()) {
11019 // Promote the arguments (C99 6.5.2.2p7).
11020 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011021 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11022 IsError |= Arg.isInvalid();
11023 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011024 }
11025 }
11026
Chris Lattner312531a2009-04-12 08:11:20 +000011027 if (IsError) return true;
11028
Eli Friedmane61eb042012-02-18 04:48:30 +000011029 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11030
Richard Smith7d96f612012-06-21 01:08:35 +000011031 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011032 return true;
11033
John McCall182f7092010-08-24 06:09:16 +000011034 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011035}
11036
Douglas Gregor8ba10742008-11-20 16:27:02 +000011037/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011038/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011039/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011040ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011041Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011042 assert(Base->getType()->isRecordType() &&
11043 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011044
John McCall5acb0c92011-10-17 18:40:02 +000011045 if (checkPlaceholderForOverload(*this, Base))
11046 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011047
John McCall5769d612010-02-08 23:07:23 +000011048 SourceLocation Loc = Base->getExprLoc();
11049
Douglas Gregor8ba10742008-11-20 16:27:02 +000011050 // C++ [over.ref]p1:
11051 //
11052 // [...] An expression x->m is interpreted as (x.operator->())->m
11053 // for a class object x of type T if T::operator->() exists and if
11054 // the operator is selected as the best match function by the
11055 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011056 DeclarationName OpName =
11057 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011058 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011059 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011060
John McCall5769d612010-02-08 23:07:23 +000011061 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011062 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011063 return ExprError();
11064
John McCalla24dc2e2009-11-17 02:14:36 +000011065 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11066 LookupQualifiedName(R, BaseRecord->getDecl());
11067 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011068
11069 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011070 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011071 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11072 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011073 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011074
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011075 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11076
Douglas Gregor8ba10742008-11-20 16:27:02 +000011077 // Perform overload resolution.
11078 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011079 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011080 case OR_Success:
11081 // Overload resolution succeeded; we'll build the call below.
11082 break;
11083
11084 case OR_No_Viable_Function:
11085 if (CandidateSet.empty())
11086 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011087 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011088 else
11089 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011090 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011091 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011092 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011093
11094 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011095 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11096 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011097 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011098 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011099
11100 case OR_Deleted:
11101 Diag(OpLoc, diag::err_ovl_deleted_oper)
11102 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011103 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011104 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011105 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011106 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011107 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011108 }
11109
Eli Friedman5f2987c2012-02-02 03:46:19 +000011110 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011111 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011112 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011113
Douglas Gregor8ba10742008-11-20 16:27:02 +000011114 // Convert the object parameter.
11115 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011116 ExprResult BaseResult =
11117 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11118 Best->FoundDecl, Method);
11119 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011120 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011121 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011122
Douglas Gregor8ba10742008-11-20 16:27:02 +000011123 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011124 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011125 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011126 if (FnExpr.isInvalid())
11127 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011128
John McCallf89e55a2010-11-18 06:31:45 +000011129 QualType ResultTy = Method->getResultType();
11130 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11131 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011132 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011133 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000011134 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011135
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011136 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011137 Method))
11138 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011139
11140 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011141}
11142
Richard Smith36f5cfe2012-03-09 08:00:36 +000011143/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11144/// a literal operator described by the provided lookup results.
11145ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11146 DeclarationNameInfo &SuffixInfo,
11147 ArrayRef<Expr*> Args,
11148 SourceLocation LitEndLoc,
11149 TemplateArgumentListInfo *TemplateArgs) {
11150 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011151
Richard Smith36f5cfe2012-03-09 08:00:36 +000011152 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11153 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11154 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011155
Richard Smith36f5cfe2012-03-09 08:00:36 +000011156 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11157
Richard Smith36f5cfe2012-03-09 08:00:36 +000011158 // Perform overload resolution. This will usually be trivial, but might need
11159 // to perform substitutions for a literal operator template.
11160 OverloadCandidateSet::iterator Best;
11161 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11162 case OR_Success:
11163 case OR_Deleted:
11164 break;
11165
11166 case OR_No_Viable_Function:
11167 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11168 << R.getLookupName();
11169 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11170 return ExprError();
11171
11172 case OR_Ambiguous:
11173 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11174 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11175 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011176 }
11177
Richard Smith36f5cfe2012-03-09 08:00:36 +000011178 FunctionDecl *FD = Best->Function;
11179 MarkFunctionReferenced(UDSuffixLoc, FD);
11180 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011181
Richard Smith36f5cfe2012-03-09 08:00:36 +000011182 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11183 SuffixInfo.getLoc(),
11184 SuffixInfo.getInfo());
11185 if (Fn.isInvalid())
11186 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011187
11188 // Check the argument types. This should almost always be a no-op, except
11189 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011190 Expr *ConvArgs[2];
11191 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11192 ExprResult InputInit = PerformCopyInitialization(
11193 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11194 SourceLocation(), Args[ArgIdx]);
11195 if (InputInit.isInvalid())
11196 return true;
11197 ConvArgs[ArgIdx] = InputInit.take();
11198 }
11199
Richard Smith9fcce652012-03-07 08:35:16 +000011200 QualType ResultTy = FD->getResultType();
11201 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11202 ResultTy = ResultTy.getNonLValueExprType(Context);
11203
Richard Smith9fcce652012-03-07 08:35:16 +000011204 UserDefinedLiteral *UDL =
11205 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11206 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11207
11208 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11209 return ExprError();
11210
Richard Smith7d96f612012-06-21 01:08:35 +000011211 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011212 return ExprError();
11213
11214 return MaybeBindToTemporary(UDL);
11215}
11216
Douglas Gregor904eed32008-11-10 20:40:00 +000011217/// FixOverloadedFunctionReference - E is an expression that refers to
11218/// a C++ overloaded function (possibly with some parentheses and
11219/// perhaps a '&' around it). We have resolved the overloaded function
11220/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011221/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011222Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011223 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011224 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011225 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11226 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011227 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011228 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011229
Douglas Gregor699ee522009-11-20 19:42:02 +000011230 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011231 }
11232
Douglas Gregor699ee522009-11-20 19:42:02 +000011233 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011234 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11235 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011236 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011237 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011238 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011239 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011240 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011241 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011242
11243 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011244 ICE->getCastKind(),
11245 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011246 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011247 }
11248
Douglas Gregor699ee522009-11-20 19:42:02 +000011249 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011250 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011251 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11253 if (Method->isStatic()) {
11254 // Do nothing: static member functions aren't any different
11255 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011256 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011257 // Fix the sub expression, which really has to be an
11258 // UnresolvedLookupExpr holding an overloaded member function
11259 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011260 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11261 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011262 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011263 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011264
John McCallba135432009-11-21 08:51:07 +000011265 assert(isa<DeclRefExpr>(SubExpr)
11266 && "fixed to something other than a decl ref");
11267 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11268 && "fixed to a member ref with no nested name qualifier");
11269
11270 // We have taken the address of a pointer to member
11271 // function. Perform the computation here so that we get the
11272 // appropriate pointer to member type.
11273 QualType ClassType
11274 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11275 QualType MemPtrType
11276 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11277
John McCallf89e55a2010-11-18 06:31:45 +000011278 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11279 VK_RValue, OK_Ordinary,
11280 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011281 }
11282 }
John McCall6bb80172010-03-30 21:47:33 +000011283 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11284 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011285 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011286 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011287
John McCall2de56d12010-08-25 11:45:40 +000011288 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011289 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011290 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011291 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011292 }
John McCallba135432009-11-21 08:51:07 +000011293
11294 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011295 // FIXME: avoid copy.
11296 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011297 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011298 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11299 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011300 }
11301
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011302 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11303 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011304 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011305 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011306 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011307 ULE->getNameLoc(),
11308 Fn->getType(),
11309 VK_LValue,
11310 Found.getDecl(),
11311 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011312 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011313 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11314 return DRE;
John McCallba135432009-11-21 08:51:07 +000011315 }
11316
John McCall129e2df2009-11-30 22:42:35 +000011317 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011318 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011319 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11320 if (MemExpr->hasExplicitTemplateArgs()) {
11321 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11322 TemplateArgs = &TemplateArgsBuffer;
11323 }
John McCalld5532b62009-11-23 01:53:49 +000011324
John McCallaa81e162009-12-01 22:10:20 +000011325 Expr *Base;
11326
John McCallf89e55a2010-11-18 06:31:45 +000011327 // If we're filling in a static method where we used to have an
11328 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011329 if (MemExpr->isImplicitAccess()) {
11330 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011331 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11332 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011333 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011334 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011335 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011336 MemExpr->getMemberLoc(),
11337 Fn->getType(),
11338 VK_LValue,
11339 Found.getDecl(),
11340 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011341 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011342 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11343 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011344 } else {
11345 SourceLocation Loc = MemExpr->getMemberLoc();
11346 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011347 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011348 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011349 Base = new (Context) CXXThisExpr(Loc,
11350 MemExpr->getBaseType(),
11351 /*isImplicit=*/true);
11352 }
John McCallaa81e162009-12-01 22:10:20 +000011353 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011354 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011355
John McCallf5307512011-04-27 00:36:17 +000011356 ExprValueKind valueKind;
11357 QualType type;
11358 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11359 valueKind = VK_LValue;
11360 type = Fn->getType();
11361 } else {
11362 valueKind = VK_RValue;
11363 type = Context.BoundMemberTy;
11364 }
11365
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011366 MemberExpr *ME = MemberExpr::Create(Context, Base,
11367 MemExpr->isArrow(),
11368 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011369 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011370 Fn,
11371 Found,
11372 MemExpr->getMemberNameInfo(),
11373 TemplateArgs,
11374 type, valueKind, OK_Ordinary);
11375 ME->setHadMultipleCandidates(true);
11376 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011377 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011378
John McCall3fa5cae2010-10-26 07:05:15 +000011379 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011380}
11381
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011382ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011383 DeclAccessPair Found,
11384 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011385 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011386}
11387
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011388} // end namespace clang