blob: 994471ab5c5675a678673d960cca9eb49cefbe23 [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 ||
392 (FromWidth == ToWidth && FromSigned != ToSigned)) {
393 // Not all values of FromType can be represented in ToType.
394 llvm::APSInt InitializerValue;
395 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
396 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
397 ConstantValue = APValue(InitializerValue);
398
399 // Add a bit to the InitializerValue so we don't have to worry about
400 // signed vs. unsigned comparisons.
401 InitializerValue = InitializerValue.extend(
402 InitializerValue.getBitWidth() + 1);
403 // Convert the initializer to and from the target width and signed-ness.
404 llvm::APSInt ConvertedValue = InitializerValue;
405 ConvertedValue = ConvertedValue.trunc(ToWidth);
406 ConvertedValue.setIsSigned(ToSigned);
407 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
408 ConvertedValue.setIsSigned(InitializerValue.isSigned());
409 // If the result is different, this was a narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000410 if (ConvertedValue != InitializerValue) {
411 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000412 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000413 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000414 } else {
415 // Variables are always narrowings.
416 return NK_Variable_Narrowing;
417 }
418 }
419 return NK_Not_Narrowing;
420 }
421
422 default:
423 // Other kinds of conversions are not narrowings.
424 return NK_Not_Narrowing;
425 }
426}
427
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000428/// DebugPrint - Print this standard conversion sequence to standard
429/// error. Useful for debugging overloading issues.
430void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000431 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432 bool PrintedSomething = false;
433 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000434 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000435 PrintedSomething = true;
436 }
437
438 if (Second != ICK_Identity) {
439 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000440 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000442 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000443
444 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000445 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000446 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000447 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000448 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000450 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (Third != ICK_Identity) {
455 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000459 PrintedSomething = true;
460 }
461
462 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
465}
466
467/// DebugPrint - Print this user-defined conversion sequence to standard
468/// error. Useful for debugging overloading issues.
469void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000470 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471 if (Before.First || Before.Second || Before.Third) {
472 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000473 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000475 if (ConversionFunction)
476 OS << '\'' << *ConversionFunction << '\'';
477 else
478 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000480 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 After.DebugPrint();
482 }
483}
484
485/// DebugPrint - Print this implicit conversion sequence to standard
486/// error. Useful for debugging overloading issues.
487void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000488 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 Standard.DebugPrint();
493 break;
494 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 UserDefined.DebugPrint();
497 break;
498 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000500 break;
John McCall1d318332010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000503 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510}
511
John McCall1d318332010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregora9333192010-05-08 17:41:32 +0000527namespace {
528 // Structure used by OverloadCandidate::DeductionFailureInfo to store
529 // template parameter and template argument information.
530 struct DFIParamWithArguments {
531 TemplateParameter Param;
532 TemplateArgument FirstArg;
533 TemplateArgument SecondArg;
534 };
535}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
Douglas Gregora9333192010-05-08 17:41:32 +0000537/// \brief Convert from Sema's representation of template deduction information
538/// to the form used in overload-candidate information.
539OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000540static MakeDeductionFailureInfo(ASTContext &Context,
541 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000542 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000543 OverloadCandidate::DeductionFailureInfo Result;
544 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000545 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000546 Result.Data = 0;
547 switch (TDK) {
548 case Sema::TDK_Success:
549 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000550 case Sema::TDK_TooManyArguments:
551 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000552 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553
Douglas Gregora9333192010-05-08 17:41:32 +0000554 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000555 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000556 Result.Data = Info.Param.getOpaqueValue();
557 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558
Douglas Gregora9333192010-05-08 17:41:32 +0000559 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000560 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000561 // FIXME: Should allocate from normal heap so that we can free this later.
562 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000563 Saved->Param = Info.Param;
564 Saved->FirstArg = Info.FirstArg;
565 Saved->SecondArg = Info.SecondArg;
566 Result.Data = Saved;
567 break;
568 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569
Douglas Gregora9333192010-05-08 17:41:32 +0000570 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000571 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000572 if (Info.hasSFINAEDiagnostic()) {
573 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
574 SourceLocation(), PartialDiagnostic::NullDiagnostic());
575 Info.takeSFINAEDiagnostic(*Diag);
576 Result.HasDiagnostic = true;
577 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000578 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregora9333192010-05-08 17:41:32 +0000580 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000581 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000583 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregora9333192010-05-08 17:41:32 +0000585 return Result;
586}
John McCall1d318332010-01-12 00:44:57 +0000587
Douglas Gregora9333192010-05-08 17:41:32 +0000588void OverloadCandidate::DeductionFailureInfo::Destroy() {
589 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
590 case Sema::TDK_Success:
591 case Sema::TDK_InstantiationDepth:
592 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000593 case Sema::TDK_TooManyArguments:
594 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000595 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000596 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Douglas Gregora9333192010-05-08 17:41:32 +0000598 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000599 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000600 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000601 Data = 0;
602 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000603
604 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000605 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000606 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000607 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
608 Diag->~PartialDiagnosticAt();
609 HasDiagnostic = false;
610 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000611 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000613 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000614 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000615 case Sema::TDK_FailedOverloadResolution:
616 break;
617 }
618}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000619
Richard Smithb8590f32012-05-07 09:03:25 +0000620PartialDiagnosticAt *
621OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
622 if (HasDiagnostic)
623 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
624 return 0;
625}
626
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000628OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000634 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000635 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000636
Douglas Gregora9333192010-05-08 17:41:32 +0000637 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000638 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000640
641 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000642 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000643 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000644
Douglas Gregora9333192010-05-08 17:41:32 +0000645 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000646 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000647 case Sema::TDK_FailedOverloadResolution:
648 break;
649 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000650
Douglas Gregora9333192010-05-08 17:41:32 +0000651 return TemplateParameter();
652}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000653
Douglas Gregorec20f462010-05-08 20:07:26 +0000654TemplateArgumentList *
655OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
656 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
657 case Sema::TDK_Success:
658 case Sema::TDK_InstantiationDepth:
659 case Sema::TDK_TooManyArguments:
660 case Sema::TDK_TooFewArguments:
661 case Sema::TDK_Incomplete:
662 case Sema::TDK_InvalidExplicitArguments:
663 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000665 return 0;
666
667 case Sema::TDK_SubstitutionFailure:
668 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669
Douglas Gregorec20f462010-05-08 20:07:26 +0000670 // Unhandled
671 case Sema::TDK_NonDeducedMismatch:
672 case Sema::TDK_FailedOverloadResolution:
673 break;
674 }
675
676 return 0;
677}
678
Douglas Gregora9333192010-05-08 17:41:32 +0000679const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681 case Sema::TDK_Success:
682 case Sema::TDK_InstantiationDepth:
683 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000684 case Sema::TDK_TooManyArguments:
685 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000686 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000687 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return 0;
689
Douglas Gregora9333192010-05-08 17:41:32 +0000690 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000691 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000692 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000693
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000694 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000695 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000696 case Sema::TDK_FailedOverloadResolution:
697 break;
698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699
Douglas Gregora9333192010-05-08 17:41:32 +0000700 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701}
Douglas Gregora9333192010-05-08 17:41:32 +0000702
703const TemplateArgument *
704OverloadCandidate::DeductionFailureInfo::getSecondArg() {
705 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
706 case Sema::TDK_Success:
707 case Sema::TDK_InstantiationDepth:
708 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000709 case Sema::TDK_TooManyArguments:
710 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000711 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000712 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000713 return 0;
714
Douglas Gregora9333192010-05-08 17:41:32 +0000715 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000716 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000717 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
718
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000719 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000720 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000721 case Sema::TDK_FailedOverloadResolution:
722 break;
723 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000724
Douglas Gregora9333192010-05-08 17:41:32 +0000725 return 0;
726}
727
728void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000729 for (iterator i = begin(), e = end(); i != e; ++i)
730 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
731 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000732 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000733 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000734 Functions.clear();
735}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000736
John McCall5acb0c92011-10-17 18:40:02 +0000737namespace {
738 class UnbridgedCastsSet {
739 struct Entry {
740 Expr **Addr;
741 Expr *Saved;
742 };
743 SmallVector<Entry, 2> Entries;
744
745 public:
746 void save(Sema &S, Expr *&E) {
747 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
748 Entry entry = { &E, E };
749 Entries.push_back(entry);
750 E = S.stripARCUnbridgedCast(E);
751 }
752
753 void restore() {
754 for (SmallVectorImpl<Entry>::iterator
755 i = Entries.begin(), e = Entries.end(); i != e; ++i)
756 *i->Addr = i->Saved;
757 }
758 };
759}
760
761/// checkPlaceholderForOverload - Do any interesting placeholder-like
762/// preprocessing on the given expression.
763///
764/// \param unbridgedCasts a collection to which to add unbridged casts;
765/// without this, they will be immediately diagnosed as errors
766///
767/// Return true on unrecoverable error.
768static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
769 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000770 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
771 // We can't handle overloaded expressions here because overload
772 // resolution might reasonably tweak them.
773 if (placeholder->getKind() == BuiltinType::Overload) return false;
774
775 // If the context potentially accepts unbridged ARC casts, strip
776 // the unbridged cast and add it to the collection for later restoration.
777 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
778 unbridgedCasts) {
779 unbridgedCasts->save(S, E);
780 return false;
781 }
782
783 // Go ahead and check everything else.
784 ExprResult result = S.CheckPlaceholderExpr(E);
785 if (result.isInvalid())
786 return true;
787
788 E = result.take();
789 return false;
790 }
791
792 // Nothing to do.
793 return false;
794}
795
796/// checkArgPlaceholdersForOverload - Check a set of call operands for
797/// placeholders.
798static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
799 unsigned numArgs,
800 UnbridgedCastsSet &unbridged) {
801 for (unsigned i = 0; i != numArgs; ++i)
802 if (checkPlaceholderForOverload(S, args[i], &unbridged))
803 return true;
804
805 return false;
806}
807
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000808// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000809// overload of the declarations in Old. This routine returns false if
810// New and Old cannot be overloaded, e.g., if New has the same
811// signature as some function in Old (C++ 1.3.10) or if the Old
812// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000813// it does return false, MatchedDecl will point to the decl that New
814// cannot be overloaded with. This decl may be a UsingShadowDecl on
815// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816//
817// Example: Given the following input:
818//
819// void f(int, float); // #1
820// void f(int, int); // #2
821// int f(int, int); // #3
822//
823// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000824// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000825//
John McCall51fa86f2009-12-02 08:47:38 +0000826// When we process #2, Old contains only the FunctionDecl for #1. By
827// comparing the parameter types, we see that #1 and #2 are overloaded
828// (since they have different signatures), so this routine returns
829// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000830//
John McCall51fa86f2009-12-02 08:47:38 +0000831// When we process #3, Old is an overload set containing #1 and #2. We
832// compare the signatures of #3 to #1 (they're overloaded, so we do
833// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
834// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000835// signature), IsOverload returns false and MatchedDecl will be set to
836// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000837//
838// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
839// into a class by a using declaration. The rules for whether to hide
840// shadow declarations ignore some properties which otherwise figure
841// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000842Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000843Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
844 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000845 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000846 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000847 NamedDecl *OldD = *I;
848
849 bool OldIsUsingDecl = false;
850 if (isa<UsingShadowDecl>(OldD)) {
851 OldIsUsingDecl = true;
852
853 // We can always introduce two using declarations into the same
854 // context, even if they have identical signatures.
855 if (NewIsUsingDecl) continue;
856
857 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
858 }
859
860 // If either declaration was introduced by a using declaration,
861 // we'll need to use slightly different rules for matching.
862 // Essentially, these rules are the normal rules, except that
863 // function templates hide function templates with different
864 // return types or template parameter lists.
865 bool UseMemberUsingDeclRules =
866 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
867
John McCall51fa86f2009-12-02 08:47:38 +0000868 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000869 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
870 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
871 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
872 continue;
873 }
874
John McCall871b2e72009-12-09 03:35:25 +0000875 Match = *I;
876 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000877 }
John McCall51fa86f2009-12-02 08:47:38 +0000878 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000879 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
880 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
881 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
882 continue;
883 }
884
John McCall871b2e72009-12-09 03:35:25 +0000885 Match = *I;
886 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000887 }
John McCalld7945c62010-11-10 03:01:53 +0000888 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000889 // We can overload with these, which can show up when doing
890 // redeclaration checks for UsingDecls.
891 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000892 } else if (isa<TagDecl>(OldD)) {
893 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000894 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
895 // Optimistically assume that an unresolved using decl will
896 // overload; if it doesn't, we'll have to diagnose during
897 // template instantiation.
898 } else {
John McCall68263142009-11-18 22:49:29 +0000899 // (C++ 13p1):
900 // Only function declarations can be overloaded; object and type
901 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000902 Match = *I;
903 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000904 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000905 }
John McCall68263142009-11-18 22:49:29 +0000906
John McCall871b2e72009-12-09 03:35:25 +0000907 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000908}
909
John McCallad00b772010-06-16 08:42:20 +0000910bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
911 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000912 // If both of the functions are extern "C", then they are not
913 // overloads.
914 if (Old->isExternC() && New->isExternC())
915 return false;
916
John McCall68263142009-11-18 22:49:29 +0000917 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
918 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
919
920 // C++ [temp.fct]p2:
921 // A function template can be overloaded with other function templates
922 // and with normal (non-template) functions.
923 if ((OldTemplate == 0) != (NewTemplate == 0))
924 return true;
925
926 // Is the function New an overload of the function Old?
927 QualType OldQType = Context.getCanonicalType(Old->getType());
928 QualType NewQType = Context.getCanonicalType(New->getType());
929
930 // Compare the signatures (C++ 1.3.10) of the two functions to
931 // determine whether they are overloads. If we find any mismatch
932 // in the signature, they are overloads.
933
934 // If either of these functions is a K&R-style function (no
935 // prototype), then we consider them to have matching signatures.
936 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
937 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
938 return false;
939
John McCallf4c73712011-01-19 06:33:43 +0000940 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
941 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000942
943 // The signature of a function includes the types of its
944 // parameters (C++ 1.3.10), which includes the presence or absence
945 // of the ellipsis; see C++ DR 357).
946 if (OldQType != NewQType &&
947 (OldType->getNumArgs() != NewType->getNumArgs() ||
948 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000949 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000950 return true;
951
952 // C++ [temp.over.link]p4:
953 // The signature of a function template consists of its function
954 // signature, its return type and its template parameter list. The names
955 // of the template parameters are significant only for establishing the
956 // relationship between the template parameters and the rest of the
957 // signature.
958 //
959 // We check the return type and template parameter lists for function
960 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000961 //
962 // However, we don't consider either of these when deciding whether
963 // a member introduced by a shadow declaration is hidden.
964 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000965 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
966 OldTemplate->getTemplateParameters(),
967 false, TPL_TemplateMatch) ||
968 OldType->getResultType() != NewType->getResultType()))
969 return true;
970
971 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000972 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000973 //
974 // As part of this, also check whether one of the member functions
975 // is static, in which case they are not overloads (C++
976 // 13.1p2). While not part of the definition of the signature,
977 // this check is important to determine whether these functions
978 // can be overloaded.
979 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
980 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
981 if (OldMethod && NewMethod &&
982 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000983 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000984 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
985 if (!UseUsingDeclRules &&
986 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
987 (OldMethod->getRefQualifier() == RQ_None ||
988 NewMethod->getRefQualifier() == RQ_None)) {
989 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000990 // - Member function declarations with the same name and the same
991 // parameter-type-list as well as member function template
992 // declarations with the same name, the same parameter-type-list, and
993 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000994 // them, but not all, have a ref-qualifier (8.3.5).
995 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
996 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
997 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999
John McCall68263142009-11-18 22:49:29 +00001000 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001001 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002
John McCall68263142009-11-18 22:49:29 +00001003 // The signatures match; this is not an overload.
1004 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005}
1006
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001007/// \brief Checks availability of the function depending on the current
1008/// function context. Inside an unavailable function, unavailability is ignored.
1009///
1010/// \returns true if \arg FD is unavailable and current context is inside
1011/// an available function, false otherwise.
1012bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1013 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1014}
1015
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001016/// \brief Tries a user-defined conversion from From to ToType.
1017///
1018/// Produces an implicit conversion sequence for when a standard conversion
1019/// is not an option. See TryImplicitConversion for more information.
1020static ImplicitConversionSequence
1021TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1022 bool SuppressUserConversions,
1023 bool AllowExplicit,
1024 bool InOverloadResolution,
1025 bool CStyle,
1026 bool AllowObjCWritebackConversion) {
1027 ImplicitConversionSequence ICS;
1028
1029 if (SuppressUserConversions) {
1030 // We're not in the case above, so there is no conversion that
1031 // we can perform.
1032 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1033 return ICS;
1034 }
1035
1036 // Attempt user-defined conversion.
1037 OverloadCandidateSet Conversions(From->getExprLoc());
1038 OverloadingResult UserDefResult
1039 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1040 AllowExplicit);
1041
1042 if (UserDefResult == OR_Success) {
1043 ICS.setUserDefined();
1044 // C++ [over.ics.user]p4:
1045 // A conversion of an expression of class type to the same class
1046 // type is given Exact Match rank, and a conversion of an
1047 // expression of class type to a base class of that type is
1048 // given Conversion rank, in spite of the fact that a copy
1049 // constructor (i.e., a user-defined conversion function) is
1050 // called for those cases.
1051 if (CXXConstructorDecl *Constructor
1052 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1053 QualType FromCanon
1054 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1055 QualType ToCanon
1056 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1057 if (Constructor->isCopyConstructor() &&
1058 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1059 // Turn this into a "standard" conversion sequence, so that it
1060 // gets ranked with standard conversion sequences.
1061 ICS.setStandard();
1062 ICS.Standard.setAsIdentityConversion();
1063 ICS.Standard.setFromType(From->getType());
1064 ICS.Standard.setAllToTypes(ToType);
1065 ICS.Standard.CopyConstructor = Constructor;
1066 if (ToCanon != FromCanon)
1067 ICS.Standard.Second = ICK_Derived_To_Base;
1068 }
1069 }
1070
1071 // C++ [over.best.ics]p4:
1072 // However, when considering the argument of a user-defined
1073 // conversion function that is a candidate by 13.3.1.3 when
1074 // invoked for the copying of the temporary in the second step
1075 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1076 // 13.3.1.6 in all cases, only standard conversion sequences and
1077 // ellipsis conversion sequences are allowed.
1078 if (SuppressUserConversions && ICS.isUserDefined()) {
1079 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1080 }
1081 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1082 ICS.setAmbiguous();
1083 ICS.Ambiguous.setFromType(From->getType());
1084 ICS.Ambiguous.setToType(ToType);
1085 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1086 Cand != Conversions.end(); ++Cand)
1087 if (Cand->Viable)
1088 ICS.Ambiguous.addConversion(Cand->Function);
1089 } else {
1090 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1091 }
1092
1093 return ICS;
1094}
1095
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001096/// TryImplicitConversion - Attempt to perform an implicit conversion
1097/// from the given expression (Expr) to the given type (ToType). This
1098/// function returns an implicit conversion sequence that can be used
1099/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001100///
1101/// void f(float f);
1102/// void g(int i) { f(i); }
1103///
1104/// this routine would produce an implicit conversion sequence to
1105/// describe the initialization of f from i, which will be a standard
1106/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1107/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1108//
1109/// Note that this routine only determines how the conversion can be
1110/// performed; it does not actually perform the conversion. As such,
1111/// it will not produce any diagnostics if no conversion is available,
1112/// but will instead return an implicit conversion sequence of kind
1113/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001114///
1115/// If @p SuppressUserConversions, then user-defined conversions are
1116/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001117/// If @p AllowExplicit, then explicit user-defined conversions are
1118/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001119///
1120/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1121/// writeback conversion, which allows __autoreleasing id* parameters to
1122/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001123static ImplicitConversionSequence
1124TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1125 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001127 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001128 bool CStyle,
1129 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001131 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001132 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001133 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001134 return ICS;
1135 }
1136
David Blaikie4e4d0842012-03-11 07:00:24 +00001137 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001138 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001139 return ICS;
1140 }
1141
Douglas Gregor604eb652010-08-11 02:15:33 +00001142 // C++ [over.ics.user]p4:
1143 // A conversion of an expression of class type to the same class
1144 // type is given Exact Match rank, and a conversion of an
1145 // expression of class type to a base class of that type is
1146 // given Conversion rank, in spite of the fact that a copy/move
1147 // constructor (i.e., a user-defined conversion function) is
1148 // called for those cases.
1149 QualType FromType = From->getType();
1150 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001151 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1152 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001153 ICS.setStandard();
1154 ICS.Standard.setAsIdentityConversion();
1155 ICS.Standard.setFromType(FromType);
1156 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001158 // We don't actually check at this point whether there is a valid
1159 // copy/move constructor, since overloading just assumes that it
1160 // exists. When we actually perform initialization, we'll find the
1161 // appropriate constructor to copy the returned object, if needed.
1162 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001163
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001164 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001165 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001166 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001167
Douglas Gregor604eb652010-08-11 02:15:33 +00001168 return ICS;
1169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001170
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001171 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1172 AllowExplicit, InOverloadResolution, CStyle,
1173 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001174}
1175
John McCallf85e1932011-06-15 23:02:42 +00001176ImplicitConversionSequence
1177Sema::TryImplicitConversion(Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
1179 bool AllowExplicit,
1180 bool InOverloadResolution,
1181 bool CStyle,
1182 bool AllowObjCWritebackConversion) {
1183 return clang::TryImplicitConversion(*this, From, ToType,
1184 SuppressUserConversions, AllowExplicit,
1185 InOverloadResolution, CStyle,
1186 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001187}
1188
Douglas Gregor575c63a2010-04-16 22:27:05 +00001189/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001190/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001191/// converted expression. Flavor is the kind of conversion we're
1192/// performing, used in the error message. If @p AllowExplicit,
1193/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001194ExprResult
1195Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001196 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001197 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001198 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001199}
1200
John Wiegley429bb272011-04-08 18:41:53 +00001201ExprResult
1202Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001203 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001204 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001205 if (checkPlaceholderForOverload(*this, From))
1206 return ExprError();
1207
John McCallf85e1932011-06-15 23:02:42 +00001208 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1209 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001211 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001212
John McCall120d63c2010-08-24 20:38:10 +00001213 ICS = clang::TryImplicitConversion(*this, From, ToType,
1214 /*SuppressUserConversions=*/false,
1215 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001216 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001217 /*CStyle=*/false,
1218 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001219 return PerformImplicitConversion(From, ToType, ICS, Action);
1220}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001221
1222/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001223/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001224bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1225 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001226 if (Context.hasSameUnqualifiedType(FromType, ToType))
1227 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001228
John McCall00ccbef2010-12-21 00:44:39 +00001229 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1230 // where F adds one of the following at most once:
1231 // - a pointer
1232 // - a member pointer
1233 // - a block pointer
1234 CanQualType CanTo = Context.getCanonicalType(ToType);
1235 CanQualType CanFrom = Context.getCanonicalType(FromType);
1236 Type::TypeClass TyClass = CanTo->getTypeClass();
1237 if (TyClass != CanFrom->getTypeClass()) return false;
1238 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1239 if (TyClass == Type::Pointer) {
1240 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1241 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1242 } else if (TyClass == Type::BlockPointer) {
1243 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1244 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1245 } else if (TyClass == Type::MemberPointer) {
1246 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1247 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1248 } else {
1249 return false;
1250 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001251
John McCall00ccbef2010-12-21 00:44:39 +00001252 TyClass = CanTo->getTypeClass();
1253 if (TyClass != CanFrom->getTypeClass()) return false;
1254 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1255 return false;
1256 }
1257
1258 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1259 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1260 if (!EInfo.getNoReturn()) return false;
1261
1262 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1263 assert(QualType(FromFn, 0).isCanonical());
1264 if (QualType(FromFn, 0) != CanTo) return false;
1265
1266 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001267 return true;
1268}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001270/// \brief Determine whether the conversion from FromType to ToType is a valid
1271/// vector conversion.
1272///
1273/// \param ICK Will be set to the vector conversion kind, if this is a vector
1274/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001275static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1276 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001277 // We need at least one of these types to be a vector type to have a vector
1278 // conversion.
1279 if (!ToType->isVectorType() && !FromType->isVectorType())
1280 return false;
1281
1282 // Identical types require no conversions.
1283 if (Context.hasSameUnqualifiedType(FromType, ToType))
1284 return false;
1285
1286 // There are no conversions between extended vector types, only identity.
1287 if (ToType->isExtVectorType()) {
1288 // There are no conversions between extended vector types other than the
1289 // identity conversion.
1290 if (FromType->isExtVectorType())
1291 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001293 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001294 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001295 ICK = ICK_Vector_Splat;
1296 return true;
1297 }
1298 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001299
1300 // We can perform the conversion between vector types in the following cases:
1301 // 1)vector types are equivalent AltiVec and GCC vector types
1302 // 2)lax vector conversions are permitted and the vector types are of the
1303 // same size
1304 if (ToType->isVectorType() && FromType->isVectorType()) {
1305 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001306 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001307 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001308 ICK = ICK_Vector_Conversion;
1309 return true;
1310 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001311 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001312
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001313 return false;
1314}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315
Douglas Gregor7d000652012-04-12 20:48:09 +00001316static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1317 bool InOverloadResolution,
1318 StandardConversionSequence &SCS,
1319 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001320
Douglas Gregor60d62c22008-10-31 16:23:19 +00001321/// IsStandardConversion - Determines whether there is a standard
1322/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1323/// expression From to the type ToType. Standard conversion sequences
1324/// only consider non-class types; for conversions that involve class
1325/// types, use TryImplicitConversion. If a conversion exists, SCS will
1326/// contain the standard conversion sequence required to perform this
1327/// conversion and this routine will return true. Otherwise, this
1328/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001329static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1330 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001331 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001332 bool CStyle,
1333 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001334 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001335
Douglas Gregor60d62c22008-10-31 16:23:19 +00001336 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001337 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001338 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001339 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001340 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001341 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342
Douglas Gregorf9201e02009-02-11 23:02:49 +00001343 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001344 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001345 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001346 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001347 return false;
1348
Mike Stump1eb44332009-09-09 15:08:12 +00001349 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001350 }
1351
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001352 // The first conversion can be an lvalue-to-rvalue conversion,
1353 // array-to-pointer conversion, or function-to-pointer conversion
1354 // (C++ 4p1).
1355
John McCall120d63c2010-08-24 20:38:10 +00001356 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001357 DeclAccessPair AccessPair;
1358 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001360 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001361 // We were able to resolve the address of the overloaded function,
1362 // so we can convert to the type of that function.
1363 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001364
1365 // we can sometimes resolve &foo<int> regardless of ToType, so check
1366 // if the type matches (identity) or we are converting to bool
1367 if (!S.Context.hasSameUnqualifiedType(
1368 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1369 QualType resultTy;
1370 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001371 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001372 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1373 // otherwise, only a boolean conversion is standard
1374 if (!ToType->isBooleanType())
1375 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001377
Chandler Carruth90434232011-03-29 08:08:18 +00001378 // Check if the "from" expression is taking the address of an overloaded
1379 // function and recompute the FromType accordingly. Take advantage of the
1380 // fact that non-static member functions *must* have such an address-of
1381 // expression.
1382 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1383 if (Method && !Method->isStatic()) {
1384 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1385 "Non-unary operator on non-static member address");
1386 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1387 == UO_AddrOf &&
1388 "Non-address-of operator on non-static member address");
1389 const Type *ClassType
1390 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1391 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001392 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1393 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1394 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001395 "Non-address-of operator for overloaded function expression");
1396 FromType = S.Context.getPointerType(FromType);
1397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001398
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001399 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001400 assert(S.Context.hasSameType(
1401 FromType,
1402 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001403 } else {
1404 return false;
1405 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001406 }
John McCall21480112011-08-30 00:57:29 +00001407 // Lvalue-to-rvalue conversion (C++11 4.1):
1408 // A glvalue (3.10) of a non-function, non-array type T can
1409 // be converted to a prvalue.
1410 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001411 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001412 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001413 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001414 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001415
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001416 // C11 6.3.2.1p2:
1417 // ... if the lvalue has atomic type, the value has the non-atomic version
1418 // of the type of the lvalue ...
1419 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1420 FromType = Atomic->getValueType();
1421
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001422 // If T is a non-class type, the type of the rvalue is the
1423 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001424 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1425 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001426 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001427 } else if (FromType->isArrayType()) {
1428 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001429 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430
1431 // An lvalue or rvalue of type "array of N T" or "array of unknown
1432 // bound of T" can be converted to an rvalue of type "pointer to
1433 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001434 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001435
John McCall120d63c2010-08-24 20:38:10 +00001436 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001437 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001438 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001439
1440 // For the purpose of ranking in overload resolution
1441 // (13.3.3.1.1), this conversion is considered an
1442 // array-to-pointer conversion followed by a qualification
1443 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001444 SCS.Second = ICK_Identity;
1445 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001446 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001447 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001448 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001449 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001450 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001451 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001452 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453
1454 // An lvalue of function type T can be converted to an rvalue of
1455 // type "pointer to T." The result is a pointer to the
1456 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001457 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001458 } else {
1459 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001460 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001461 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001462 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001463
1464 // The second conversion can be an integral promotion, floating
1465 // point promotion, integral conversion, floating point conversion,
1466 // floating-integral conversion, pointer conversion,
1467 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001468 // For overloading in C, this can also be a "compatible-type"
1469 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001470 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001471 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001472 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001473 // The unqualified versions of the types are the same: there's no
1474 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001475 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001476 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001478 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001479 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001480 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001481 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001482 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001484 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001485 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001486 SCS.Second = ICK_Complex_Promotion;
1487 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001488 } else if (ToType->isBooleanType() &&
1489 (FromType->isArithmeticType() ||
1490 FromType->isAnyPointerType() ||
1491 FromType->isBlockPointerType() ||
1492 FromType->isMemberPointerType() ||
1493 FromType->isNullPtrType())) {
1494 // Boolean conversions (C++ 4.12).
1495 SCS.Second = ICK_Boolean_Conversion;
1496 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001497 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001498 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001502 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001503 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001504 SCS.Second = ICK_Complex_Conversion;
1505 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001506 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1507 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001508 // Complex-real conversions (C99 6.3.1.7)
1509 SCS.Second = ICK_Complex_Real;
1510 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001511 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001512 // Floating point conversions (C++ 4.8).
1513 SCS.Second = ICK_Floating_Conversion;
1514 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001516 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001517 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001518 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001519 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001521 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001522 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001523 SCS.Second = ICK_Block_Pointer_Conversion;
1524 } else if (AllowObjCWritebackConversion &&
1525 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1526 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001527 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1528 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001529 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001531 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001532 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001534 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001535 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001536 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001537 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001538 SCS.Second = SecondICK;
1539 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001540 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001541 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001542 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001543 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001544 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001545 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001546 // Treat a conversion that strips "noreturn" as an identity conversion.
1547 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001548 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1549 InOverloadResolution,
1550 SCS, CStyle)) {
1551 SCS.Second = ICK_TransparentUnionConversion;
1552 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001553 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1554 CStyle)) {
1555 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001556 // appropriately.
1557 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001558 } else {
1559 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001562 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001563
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001564 QualType CanonFrom;
1565 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001566 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001567 bool ObjCLifetimeConversion;
1568 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1569 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001570 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001571 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001572 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001573 CanonFrom = S.Context.getCanonicalType(FromType);
1574 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 } else {
1576 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001577 SCS.Third = ICK_Identity;
1578
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001580 // [...] Any difference in top-level cv-qualification is
1581 // subsumed by the initialization itself and does not constitute
1582 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001583 CanonFrom = S.Context.getCanonicalType(FromType);
1584 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001585 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001586 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001587 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001588 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1589 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001590 FromType = ToType;
1591 CanonFrom = CanonTo;
1592 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001594 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001595
1596 // If we have not converted the argument type to the parameter type,
1597 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001598 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001600
Douglas Gregor60d62c22008-10-31 16:23:19 +00001601 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001602}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001603
1604static bool
1605IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1606 QualType &ToType,
1607 bool InOverloadResolution,
1608 StandardConversionSequence &SCS,
1609 bool CStyle) {
1610
1611 const RecordType *UT = ToType->getAsUnionType();
1612 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1613 return false;
1614 // The field to initialize within the transparent union.
1615 RecordDecl *UD = UT->getDecl();
1616 // It's compatible if the expression matches any of the fields.
1617 for (RecordDecl::field_iterator it = UD->field_begin(),
1618 itend = UD->field_end();
1619 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001620 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1621 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001622 ToType = it->getType();
1623 return true;
1624 }
1625 }
1626 return false;
1627}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001628
1629/// IsIntegralPromotion - Determines whether the conversion from the
1630/// expression From (whose potentially-adjusted type is FromType) to
1631/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1632/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001633bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001634 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001635 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001636 if (!To) {
1637 return false;
1638 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001639
1640 // An rvalue of type char, signed char, unsigned char, short int, or
1641 // unsigned short int can be converted to an rvalue of type int if
1642 // int can represent all the values of the source type; otherwise,
1643 // the source rvalue can be converted to an rvalue of type unsigned
1644 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001645 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1646 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001647 if (// We can promote any signed, promotable integer type to an int
1648 (FromType->isSignedIntegerType() ||
1649 // We can promote any unsigned integer type whose size is
1650 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001651 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001652 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001654 }
1655
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001656 return To->getKind() == BuiltinType::UInt;
1657 }
1658
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001659 // C++0x [conv.prom]p3:
1660 // A prvalue of an unscoped enumeration type whose underlying type is not
1661 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1662 // following types that can represent all the values of the enumeration
1663 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1664 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001665 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001666 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001667 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668 // with lowest integer conversion rank (4.13) greater than the rank of long
1669 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001670 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001671 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1672 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1673 // provided for a scoped enumeration.
1674 if (FromEnumType->getDecl()->isScoped())
1675 return false;
1676
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001677 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001679 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001680 return Context.hasSameUnqualifiedType(ToType,
1681 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001682 }
John McCall842aef82009-12-09 09:09:27 +00001683
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001684 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001685 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1686 // to an rvalue a prvalue of the first of the following types that can
1687 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001688 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001690 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001691 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001692 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001693 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001694 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001695 // Determine whether the type we're converting from is signed or
1696 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001697 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001698 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001700 // The types we'll try to promote to, in the appropriate
1701 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001702 QualType PromoteTypes[6] = {
1703 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001704 Context.LongTy, Context.UnsignedLongTy ,
1705 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001706 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001707 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001708 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1709 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001710 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1712 // We found the type that we can promote to. If this is the
1713 // type we wanted, we have a promotion. Otherwise, no
1714 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001715 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001716 }
1717 }
1718 }
1719
1720 // An rvalue for an integral bit-field (9.6) can be converted to an
1721 // rvalue of type int if int can represent all the values of the
1722 // bit-field; otherwise, it can be converted to unsigned int if
1723 // unsigned int can represent all the values of the bit-field. If
1724 // the bit-field is larger yet, no integral promotion applies to
1725 // it. If the bit-field has an enumerated type, it is treated as any
1726 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001727 // FIXME: We should delay checking of bit-fields until we actually perform the
1728 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001729 using llvm::APSInt;
1730 if (From)
1731 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001732 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001733 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001734 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1735 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1736 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Douglas Gregor86f19402008-12-20 23:49:58 +00001738 // Are we promoting to an int from a bitfield that fits in an int?
1739 if (BitWidth < ToSize ||
1740 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1741 return To->getKind() == BuiltinType::Int;
1742 }
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Douglas Gregor86f19402008-12-20 23:49:58 +00001744 // Are we promoting to an unsigned int from an unsigned bitfield
1745 // that fits into an unsigned int?
1746 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1747 return To->getKind() == BuiltinType::UInt;
1748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Douglas Gregor86f19402008-12-20 23:49:58 +00001750 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001751 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001754 // An rvalue of type bool can be converted to an rvalue of type int,
1755 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001756 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001757 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001758 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001759
1760 return false;
1761}
1762
1763/// IsFloatingPointPromotion - Determines whether the conversion from
1764/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1765/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001766bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001767 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1768 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001769 /// An rvalue of type float can be converted to an rvalue of type
1770 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771 if (FromBuiltin->getKind() == BuiltinType::Float &&
1772 ToBuiltin->getKind() == BuiltinType::Double)
1773 return true;
1774
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001775 // C99 6.3.1.5p1:
1776 // When a float is promoted to double or long double, or a
1777 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001778 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001779 (FromBuiltin->getKind() == BuiltinType::Float ||
1780 FromBuiltin->getKind() == BuiltinType::Double) &&
1781 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1782 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001783
1784 // Half can be promoted to float.
1785 if (FromBuiltin->getKind() == BuiltinType::Half &&
1786 ToBuiltin->getKind() == BuiltinType::Float)
1787 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001788 }
1789
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001790 return false;
1791}
1792
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001793/// \brief Determine if a conversion is a complex promotion.
1794///
1795/// A complex promotion is defined as a complex -> complex conversion
1796/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001797/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001798bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001799 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001800 if (!FromComplex)
1801 return false;
1802
John McCall183700f2009-09-21 23:43:11 +00001803 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001804 if (!ToComplex)
1805 return false;
1806
1807 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001808 ToComplex->getElementType()) ||
1809 IsIntegralPromotion(0, FromComplex->getElementType(),
1810 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001811}
1812
Douglas Gregorcb7de522008-11-26 23:31:11 +00001813/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1814/// the pointer type FromPtr to a pointer to type ToPointee, with the
1815/// same type qualifiers as FromPtr has on its pointee type. ToType,
1816/// if non-empty, will be a pointer to ToType that may or may not have
1817/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001818///
Mike Stump1eb44332009-09-09 15:08:12 +00001819static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001820BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001821 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001822 ASTContext &Context,
1823 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001824 assert((FromPtr->getTypeClass() == Type::Pointer ||
1825 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1826 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001827
John McCallf85e1932011-06-15 23:02:42 +00001828 /// Conversions to 'id' subsume cv-qualifier conversions.
1829 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001830 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001831
1832 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001833 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001834 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001835 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001836
John McCallf85e1932011-06-15 23:02:42 +00001837 if (StripObjCLifetime)
1838 Quals.removeObjCLifetime();
1839
Mike Stump1eb44332009-09-09 15:08:12 +00001840 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001841 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001842 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001843 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001844 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001845
1846 // Build a pointer to ToPointee. It has the right qualifiers
1847 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001848 if (isa<ObjCObjectPointerType>(ToType))
1849 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001850 return Context.getPointerType(ToPointee);
1851 }
1852
1853 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001854 QualType QualifiedCanonToPointee
1855 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001856
Douglas Gregorda80f742010-12-01 21:43:58 +00001857 if (isa<ObjCObjectPointerType>(ToType))
1858 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1859 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001860}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001861
Mike Stump1eb44332009-09-09 15:08:12 +00001862static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001863 bool InOverloadResolution,
1864 ASTContext &Context) {
1865 // Handle value-dependent integral null pointer constants correctly.
1866 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1867 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001868 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001869 return !InOverloadResolution;
1870
Douglas Gregorce940492009-09-25 04:25:58 +00001871 return Expr->isNullPointerConstant(Context,
1872 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1873 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001874}
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001876/// IsPointerConversion - Determines whether the conversion of the
1877/// expression From, which has the (possibly adjusted) type FromType,
1878/// can be converted to the type ToType via a pointer conversion (C++
1879/// 4.10). If so, returns true and places the converted type (that
1880/// might differ from ToType in its cv-qualifiers at some level) into
1881/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001882///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001883/// This routine also supports conversions to and from block pointers
1884/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1885/// pointers to interfaces. FIXME: Once we've determined the
1886/// appropriate overloading rules for Objective-C, we may want to
1887/// split the Objective-C checks into a different routine; however,
1888/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001889/// conversions, so for now they live here. IncompatibleObjC will be
1890/// set if the conversion is an allowed Objective-C conversion that
1891/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001892bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001893 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001894 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001895 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001896 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001897 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1898 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001899 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001900
Mike Stump1eb44332009-09-09 15:08:12 +00001901 // Conversion from a null pointer constant to any Objective-C pointer type.
1902 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001903 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001904 ConvertedType = ToType;
1905 return true;
1906 }
1907
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001908 // Blocks: Block pointers can be converted to void*.
1909 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001910 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001911 ConvertedType = ToType;
1912 return true;
1913 }
1914 // Blocks: A null pointer constant can be converted to a block
1915 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001916 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001917 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001918 ConvertedType = ToType;
1919 return true;
1920 }
1921
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001922 // If the left-hand-side is nullptr_t, the right side can be a null
1923 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001924 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001925 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001926 ConvertedType = ToType;
1927 return true;
1928 }
1929
Ted Kremenek6217b802009-07-29 21:53:49 +00001930 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001931 if (!ToTypePtr)
1932 return false;
1933
1934 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001935 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001936 ConvertedType = ToType;
1937 return true;
1938 }
Sebastian Redl07779722008-10-31 14:43:28 +00001939
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001940 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001941 // , including objective-c pointers.
1942 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001943 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001944 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001945 ConvertedType = BuildSimilarlyQualifiedPointerType(
1946 FromType->getAs<ObjCObjectPointerType>(),
1947 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001948 ToType, Context);
1949 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001950 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001951 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952 if (!FromTypePtr)
1953 return false;
1954
1955 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001956
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001958 // pointer conversion, so don't do all of the work below.
1959 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1960 return false;
1961
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001962 // An rvalue of type "pointer to cv T," where T is an object type,
1963 // can be converted to an rvalue of type "pointer to cv void" (C++
1964 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001965 if (FromPointeeType->isIncompleteOrObjectType() &&
1966 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001968 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001969 ToType, Context,
1970 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001971 return true;
1972 }
1973
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001974 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001975 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001976 ToPointeeType->isVoidType()) {
1977 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1978 ToPointeeType,
1979 ToType, Context);
1980 return true;
1981 }
1982
Douglas Gregorf9201e02009-02-11 23:02:49 +00001983 // When we're overloading in C, we allow a special kind of pointer
1984 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001985 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001986 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001988 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001989 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001990 return true;
1991 }
1992
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001993 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001994 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001995 // An rvalue of type "pointer to cv D," where D is a class type,
1996 // can be converted to an rvalue of type "pointer to cv B," where
1997 // B is a base class (clause 10) of D. If B is an inaccessible
1998 // (clause 11) or ambiguous (10.2) base class of D, a program that
1999 // necessitates this conversion is ill-formed. The result of the
2000 // conversion is a pointer to the base class sub-object of the
2001 // derived class object. The null pointer value is converted to
2002 // the null pointer value of the destination type.
2003 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002004 // Note that we do not check for ambiguity or inaccessibility
2005 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002006 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002007 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002008 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002009 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002010 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002011 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002012 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002013 ToType, Context);
2014 return true;
2015 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002016
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002017 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2018 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2020 ToPointeeType,
2021 ToType, Context);
2022 return true;
2023 }
2024
Douglas Gregorc7887512008-12-19 19:13:09 +00002025 return false;
2026}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002027
2028/// \brief Adopt the given qualifiers for the given type.
2029static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2030 Qualifiers TQs = T.getQualifiers();
2031
2032 // Check whether qualifiers already match.
2033 if (TQs == Qs)
2034 return T;
2035
2036 if (Qs.compatiblyIncludes(TQs))
2037 return Context.getQualifiedType(T, Qs);
2038
2039 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2040}
Douglas Gregorc7887512008-12-19 19:13:09 +00002041
2042/// isObjCPointerConversion - Determines whether this is an
2043/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2044/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002045bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002046 QualType& ConvertedType,
2047 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002048 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002049 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002051 // The set of qualifiers on the type we're converting from.
2052 Qualifiers FromQualifiers = FromType.getQualifiers();
2053
Steve Naroff14108da2009-07-10 23:34:53 +00002054 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002055 const ObjCObjectPointerType* ToObjCPtr =
2056 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002057 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002058 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002059
Steve Naroff14108da2009-07-10 23:34:53 +00002060 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002061 // If the pointee types are the same (ignoring qualifications),
2062 // then this is not a pointer conversion.
2063 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2064 FromObjCPtr->getPointeeType()))
2065 return false;
2066
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002067 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002068 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002069 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002070 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002071 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002072 return true;
2073 }
2074 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002075 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002076 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002077 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002078 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002079 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002080 return true;
2081 }
2082 // Objective C++: We're able to convert from a pointer to an
2083 // interface to a pointer to a different interface.
2084 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002085 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2086 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002087 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002088 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2089 FromObjCPtr->getPointeeType()))
2090 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002092 ToObjCPtr->getPointeeType(),
2093 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002094 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002095 return true;
2096 }
2097
2098 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2099 // Okay: this is some kind of implicit downcast of Objective-C
2100 // interfaces, which is permitted. However, we're going to
2101 // complain about it.
2102 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002104 ToObjCPtr->getPointeeType(),
2105 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002107 return true;
2108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109 }
Steve Naroff14108da2009-07-10 23:34:53 +00002110 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002111 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002112 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002113 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002114 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002115 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002116 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002117 // to a block pointer type.
2118 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002119 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002120 return true;
2121 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002122 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002125 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002126 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002127 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002128 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002129 return true;
2130 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002131 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002132 return false;
2133
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002134 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002135 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002136 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002137 else if (const BlockPointerType *FromBlockPtr =
2138 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002139 FromPointeeType = FromBlockPtr->getPointeeType();
2140 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002141 return false;
2142
Douglas Gregorc7887512008-12-19 19:13:09 +00002143 // If we have pointers to pointers, recursively check whether this
2144 // is an Objective-C conversion.
2145 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2146 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2147 IncompatibleObjC)) {
2148 // We always complain about this conversion.
2149 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002150 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002152 return true;
2153 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002154 // Allow conversion of pointee being objective-c pointer to another one;
2155 // as in I* to id.
2156 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2157 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2159 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002160
Douglas Gregorda80f742010-12-01 21:43:58 +00002161 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002162 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002163 return true;
2164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002165
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002166 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002167 // differences in the argument and result types are in Objective-C
2168 // pointer conversions. If so, we permit the conversion (but
2169 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002170 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002171 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002172 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002173 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002174 if (FromFunctionType && ToFunctionType) {
2175 // If the function types are exactly the same, this isn't an
2176 // Objective-C pointer conversion.
2177 if (Context.getCanonicalType(FromPointeeType)
2178 == Context.getCanonicalType(ToPointeeType))
2179 return false;
2180
2181 // Perform the quick checks that will tell us whether these
2182 // function types are obviously different.
2183 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2184 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2185 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2186 return false;
2187
2188 bool HasObjCConversion = false;
2189 if (Context.getCanonicalType(FromFunctionType->getResultType())
2190 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2191 // Okay, the types match exactly. Nothing to do.
2192 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2193 ToFunctionType->getResultType(),
2194 ConvertedType, IncompatibleObjC)) {
2195 // Okay, we have an Objective-C pointer conversion.
2196 HasObjCConversion = true;
2197 } else {
2198 // Function types are too different. Abort.
2199 return false;
2200 }
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Douglas Gregorc7887512008-12-19 19:13:09 +00002202 // Check argument types.
2203 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2204 ArgIdx != NumArgs; ++ArgIdx) {
2205 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2206 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2207 if (Context.getCanonicalType(FromArgType)
2208 == Context.getCanonicalType(ToArgType)) {
2209 // Okay, the types match exactly. Nothing to do.
2210 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2211 ConvertedType, IncompatibleObjC)) {
2212 // Okay, we have an Objective-C pointer conversion.
2213 HasObjCConversion = true;
2214 } else {
2215 // Argument types are too different. Abort.
2216 return false;
2217 }
2218 }
2219
2220 if (HasObjCConversion) {
2221 // We had an Objective-C conversion. Allow this pointer
2222 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002224 IncompatibleObjC = true;
2225 return true;
2226 }
2227 }
2228
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002229 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002230}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231
John McCallf85e1932011-06-15 23:02:42 +00002232/// \brief Determine whether this is an Objective-C writeback conversion,
2233/// used for parameter passing when performing automatic reference counting.
2234///
2235/// \param FromType The type we're converting form.
2236///
2237/// \param ToType The type we're converting to.
2238///
2239/// \param ConvertedType The type that will be produced after applying
2240/// this conversion.
2241bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2242 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002243 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002244 Context.hasSameUnqualifiedType(FromType, ToType))
2245 return false;
2246
2247 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2248 QualType ToPointee;
2249 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2250 ToPointee = ToPointer->getPointeeType();
2251 else
2252 return false;
2253
2254 Qualifiers ToQuals = ToPointee.getQualifiers();
2255 if (!ToPointee->isObjCLifetimeType() ||
2256 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002257 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002258 return false;
2259
2260 // Argument must be a pointer to __strong to __weak.
2261 QualType FromPointee;
2262 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2263 FromPointee = FromPointer->getPointeeType();
2264 else
2265 return false;
2266
2267 Qualifiers FromQuals = FromPointee.getQualifiers();
2268 if (!FromPointee->isObjCLifetimeType() ||
2269 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2270 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2271 return false;
2272
2273 // Make sure that we have compatible qualifiers.
2274 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2275 if (!ToQuals.compatiblyIncludes(FromQuals))
2276 return false;
2277
2278 // Remove qualifiers from the pointee type we're converting from; they
2279 // aren't used in the compatibility check belong, and we'll be adding back
2280 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2281 FromPointee = FromPointee.getUnqualifiedType();
2282
2283 // The unqualified form of the pointee types must be compatible.
2284 ToPointee = ToPointee.getUnqualifiedType();
2285 bool IncompatibleObjC;
2286 if (Context.typesAreCompatible(FromPointee, ToPointee))
2287 FromPointee = ToPointee;
2288 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2289 IncompatibleObjC))
2290 return false;
2291
2292 /// \brief Construct the type we're converting to, which is a pointer to
2293 /// __autoreleasing pointee.
2294 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2295 ConvertedType = Context.getPointerType(FromPointee);
2296 return true;
2297}
2298
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002299bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2300 QualType& ConvertedType) {
2301 QualType ToPointeeType;
2302 if (const BlockPointerType *ToBlockPtr =
2303 ToType->getAs<BlockPointerType>())
2304 ToPointeeType = ToBlockPtr->getPointeeType();
2305 else
2306 return false;
2307
2308 QualType FromPointeeType;
2309 if (const BlockPointerType *FromBlockPtr =
2310 FromType->getAs<BlockPointerType>())
2311 FromPointeeType = FromBlockPtr->getPointeeType();
2312 else
2313 return false;
2314 // We have pointer to blocks, check whether the only
2315 // differences in the argument and result types are in Objective-C
2316 // pointer conversions. If so, we permit the conversion.
2317
2318 const FunctionProtoType *FromFunctionType
2319 = FromPointeeType->getAs<FunctionProtoType>();
2320 const FunctionProtoType *ToFunctionType
2321 = ToPointeeType->getAs<FunctionProtoType>();
2322
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002323 if (!FromFunctionType || !ToFunctionType)
2324 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002325
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002326 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002327 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002328
2329 // Perform the quick checks that will tell us whether these
2330 // function types are obviously different.
2331 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2332 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2333 return false;
2334
2335 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2336 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2337 if (FromEInfo != ToEInfo)
2338 return false;
2339
2340 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002341 if (Context.hasSameType(FromFunctionType->getResultType(),
2342 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002343 // Okay, the types match exactly. Nothing to do.
2344 } else {
2345 QualType RHS = FromFunctionType->getResultType();
2346 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002347 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002348 !RHS.hasQualifiers() && LHS.hasQualifiers())
2349 LHS = LHS.getUnqualifiedType();
2350
2351 if (Context.hasSameType(RHS,LHS)) {
2352 // OK exact match.
2353 } else if (isObjCPointerConversion(RHS, LHS,
2354 ConvertedType, IncompatibleObjC)) {
2355 if (IncompatibleObjC)
2356 return false;
2357 // Okay, we have an Objective-C pointer conversion.
2358 }
2359 else
2360 return false;
2361 }
2362
2363 // Check argument types.
2364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2365 ArgIdx != NumArgs; ++ArgIdx) {
2366 IncompatibleObjC = false;
2367 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2368 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2369 if (Context.hasSameType(FromArgType, ToArgType)) {
2370 // Okay, the types match exactly. Nothing to do.
2371 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2372 ConvertedType, IncompatibleObjC)) {
2373 if (IncompatibleObjC)
2374 return false;
2375 // Okay, we have an Objective-C pointer conversion.
2376 } else
2377 // Argument types are too different. Abort.
2378 return false;
2379 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002380 if (LangOpts.ObjCAutoRefCount &&
2381 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2382 ToFunctionType))
2383 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002384
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002385 ConvertedType = ToType;
2386 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002387}
2388
Richard Trieu6efd4c52011-11-23 22:32:32 +00002389enum {
2390 ft_default,
2391 ft_different_class,
2392 ft_parameter_arity,
2393 ft_parameter_mismatch,
2394 ft_return_type,
2395 ft_qualifer_mismatch
2396};
2397
2398/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2399/// function types. Catches different number of parameter, mismatch in
2400/// parameter types, and different return types.
2401void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2402 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002403 // If either type is not valid, include no extra info.
2404 if (FromType.isNull() || ToType.isNull()) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
Richard Trieu6efd4c52011-11-23 22:32:32 +00002409 // Get the function type from the pointers.
2410 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2411 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2412 *ToMember = ToType->getAs<MemberPointerType>();
2413 if (FromMember->getClass() != ToMember->getClass()) {
2414 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2415 << QualType(FromMember->getClass(), 0);
2416 return;
2417 }
2418 FromType = FromMember->getPointeeType();
2419 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002420 }
2421
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002422 if (FromType->isPointerType())
2423 FromType = FromType->getPointeeType();
2424 if (ToType->isPointerType())
2425 ToType = ToType->getPointeeType();
2426
2427 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002428 FromType = FromType.getNonReferenceType();
2429 ToType = ToType.getNonReferenceType();
2430
Richard Trieu6efd4c52011-11-23 22:32:32 +00002431 // Don't print extra info for non-specialized template functions.
2432 if (FromType->isInstantiationDependentType() &&
2433 !FromType->getAs<TemplateSpecializationType>()) {
2434 PDiag << ft_default;
2435 return;
2436 }
2437
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002438 // No extra info for same types.
2439 if (Context.hasSameType(FromType, ToType)) {
2440 PDiag << ft_default;
2441 return;
2442 }
2443
Richard Trieu6efd4c52011-11-23 22:32:32 +00002444 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2445 *ToFunction = ToType->getAs<FunctionProtoType>();
2446
2447 // Both types need to be function types.
2448 if (!FromFunction || !ToFunction) {
2449 PDiag << ft_default;
2450 return;
2451 }
2452
2453 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2454 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2455 << FromFunction->getNumArgs();
2456 return;
2457 }
2458
2459 // Handle different parameter types.
2460 unsigned ArgPos;
2461 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2462 PDiag << ft_parameter_mismatch << ArgPos + 1
2463 << ToFunction->getArgType(ArgPos)
2464 << FromFunction->getArgType(ArgPos);
2465 return;
2466 }
2467
2468 // Handle different return type.
2469 if (!Context.hasSameType(FromFunction->getResultType(),
2470 ToFunction->getResultType())) {
2471 PDiag << ft_return_type << ToFunction->getResultType()
2472 << FromFunction->getResultType();
2473 return;
2474 }
2475
2476 unsigned FromQuals = FromFunction->getTypeQuals(),
2477 ToQuals = ToFunction->getTypeQuals();
2478 if (FromQuals != ToQuals) {
2479 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2480 return;
2481 }
2482
2483 // Unable to find a difference, so add no extra info.
2484 PDiag << ft_default;
2485}
2486
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002487/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002488/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002489/// they have same number of arguments. This routine assumes that Objective-C
2490/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002491/// If the parameters are different, ArgPos will have the the parameter index
2492/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002493bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002494 const FunctionProtoType *NewType,
2495 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002496 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002497 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2498 N = NewType->arg_type_begin(),
2499 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2500 if (!Context.hasSameType(*O, *N)) {
2501 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2502 return false;
2503 }
2504 }
2505 return true;
2506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002507
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002508 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2509 N = NewType->arg_type_begin(),
2510 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2511 QualType ToType = (*O);
2512 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002513 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002514 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2515 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002516 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2517 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2518 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2519 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002520 continue;
2521 }
John McCallc12c5bb2010-05-15 11:32:37 +00002522 else if (const ObjCObjectPointerType *PTTo =
2523 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002524 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002525 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002526 if (Context.hasSameUnqualifiedType(
2527 PTTo->getObjectType()->getBaseType(),
2528 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002529 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002530 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002531 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002532 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002533 }
2534 }
2535 return true;
2536}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002537
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002538/// CheckPointerConversion - Check the pointer conversion from the
2539/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002540/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002541/// conversions for which IsPointerConversion has already returned
2542/// true. It returns true and produces a diagnostic if there was an
2543/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002544bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002545 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002546 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002547 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002548 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002549 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550
John McCalldaa8e4e2010-11-15 09:13:47 +00002551 Kind = CK_BitCast;
2552
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002553 if (!IsCStyleOrFunctionalCast &&
2554 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2555 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2556 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002557 PDiag(diag::warn_impcast_bool_to_null_pointer)
2558 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002559
John McCall1d9b3b22011-09-09 05:25:32 +00002560 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2561 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562 QualType FromPointeeType = FromPtrType->getPointeeType(),
2563 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002564
Douglas Gregor5fccd362010-03-03 23:55:11 +00002565 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2566 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002567 // We must have a derived-to-base conversion. Check an
2568 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002569 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2570 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002571 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002572 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002573 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002574
Anders Carlsson61faec12009-09-12 04:46:44 +00002575 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002576 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002577 }
2578 }
John McCall1d9b3b22011-09-09 05:25:32 +00002579 } else if (const ObjCObjectPointerType *ToPtrType =
2580 ToType->getAs<ObjCObjectPointerType>()) {
2581 if (const ObjCObjectPointerType *FromPtrType =
2582 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002583 // Objective-C++ conversions are always okay.
2584 // FIXME: We should have a different class of conversions for the
2585 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002586 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002587 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002588 } else if (FromType->isBlockPointerType()) {
2589 Kind = CK_BlockPointerToObjCPointerCast;
2590 } else {
2591 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002592 }
John McCall1d9b3b22011-09-09 05:25:32 +00002593 } else if (ToType->isBlockPointerType()) {
2594 if (!FromType->isBlockPointerType())
2595 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002596 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002597
2598 // We shouldn't fall into this case unless it's valid for other
2599 // reasons.
2600 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2601 Kind = CK_NullToPointer;
2602
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002603 return false;
2604}
2605
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002606/// IsMemberPointerConversion - Determines whether the conversion of the
2607/// expression From, which has the (possibly adjusted) type FromType, can be
2608/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2609/// If so, returns true and places the converted type (that might differ from
2610/// ToType in its cv-qualifiers at some level) into ConvertedType.
2611bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002613 bool InOverloadResolution,
2614 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002615 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002616 if (!ToTypePtr)
2617 return false;
2618
2619 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002620 if (From->isNullPointerConstant(Context,
2621 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2622 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002623 ConvertedType = ToType;
2624 return true;
2625 }
2626
2627 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002628 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002629 if (!FromTypePtr)
2630 return false;
2631
2632 // A pointer to member of B can be converted to a pointer to member of D,
2633 // where D is derived from B (C++ 4.11p2).
2634 QualType FromClass(FromTypePtr->getClass(), 0);
2635 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002636
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002637 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002638 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002639 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002640 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2641 ToClass.getTypePtr());
2642 return true;
2643 }
2644
2645 return false;
2646}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002648/// CheckMemberPointerConversion - Check the member pointer conversion from the
2649/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002650/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002651/// for which IsMemberPointerConversion has already returned true. It returns
2652/// true and produces a diagnostic if there was an error, or returns false
2653/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002654bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002655 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002656 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002657 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002658 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002659 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002660 if (!FromPtrType) {
2661 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002663 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002664 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002665 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002666 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002667 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002668
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002670 assert(ToPtrType && "No member pointer cast has a target type "
2671 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002672
Sebastian Redl21593ac2009-01-28 18:33:18 +00002673 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2674 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002675
Sebastian Redl21593ac2009-01-28 18:33:18 +00002676 // FIXME: What about dependent types?
2677 assert(FromClass->isRecordType() && "Pointer into non-class.");
2678 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002679
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002680 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002681 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002682 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2683 assert(DerivationOkay &&
2684 "Should not have been called if derivation isn't OK.");
2685 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002686
Sebastian Redl21593ac2009-01-28 18:33:18 +00002687 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2688 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002689 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2690 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2691 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2692 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002693 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002694
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002695 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002696 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2697 << FromClass << ToClass << QualType(VBase, 0)
2698 << From->getSourceRange();
2699 return true;
2700 }
2701
John McCall6b2accb2010-02-10 09:31:12 +00002702 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002703 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2704 Paths.front(),
2705 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002706
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002707 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002708 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002709 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002710 return false;
2711}
2712
Douglas Gregor98cd5992008-10-21 23:43:52 +00002713/// IsQualificationConversion - Determines whether the conversion from
2714/// an rvalue of type FromType to ToType is a qualification conversion
2715/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002716///
2717/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2718/// when the qualification conversion involves a change in the Objective-C
2719/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002720bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002721Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002722 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002723 FromType = Context.getCanonicalType(FromType);
2724 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002725 ObjCLifetimeConversion = false;
2726
Douglas Gregor98cd5992008-10-21 23:43:52 +00002727 // If FromType and ToType are the same type, this is not a
2728 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002729 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002730 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002731
Douglas Gregor98cd5992008-10-21 23:43:52 +00002732 // (C++ 4.4p4):
2733 // A conversion can add cv-qualifiers at levels other than the first
2734 // in multi-level pointers, subject to the following rules: [...]
2735 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002736 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002737 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002738 // Within each iteration of the loop, we check the qualifiers to
2739 // determine if this still looks like a qualification
2740 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002741 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002742 // until there are no more pointers or pointers-to-members left to
2743 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002744 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002745
Douglas Gregor621c92a2011-04-25 18:40:17 +00002746 Qualifiers FromQuals = FromType.getQualifiers();
2747 Qualifiers ToQuals = ToType.getQualifiers();
2748
John McCallf85e1932011-06-15 23:02:42 +00002749 // Objective-C ARC:
2750 // Check Objective-C lifetime conversions.
2751 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2752 UnwrappedAnyPointer) {
2753 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2754 ObjCLifetimeConversion = true;
2755 FromQuals.removeObjCLifetime();
2756 ToQuals.removeObjCLifetime();
2757 } else {
2758 // Qualification conversions cannot cast between different
2759 // Objective-C lifetime qualifiers.
2760 return false;
2761 }
2762 }
2763
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002764 // Allow addition/removal of GC attributes but not changing GC attributes.
2765 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2766 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2767 FromQuals.removeObjCGCAttr();
2768 ToQuals.removeObjCGCAttr();
2769 }
2770
Douglas Gregor98cd5992008-10-21 23:43:52 +00002771 // -- for every j > 0, if const is in cv 1,j then const is in cv
2772 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002773 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002774 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Douglas Gregor98cd5992008-10-21 23:43:52 +00002776 // -- if the cv 1,j and cv 2,j are different, then const is in
2777 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002778 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002779 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002780 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregor98cd5992008-10-21 23:43:52 +00002782 // Keep track of whether all prior cv-qualifiers in the "to" type
2783 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002784 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002785 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002786 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002787
2788 // We are left with FromType and ToType being the pointee types
2789 // after unwrapping the original FromType and ToType the same number
2790 // of types. If we unwrapped any pointers, and if FromType and
2791 // ToType have the same unqualified type (since we checked
2792 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002793 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002794}
2795
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002796/// \brief - Determine whether this is a conversion from a scalar type to an
2797/// atomic type.
2798///
2799/// If successful, updates \c SCS's second and third steps in the conversion
2800/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002801static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2802 bool InOverloadResolution,
2803 StandardConversionSequence &SCS,
2804 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002805 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2806 if (!ToAtomic)
2807 return false;
2808
2809 StandardConversionSequence InnerSCS;
2810 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2811 InOverloadResolution, InnerSCS,
2812 CStyle, /*AllowObjCWritebackConversion=*/false))
2813 return false;
2814
2815 SCS.Second = InnerSCS.Second;
2816 SCS.setToType(1, InnerSCS.getToType(1));
2817 SCS.Third = InnerSCS.Third;
2818 SCS.QualificationIncludesObjCLifetime
2819 = InnerSCS.QualificationIncludesObjCLifetime;
2820 SCS.setToType(2, InnerSCS.getToType(2));
2821 return true;
2822}
2823
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002824static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2825 CXXConstructorDecl *Constructor,
2826 QualType Type) {
2827 const FunctionProtoType *CtorType =
2828 Constructor->getType()->getAs<FunctionProtoType>();
2829 if (CtorType->getNumArgs() > 0) {
2830 QualType FirstArg = CtorType->getArgType(0);
2831 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2832 return true;
2833 }
2834 return false;
2835}
2836
Sebastian Redl56a04282012-02-11 23:51:08 +00002837static OverloadingResult
2838IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2839 CXXRecordDecl *To,
2840 UserDefinedConversionSequence &User,
2841 OverloadCandidateSet &CandidateSet,
2842 bool AllowExplicit) {
2843 DeclContext::lookup_iterator Con, ConEnd;
2844 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2845 Con != ConEnd; ++Con) {
2846 NamedDecl *D = *Con;
2847 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2848
2849 // Find the constructor (which may be a template).
2850 CXXConstructorDecl *Constructor = 0;
2851 FunctionTemplateDecl *ConstructorTmpl
2852 = dyn_cast<FunctionTemplateDecl>(D);
2853 if (ConstructorTmpl)
2854 Constructor
2855 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2856 else
2857 Constructor = cast<CXXConstructorDecl>(D);
2858
2859 bool Usable = !Constructor->isInvalidDecl() &&
2860 S.isInitListConstructor(Constructor) &&
2861 (AllowExplicit || !Constructor->isExplicit());
2862 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002863 // If the first argument is (a reference to) the target type,
2864 // suppress conversions.
2865 bool SuppressUserConversions =
2866 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002867 if (ConstructorTmpl)
2868 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2869 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002870 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002871 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002872 else
2873 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002874 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002875 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002876 }
2877 }
2878
2879 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2880
2881 OverloadCandidateSet::iterator Best;
2882 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2883 case OR_Success: {
2884 // Record the standard conversion we used and the conversion function.
2885 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2886 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2887
2888 QualType ThisType = Constructor->getThisType(S.Context);
2889 // Initializer lists don't have conversions as such.
2890 User.Before.setAsIdentityConversion();
2891 User.HadMultipleCandidates = HadMultipleCandidates;
2892 User.ConversionFunction = Constructor;
2893 User.FoundConversionFunction = Best->FoundDecl;
2894 User.After.setAsIdentityConversion();
2895 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2896 User.After.setAllToTypes(ToType);
2897 return OR_Success;
2898 }
2899
2900 case OR_No_Viable_Function:
2901 return OR_No_Viable_Function;
2902 case OR_Deleted:
2903 return OR_Deleted;
2904 case OR_Ambiguous:
2905 return OR_Ambiguous;
2906 }
2907
2908 llvm_unreachable("Invalid OverloadResult!");
2909}
2910
Douglas Gregor734d9862009-01-30 23:27:23 +00002911/// Determines whether there is a user-defined conversion sequence
2912/// (C++ [over.ics.user]) that converts expression From to the type
2913/// ToType. If such a conversion exists, User will contain the
2914/// user-defined conversion sequence that performs such a conversion
2915/// and this routine will return true. Otherwise, this routine returns
2916/// false and User is unspecified.
2917///
Douglas Gregor734d9862009-01-30 23:27:23 +00002918/// \param AllowExplicit true if the conversion should consider C++0x
2919/// "explicit" conversion functions as well as non-explicit conversion
2920/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002921static OverloadingResult
2922IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002923 UserDefinedConversionSequence &User,
2924 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002925 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002926 // Whether we will only visit constructors.
2927 bool ConstructorsOnly = false;
2928
2929 // If the type we are conversion to is a class type, enumerate its
2930 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002931 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002932 // C++ [over.match.ctor]p1:
2933 // When objects of class type are direct-initialized (8.5), or
2934 // copy-initialized from an expression of the same or a
2935 // derived class type (8.5), overload resolution selects the
2936 // constructor. [...] For copy-initialization, the candidate
2937 // functions are all the converting constructors (12.3.1) of
2938 // that class. The argument list is the expression-list within
2939 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002940 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002941 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002942 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002943 ConstructorsOnly = true;
2944
Douglas Gregord10099e2012-05-04 16:32:21 +00002945 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002946 // RequireCompleteType may have returned true due to some invalid decl
2947 // during template instantiation, but ToType may be complete enough now
2948 // to try to recover.
2949 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002950 // We're not going to find any constructors.
2951 } else if (CXXRecordDecl *ToRecordDecl
2952 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002953
2954 Expr **Args = &From;
2955 unsigned NumArgs = 1;
2956 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002957 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002958 // But first, see if there is an init-list-contructor that will work.
2959 OverloadingResult Result = IsInitializerListConstructorConversion(
2960 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2961 if (Result != OR_No_Viable_Function)
2962 return Result;
2963 // Never mind.
2964 CandidateSet.clear();
2965
2966 // If we're list-initializing, we pass the individual elements as
2967 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002968 Args = InitList->getInits();
2969 NumArgs = InitList->getNumInits();
2970 ListInitializing = true;
2971 }
2972
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002973 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002974 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002975 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002976 NamedDecl *D = *Con;
2977 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2978
Douglas Gregordec06662009-08-21 18:42:58 +00002979 // Find the constructor (which may be a template).
2980 CXXConstructorDecl *Constructor = 0;
2981 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002982 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002983 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002984 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002985 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2986 else
John McCall9aa472c2010-03-19 07:35:19 +00002987 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002988
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002989 bool Usable = !Constructor->isInvalidDecl();
2990 if (ListInitializing)
2991 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2992 else
2993 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2994 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002995 bool SuppressUserConversions = !ConstructorsOnly;
2996 if (SuppressUserConversions && ListInitializing) {
2997 SuppressUserConversions = false;
2998 if (NumArgs == 1) {
2999 // If the first argument is (a reference to) the target type,
3000 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003001 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3002 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003003 }
3004 }
Douglas Gregordec06662009-08-21 18:42:58 +00003005 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003006 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3007 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003008 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003009 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003010 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003011 // Allow one user-defined conversion when user specifies a
3012 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003013 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003014 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003015 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003016 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003017 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003018 }
3019 }
3020
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003021 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003022 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003023 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003024 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003025 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003026 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003027 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003028 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3029 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003030 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003031 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003032 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003033 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003034 DeclAccessPair FoundDecl = I.getPair();
3035 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003036 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3037 if (isa<UsingShadowDecl>(D))
3038 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3039
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003040 CXXConversionDecl *Conv;
3041 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003042 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3043 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003044 else
John McCall32daa422010-03-31 01:36:47 +00003045 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003046
3047 if (AllowExplicit || !Conv->isExplicit()) {
3048 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003049 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3050 ActingContext, From, ToType,
3051 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003052 else
John McCall120d63c2010-08-24 20:38:10 +00003053 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3054 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003055 }
3056 }
3057 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003058 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003059
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003060 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3061
Douglas Gregor60d62c22008-10-31 16:23:19 +00003062 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003063 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003064 case OR_Success:
3065 // Record the standard conversion we used and the conversion function.
3066 if (CXXConstructorDecl *Constructor
3067 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003068 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003069
John McCall120d63c2010-08-24 20:38:10 +00003070 // C++ [over.ics.user]p1:
3071 // If the user-defined conversion is specified by a
3072 // constructor (12.3.1), the initial standard conversion
3073 // sequence converts the source type to the type required by
3074 // the argument of the constructor.
3075 //
3076 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003077 if (isa<InitListExpr>(From)) {
3078 // Initializer lists don't have conversions as such.
3079 User.Before.setAsIdentityConversion();
3080 } else {
3081 if (Best->Conversions[0].isEllipsis())
3082 User.EllipsisConversion = true;
3083 else {
3084 User.Before = Best->Conversions[0].Standard;
3085 User.EllipsisConversion = false;
3086 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003087 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003088 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003089 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003090 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003091 User.After.setAsIdentityConversion();
3092 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3093 User.After.setAllToTypes(ToType);
3094 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003095 }
3096 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003097 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003098 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003099
John McCall120d63c2010-08-24 20:38:10 +00003100 // C++ [over.ics.user]p1:
3101 //
3102 // [...] If the user-defined conversion is specified by a
3103 // conversion function (12.3.2), the initial standard
3104 // conversion sequence converts the source type to the
3105 // implicit object parameter of the conversion function.
3106 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003107 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003108 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003109 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003110 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003111
John McCall120d63c2010-08-24 20:38:10 +00003112 // C++ [over.ics.user]p2:
3113 // The second standard conversion sequence converts the
3114 // result of the user-defined conversion to the target type
3115 // for the sequence. Since an implicit conversion sequence
3116 // is an initialization, the special rules for
3117 // initialization by user-defined conversion apply when
3118 // selecting the best user-defined conversion for a
3119 // user-defined conversion sequence (see 13.3.3 and
3120 // 13.3.3.1).
3121 User.After = Best->FinalConversion;
3122 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003123 }
David Blaikie7530c032012-01-17 06:56:22 +00003124 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003125
John McCall120d63c2010-08-24 20:38:10 +00003126 case OR_No_Viable_Function:
3127 return OR_No_Viable_Function;
3128 case OR_Deleted:
3129 // No conversion here! We're done.
3130 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
John McCall120d63c2010-08-24 20:38:10 +00003132 case OR_Ambiguous:
3133 return OR_Ambiguous;
3134 }
3135
David Blaikie7530c032012-01-17 06:56:22 +00003136 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003137}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003139bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003140Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003141 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003142 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003143 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003144 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003145 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003146 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003147 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003148 diag::err_typecheck_ambiguous_condition)
3149 << From->getType() << ToType << From->getSourceRange();
3150 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003151 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003152 diag::err_typecheck_nonviable_condition)
3153 << From->getType() << ToType << From->getSourceRange();
3154 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003155 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003157 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003158}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003159
Douglas Gregorb734e242012-02-22 17:32:19 +00003160/// \brief Compare the user-defined conversion functions or constructors
3161/// of two user-defined conversion sequences to determine whether any ordering
3162/// is possible.
3163static ImplicitConversionSequence::CompareKind
3164compareConversionFunctions(Sema &S,
3165 FunctionDecl *Function1,
3166 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003167 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003168 return ImplicitConversionSequence::Indistinguishable;
3169
3170 // Objective-C++:
3171 // If both conversion functions are implicitly-declared conversions from
3172 // a lambda closure type to a function pointer and a block pointer,
3173 // respectively, always prefer the conversion to a function pointer,
3174 // because the function pointer is more lightweight and is more likely
3175 // to keep code working.
3176 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3177 if (!Conv1)
3178 return ImplicitConversionSequence::Indistinguishable;
3179
3180 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3181 if (!Conv2)
3182 return ImplicitConversionSequence::Indistinguishable;
3183
3184 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3185 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3186 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3187 if (Block1 != Block2)
3188 return Block1? ImplicitConversionSequence::Worse
3189 : ImplicitConversionSequence::Better;
3190 }
3191
3192 return ImplicitConversionSequence::Indistinguishable;
3193}
3194
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003195/// CompareImplicitConversionSequences - Compare two implicit
3196/// conversion sequences to determine whether one is better than the
3197/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003198static ImplicitConversionSequence::CompareKind
3199CompareImplicitConversionSequences(Sema &S,
3200 const ImplicitConversionSequence& ICS1,
3201 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003202{
3203 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3204 // conversion sequences (as defined in 13.3.3.1)
3205 // -- a standard conversion sequence (13.3.3.1.1) is a better
3206 // conversion sequence than a user-defined conversion sequence or
3207 // an ellipsis conversion sequence, and
3208 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3209 // conversion sequence than an ellipsis conversion sequence
3210 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003211 //
John McCall1d318332010-01-12 00:44:57 +00003212 // C++0x [over.best.ics]p10:
3213 // For the purpose of ranking implicit conversion sequences as
3214 // described in 13.3.3.2, the ambiguous conversion sequence is
3215 // treated as a user-defined sequence that is indistinguishable
3216 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003217 if (ICS1.getKindRank() < ICS2.getKindRank())
3218 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003219 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003220 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003221
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003222 // The following checks require both conversion sequences to be of
3223 // the same kind.
3224 if (ICS1.getKind() != ICS2.getKind())
3225 return ImplicitConversionSequence::Indistinguishable;
3226
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003227 ImplicitConversionSequence::CompareKind Result =
3228 ImplicitConversionSequence::Indistinguishable;
3229
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003230 // Two implicit conversion sequences of the same form are
3231 // indistinguishable conversion sequences unless one of the
3232 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003233 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003234 Result = CompareStandardConversionSequences(S,
3235 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003236 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003237 // User-defined conversion sequence U1 is a better conversion
3238 // sequence than another user-defined conversion sequence U2 if
3239 // they contain the same user-defined conversion function or
3240 // constructor and if the second standard conversion sequence of
3241 // U1 is better than the second standard conversion sequence of
3242 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003243 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003244 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003245 Result = CompareStandardConversionSequences(S,
3246 ICS1.UserDefined.After,
3247 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003248 else
3249 Result = compareConversionFunctions(S,
3250 ICS1.UserDefined.ConversionFunction,
3251 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003252 }
3253
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003254 // List-initialization sequence L1 is a better conversion sequence than
3255 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3256 // for some X and L2 does not.
3257 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003258 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003259 ICS1.isListInitializationSequence() &&
3260 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003261 if (ICS1.isStdInitializerListElement() &&
3262 !ICS2.isStdInitializerListElement())
3263 return ImplicitConversionSequence::Better;
3264 if (!ICS1.isStdInitializerListElement() &&
3265 ICS2.isStdInitializerListElement())
3266 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003267 }
3268
3269 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003270}
3271
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003272static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3273 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3274 Qualifiers Quals;
3275 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003279 return Context.hasSameUnqualifiedType(T1, T2);
3280}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281
Douglas Gregorad323a82010-01-27 03:51:04 +00003282// Per 13.3.3.2p3, compare the given standard conversion sequences to
3283// determine if one is a proper subset of the other.
3284static ImplicitConversionSequence::CompareKind
3285compareStandardConversionSubsets(ASTContext &Context,
3286 const StandardConversionSequence& SCS1,
3287 const StandardConversionSequence& SCS2) {
3288 ImplicitConversionSequence::CompareKind Result
3289 = ImplicitConversionSequence::Indistinguishable;
3290
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003291 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003292 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003293 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3294 return ImplicitConversionSequence::Better;
3295 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3296 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297
Douglas Gregorad323a82010-01-27 03:51:04 +00003298 if (SCS1.Second != SCS2.Second) {
3299 if (SCS1.Second == ICK_Identity)
3300 Result = ImplicitConversionSequence::Better;
3301 else if (SCS2.Second == ICK_Identity)
3302 Result = ImplicitConversionSequence::Worse;
3303 else
3304 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003305 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003306 return ImplicitConversionSequence::Indistinguishable;
3307
3308 if (SCS1.Third == SCS2.Third) {
3309 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3310 : ImplicitConversionSequence::Indistinguishable;
3311 }
3312
3313 if (SCS1.Third == ICK_Identity)
3314 return Result == ImplicitConversionSequence::Worse
3315 ? ImplicitConversionSequence::Indistinguishable
3316 : ImplicitConversionSequence::Better;
3317
3318 if (SCS2.Third == ICK_Identity)
3319 return Result == ImplicitConversionSequence::Better
3320 ? ImplicitConversionSequence::Indistinguishable
3321 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322
Douglas Gregorad323a82010-01-27 03:51:04 +00003323 return ImplicitConversionSequence::Indistinguishable;
3324}
3325
Douglas Gregor440a4832011-01-26 14:52:12 +00003326/// \brief Determine whether one of the given reference bindings is better
3327/// than the other based on what kind of bindings they are.
3328static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3329 const StandardConversionSequence &SCS2) {
3330 // C++0x [over.ics.rank]p3b4:
3331 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3332 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003334 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003336 // reference*.
3337 //
3338 // FIXME: Rvalue references. We're going rogue with the above edits,
3339 // because the semantics in the current C++0x working paper (N3225 at the
3340 // time of this writing) break the standard definition of std::forward
3341 // and std::reference_wrapper when dealing with references to functions.
3342 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003343 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3344 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3345 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor440a4832011-01-26 14:52:12 +00003347 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3348 SCS2.IsLvalueReference) ||
3349 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3350 !SCS2.IsLvalueReference);
3351}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003352
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353/// CompareStandardConversionSequences - Compare two standard
3354/// conversion sequences to determine whether one is better than the
3355/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003356static ImplicitConversionSequence::CompareKind
3357CompareStandardConversionSequences(Sema &S,
3358 const StandardConversionSequence& SCS1,
3359 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003360{
3361 // Standard conversion sequence S1 is a better conversion sequence
3362 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3363
3364 // -- S1 is a proper subsequence of S2 (comparing the conversion
3365 // sequences in the canonical form defined by 13.3.3.1.1,
3366 // excluding any Lvalue Transformation; the identity conversion
3367 // sequence is considered to be a subsequence of any
3368 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003369 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003370 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003371 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003372
3373 // -- the rank of S1 is better than the rank of S2 (by the rules
3374 // defined below), or, if not that,
3375 ImplicitConversionRank Rank1 = SCS1.getRank();
3376 ImplicitConversionRank Rank2 = SCS2.getRank();
3377 if (Rank1 < Rank2)
3378 return ImplicitConversionSequence::Better;
3379 else if (Rank2 < Rank1)
3380 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003381
Douglas Gregor57373262008-10-22 14:17:15 +00003382 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3383 // are indistinguishable unless one of the following rules
3384 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Douglas Gregor57373262008-10-22 14:17:15 +00003386 // A conversion that is not a conversion of a pointer, or
3387 // pointer to member, to bool is better than another conversion
3388 // that is such a conversion.
3389 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3390 return SCS2.isPointerConversionToBool()
3391 ? ImplicitConversionSequence::Better
3392 : ImplicitConversionSequence::Worse;
3393
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003394 // C++ [over.ics.rank]p4b2:
3395 //
3396 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003397 // conversion of B* to A* is better than conversion of B* to
3398 // void*, and conversion of A* to void* is better than conversion
3399 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003400 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003401 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003402 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003403 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003404 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3405 // Exactly one of the conversion sequences is a conversion to
3406 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003407 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3408 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003409 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3410 // Neither conversion sequence converts to a void pointer; compare
3411 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003412 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003413 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003414 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003415 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3416 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003417 // Both conversion sequences are conversions to void
3418 // pointers. Compare the source types to determine if there's an
3419 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003420 QualType FromType1 = SCS1.getFromType();
3421 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003422
3423 // Adjust the types we're converting from via the array-to-pointer
3424 // conversion, if we need to.
3425 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003426 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003427 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003428 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003429
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003430 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3431 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003432
John McCall120d63c2010-08-24 20:38:10 +00003433 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003434 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003435 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003436 return ImplicitConversionSequence::Worse;
3437
3438 // Objective-C++: If one interface is more specific than the
3439 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003440 const ObjCObjectPointerType* FromObjCPtr1
3441 = FromType1->getAs<ObjCObjectPointerType>();
3442 const ObjCObjectPointerType* FromObjCPtr2
3443 = FromType2->getAs<ObjCObjectPointerType>();
3444 if (FromObjCPtr1 && FromObjCPtr2) {
3445 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3446 FromObjCPtr2);
3447 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3448 FromObjCPtr1);
3449 if (AssignLeft != AssignRight) {
3450 return AssignLeft? ImplicitConversionSequence::Better
3451 : ImplicitConversionSequence::Worse;
3452 }
Douglas Gregor01919692009-12-13 21:37:05 +00003453 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003454 }
Douglas Gregor57373262008-10-22 14:17:15 +00003455
3456 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3457 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003458 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003459 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003460 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003461
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003462 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003463 // Check for a better reference binding based on the kind of bindings.
3464 if (isBetterReferenceBindingKind(SCS1, SCS2))
3465 return ImplicitConversionSequence::Better;
3466 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3467 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003468
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003469 // C++ [over.ics.rank]p3b4:
3470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3471 // which the references refer are the same type except for
3472 // top-level cv-qualifiers, and the type to which the reference
3473 // initialized by S2 refers is more cv-qualified than the type
3474 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003475 QualType T1 = SCS1.getToType(2);
3476 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003477 T1 = S.Context.getCanonicalType(T1);
3478 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003479 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003482 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003483 // Objective-C++ ARC: If the references refer to objects with different
3484 // lifetimes, prefer bindings that don't change lifetime.
3485 if (SCS1.ObjCLifetimeConversionBinding !=
3486 SCS2.ObjCLifetimeConversionBinding) {
3487 return SCS1.ObjCLifetimeConversionBinding
3488 ? ImplicitConversionSequence::Worse
3489 : ImplicitConversionSequence::Better;
3490 }
3491
Chandler Carruth6df868e2010-12-12 08:17:55 +00003492 // If the type is an array type, promote the element qualifiers to the
3493 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003494 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003495 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003496 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003497 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498 if (T2.isMoreQualifiedThan(T1))
3499 return ImplicitConversionSequence::Better;
3500 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003501 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003502 }
3503 }
Douglas Gregor57373262008-10-22 14:17:15 +00003504
Francois Pichet1c98d622011-09-18 21:37:37 +00003505 // In Microsoft mode, prefer an integral conversion to a
3506 // floating-to-integral conversion if the integral conversion
3507 // is between types of the same size.
3508 // For example:
3509 // void f(float);
3510 // void f(int);
3511 // int main {
3512 // long a;
3513 // f(a);
3514 // }
3515 // Here, MSVC will call f(int) instead of generating a compile error
3516 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003517 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003518 SCS1.Second == ICK_Integral_Conversion &&
3519 SCS2.Second == ICK_Floating_Integral &&
3520 S.Context.getTypeSize(SCS1.getFromType()) ==
3521 S.Context.getTypeSize(SCS1.getToType(2)))
3522 return ImplicitConversionSequence::Better;
3523
Douglas Gregor57373262008-10-22 14:17:15 +00003524 return ImplicitConversionSequence::Indistinguishable;
3525}
3526
3527/// CompareQualificationConversions - Compares two standard conversion
3528/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003529/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3530ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003531CompareQualificationConversions(Sema &S,
3532 const StandardConversionSequence& SCS1,
3533 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003534 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003535 // -- S1 and S2 differ only in their qualification conversion and
3536 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3537 // cv-qualification signature of type T1 is a proper subset of
3538 // the cv-qualification signature of type T2, and S1 is not the
3539 // deprecated string literal array-to-pointer conversion (4.2).
3540 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3541 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3542 return ImplicitConversionSequence::Indistinguishable;
3543
3544 // FIXME: the example in the standard doesn't use a qualification
3545 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003546 QualType T1 = SCS1.getToType(2);
3547 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003548 T1 = S.Context.getCanonicalType(T1);
3549 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003550 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003551 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3552 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003553
3554 // If the types are the same, we won't learn anything by unwrapped
3555 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003556 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003557 return ImplicitConversionSequence::Indistinguishable;
3558
Chandler Carruth28e318c2009-12-29 07:16:59 +00003559 // If the type is an array type, promote the element qualifiers to the type
3560 // for comparison.
3561 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003562 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003563 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003564 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003565
Mike Stump1eb44332009-09-09 15:08:12 +00003566 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003567 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003568
3569 // Objective-C++ ARC:
3570 // Prefer qualification conversions not involving a change in lifetime
3571 // to qualification conversions that do not change lifetime.
3572 if (SCS1.QualificationIncludesObjCLifetime !=
3573 SCS2.QualificationIncludesObjCLifetime) {
3574 Result = SCS1.QualificationIncludesObjCLifetime
3575 ? ImplicitConversionSequence::Worse
3576 : ImplicitConversionSequence::Better;
3577 }
3578
John McCall120d63c2010-08-24 20:38:10 +00003579 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003580 // Within each iteration of the loop, we check the qualifiers to
3581 // determine if this still looks like a qualification
3582 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003583 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003584 // until there are no more pointers or pointers-to-members left
3585 // to unwrap. This essentially mimics what
3586 // IsQualificationConversion does, but here we're checking for a
3587 // strict subset of qualifiers.
3588 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3589 // The qualifiers are the same, so this doesn't tell us anything
3590 // about how the sequences rank.
3591 ;
3592 else if (T2.isMoreQualifiedThan(T1)) {
3593 // T1 has fewer qualifiers, so it could be the better sequence.
3594 if (Result == ImplicitConversionSequence::Worse)
3595 // Neither has qualifiers that are a subset of the other's
3596 // qualifiers.
3597 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Douglas Gregor57373262008-10-22 14:17:15 +00003599 Result = ImplicitConversionSequence::Better;
3600 } else if (T1.isMoreQualifiedThan(T2)) {
3601 // T2 has fewer qualifiers, so it could be the better sequence.
3602 if (Result == ImplicitConversionSequence::Better)
3603 // Neither has qualifiers that are a subset of the other's
3604 // qualifiers.
3605 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Douglas Gregor57373262008-10-22 14:17:15 +00003607 Result = ImplicitConversionSequence::Worse;
3608 } else {
3609 // Qualifiers are disjoint.
3610 return ImplicitConversionSequence::Indistinguishable;
3611 }
3612
3613 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003614 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003615 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003616 }
3617
Douglas Gregor57373262008-10-22 14:17:15 +00003618 // Check that the winning standard conversion sequence isn't using
3619 // the deprecated string literal array to pointer conversion.
3620 switch (Result) {
3621 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003622 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003623 Result = ImplicitConversionSequence::Indistinguishable;
3624 break;
3625
3626 case ImplicitConversionSequence::Indistinguishable:
3627 break;
3628
3629 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003630 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003631 Result = ImplicitConversionSequence::Indistinguishable;
3632 break;
3633 }
3634
3635 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003636}
3637
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003638/// CompareDerivedToBaseConversions - Compares two standard conversion
3639/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003640/// various kinds of derived-to-base conversions (C++
3641/// [over.ics.rank]p4b3). As part of these checks, we also look at
3642/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003643ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003644CompareDerivedToBaseConversions(Sema &S,
3645 const StandardConversionSequence& SCS1,
3646 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003647 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003648 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003649 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003650 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003651
3652 // Adjust the types we're converting from via the array-to-pointer
3653 // conversion, if we need to.
3654 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003655 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003656 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003657 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003658
3659 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003660 FromType1 = S.Context.getCanonicalType(FromType1);
3661 ToType1 = S.Context.getCanonicalType(ToType1);
3662 FromType2 = S.Context.getCanonicalType(FromType2);
3663 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003664
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003665 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003666 //
3667 // If class B is derived directly or indirectly from class A and
3668 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003669 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003670 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003671 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003672 SCS2.Second == ICK_Pointer_Conversion &&
3673 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3674 FromType1->isPointerType() && FromType2->isPointerType() &&
3675 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003676 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003677 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003678 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003679 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003680 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003681 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003682 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003683 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003684
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003685 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003686 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003687 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003688 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003689 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003690 return ImplicitConversionSequence::Worse;
3691 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003692
3693 // -- conversion of B* to A* is better than conversion of C* to A*,
3694 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003695 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003696 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003697 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003698 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003699 }
3700 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3701 SCS2.Second == ICK_Pointer_Conversion) {
3702 const ObjCObjectPointerType *FromPtr1
3703 = FromType1->getAs<ObjCObjectPointerType>();
3704 const ObjCObjectPointerType *FromPtr2
3705 = FromType2->getAs<ObjCObjectPointerType>();
3706 const ObjCObjectPointerType *ToPtr1
3707 = ToType1->getAs<ObjCObjectPointerType>();
3708 const ObjCObjectPointerType *ToPtr2
3709 = ToType2->getAs<ObjCObjectPointerType>();
3710
3711 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3712 // Apply the same conversion ranking rules for Objective-C pointer types
3713 // that we do for C++ pointers to class types. However, we employ the
3714 // Objective-C pseudo-subtyping relationship used for assignment of
3715 // Objective-C pointer types.
3716 bool FromAssignLeft
3717 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3718 bool FromAssignRight
3719 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3720 bool ToAssignLeft
3721 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3722 bool ToAssignRight
3723 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3724
3725 // A conversion to an a non-id object pointer type or qualified 'id'
3726 // type is better than a conversion to 'id'.
3727 if (ToPtr1->isObjCIdType() &&
3728 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3729 return ImplicitConversionSequence::Worse;
3730 if (ToPtr2->isObjCIdType() &&
3731 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3732 return ImplicitConversionSequence::Better;
3733
3734 // A conversion to a non-id object pointer type is better than a
3735 // conversion to a qualified 'id' type
3736 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3737 return ImplicitConversionSequence::Worse;
3738 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3739 return ImplicitConversionSequence::Better;
3740
3741 // A conversion to an a non-Class object pointer type or qualified 'Class'
3742 // type is better than a conversion to 'Class'.
3743 if (ToPtr1->isObjCClassType() &&
3744 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3745 return ImplicitConversionSequence::Worse;
3746 if (ToPtr2->isObjCClassType() &&
3747 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3748 return ImplicitConversionSequence::Better;
3749
3750 // A conversion to a non-Class object pointer type is better than a
3751 // conversion to a qualified 'Class' type.
3752 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3753 return ImplicitConversionSequence::Worse;
3754 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3755 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Douglas Gregor395cc372011-01-31 18:51:41 +00003757 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3758 if (S.Context.hasSameType(FromType1, FromType2) &&
3759 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3760 (ToAssignLeft != ToAssignRight))
3761 return ToAssignLeft? ImplicitConversionSequence::Worse
3762 : ImplicitConversionSequence::Better;
3763
3764 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3765 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3766 (FromAssignLeft != FromAssignRight))
3767 return FromAssignLeft? ImplicitConversionSequence::Better
3768 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003769 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003770 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003771
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003772 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003773 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3774 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3775 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003777 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003779 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003781 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003783 ToType2->getAs<MemberPointerType>();
3784 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3785 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3786 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3787 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3788 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3789 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3790 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3791 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003792 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003793 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003794 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003795 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003796 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003797 return ImplicitConversionSequence::Better;
3798 }
3799 // conversion of B::* to C::* is better than conversion of A::* to C::*
3800 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003801 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003802 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003803 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003804 return ImplicitConversionSequence::Worse;
3805 }
3806 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003808 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003809 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003810 // -- binding of an expression of type C to a reference of type
3811 // B& is better than binding an expression of type C to a
3812 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003813 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3814 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3815 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003816 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003817 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003818 return ImplicitConversionSequence::Worse;
3819 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003820
Douglas Gregor225c41e2008-11-03 19:09:14 +00003821 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003822 // -- binding of an expression of type B to a reference of type
3823 // A& is better than binding an expression of type C to a
3824 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003825 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3826 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3827 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003828 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003829 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003830 return ImplicitConversionSequence::Worse;
3831 }
3832 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003833
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003834 return ImplicitConversionSequence::Indistinguishable;
3835}
3836
Douglas Gregorabe183d2010-04-13 16:31:36 +00003837/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3838/// determine whether they are reference-related,
3839/// reference-compatible, reference-compatible with added
3840/// qualification, or incompatible, for use in C++ initialization by
3841/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3842/// type, and the first type (T1) is the pointee type of the reference
3843/// type being initialized.
3844Sema::ReferenceCompareResult
3845Sema::CompareReferenceRelationship(SourceLocation Loc,
3846 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003847 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003848 bool &ObjCConversion,
3849 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003850 assert(!OrigT1->isReferenceType() &&
3851 "T1 must be the pointee type of the reference type");
3852 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3853
3854 QualType T1 = Context.getCanonicalType(OrigT1);
3855 QualType T2 = Context.getCanonicalType(OrigT2);
3856 Qualifiers T1Quals, T2Quals;
3857 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3858 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3859
3860 // C++ [dcl.init.ref]p4:
3861 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3862 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3863 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003864 DerivedToBase = false;
3865 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003866 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003867 if (UnqualT1 == UnqualT2) {
3868 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003869 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003870 IsDerivedFrom(UnqualT2, UnqualT1))
3871 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003872 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3873 UnqualT2->isObjCObjectOrInterfaceType() &&
3874 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3875 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003876 else
3877 return Ref_Incompatible;
3878
3879 // At this point, we know that T1 and T2 are reference-related (at
3880 // least).
3881
3882 // If the type is an array type, promote the element qualifiers to the type
3883 // for comparison.
3884 if (isa<ArrayType>(T1) && T1Quals)
3885 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3886 if (isa<ArrayType>(T2) && T2Quals)
3887 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3888
3889 // C++ [dcl.init.ref]p4:
3890 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3891 // reference-related to T2 and cv1 is the same cv-qualification
3892 // as, or greater cv-qualification than, cv2. For purposes of
3893 // overload resolution, cases for which cv1 is greater
3894 // cv-qualification than cv2 are identified as
3895 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003896 //
3897 // Note that we also require equivalence of Objective-C GC and address-space
3898 // qualifiers when performing these computations, so that e.g., an int in
3899 // address space 1 is not reference-compatible with an int in address
3900 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003901 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3902 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3903 T1Quals.removeObjCLifetime();
3904 T2Quals.removeObjCLifetime();
3905 ObjCLifetimeConversion = true;
3906 }
3907
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003908 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003909 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003910 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003911 return Ref_Compatible_With_Added_Qualification;
3912 else
3913 return Ref_Related;
3914}
3915
Douglas Gregor604eb652010-08-11 02:15:33 +00003916/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003917/// with DeclType. Return true if something definite is found.
3918static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003919FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3920 QualType DeclType, SourceLocation DeclLoc,
3921 Expr *Init, QualType T2, bool AllowRvalues,
3922 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003923 assert(T2->isRecordType() && "Can only find conversions of record types.");
3924 CXXRecordDecl *T2RecordDecl
3925 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3926
3927 OverloadCandidateSet CandidateSet(DeclLoc);
3928 const UnresolvedSetImpl *Conversions
3929 = T2RecordDecl->getVisibleConversionFunctions();
3930 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3931 E = Conversions->end(); I != E; ++I) {
3932 NamedDecl *D = *I;
3933 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3934 if (isa<UsingShadowDecl>(D))
3935 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3936
3937 FunctionTemplateDecl *ConvTemplate
3938 = dyn_cast<FunctionTemplateDecl>(D);
3939 CXXConversionDecl *Conv;
3940 if (ConvTemplate)
3941 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3942 else
3943 Conv = cast<CXXConversionDecl>(D);
3944
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003946 // explicit conversions, skip it.
3947 if (!AllowExplicit && Conv->isExplicit())
3948 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003949
Douglas Gregor604eb652010-08-11 02:15:33 +00003950 if (AllowRvalues) {
3951 bool DerivedToBase = false;
3952 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003953 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003954
3955 // If we are initializing an rvalue reference, don't permit conversion
3956 // functions that return lvalues.
3957 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3958 const ReferenceType *RefType
3959 = Conv->getConversionType()->getAs<LValueReferenceType>();
3960 if (RefType && !RefType->getPointeeType()->isFunctionType())
3961 continue;
3962 }
3963
Douglas Gregor604eb652010-08-11 02:15:33 +00003964 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003965 S.CompareReferenceRelationship(
3966 DeclLoc,
3967 Conv->getConversionType().getNonReferenceType()
3968 .getUnqualifiedType(),
3969 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003970 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003971 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003972 continue;
3973 } else {
3974 // If the conversion function doesn't return a reference type,
3975 // it can't be considered for this conversion. An rvalue reference
3976 // is only acceptable if its referencee is a function type.
3977
3978 const ReferenceType *RefType =
3979 Conv->getConversionType()->getAs<ReferenceType>();
3980 if (!RefType ||
3981 (!RefType->isLValueReferenceType() &&
3982 !RefType->getPointeeType()->isFunctionType()))
3983 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003984 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985
Douglas Gregor604eb652010-08-11 02:15:33 +00003986 if (ConvTemplate)
3987 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003988 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003989 else
3990 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003991 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003992 }
3993
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003994 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3995
Sebastian Redl4680bf22010-06-30 18:13:39 +00003996 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003997 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003998 case OR_Success:
3999 // C++ [over.ics.ref]p1:
4000 //
4001 // [...] If the parameter binds directly to the result of
4002 // applying a conversion function to the argument
4003 // expression, the implicit conversion sequence is a
4004 // user-defined conversion sequence (13.3.3.1.2), with the
4005 // second standard conversion sequence either an identity
4006 // conversion or, if the conversion function returns an
4007 // entity of a type that is a derived class of the parameter
4008 // type, a derived-to-base Conversion.
4009 if (!Best->FinalConversion.DirectBinding)
4010 return false;
4011
Chandler Carruth25ca4212011-02-25 19:41:05 +00004012 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004013 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004014 ICS.setUserDefined();
4015 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4016 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004017 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004018 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004019 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004020 ICS.UserDefined.EllipsisConversion = false;
4021 assert(ICS.UserDefined.After.ReferenceBinding &&
4022 ICS.UserDefined.After.DirectBinding &&
4023 "Expected a direct reference binding!");
4024 return true;
4025
4026 case OR_Ambiguous:
4027 ICS.setAmbiguous();
4028 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4029 Cand != CandidateSet.end(); ++Cand)
4030 if (Cand->Viable)
4031 ICS.Ambiguous.addConversion(Cand->Function);
4032 return true;
4033
4034 case OR_No_Viable_Function:
4035 case OR_Deleted:
4036 // There was no suitable conversion, or we found a deleted
4037 // conversion; continue with other checks.
4038 return false;
4039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004040
David Blaikie7530c032012-01-17 06:56:22 +00004041 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004042}
4043
Douglas Gregorabe183d2010-04-13 16:31:36 +00004044/// \brief Compute an implicit conversion sequence for reference
4045/// initialization.
4046static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004047TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004048 SourceLocation DeclLoc,
4049 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004050 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004051 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4052
4053 // Most paths end in a failed conversion.
4054 ImplicitConversionSequence ICS;
4055 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4056
4057 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4058 QualType T2 = Init->getType();
4059
4060 // If the initializer is the address of an overloaded function, try
4061 // to resolve the overloaded function. If all goes well, T2 is the
4062 // type of the resulting function.
4063 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4064 DeclAccessPair Found;
4065 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4066 false, Found))
4067 T2 = Fn->getType();
4068 }
4069
4070 // Compute some basic properties of the types and the initializer.
4071 bool isRValRef = DeclType->isRValueReferenceType();
4072 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004073 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004074 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004076 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004077 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004078 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004079
Douglas Gregorabe183d2010-04-13 16:31:36 +00004080
Sebastian Redl4680bf22010-06-30 18:13:39 +00004081 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004082 // A reference to type "cv1 T1" is initialized by an expression
4083 // of type "cv2 T2" as follows:
4084
Sebastian Redl4680bf22010-06-30 18:13:39 +00004085 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004086 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004087 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4088 // reference-compatible with "cv2 T2," or
4089 //
4090 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4091 if (InitCategory.isLValue() &&
4092 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004093 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004094 // When a parameter of reference type binds directly (8.5.3)
4095 // to an argument expression, the implicit conversion sequence
4096 // is the identity conversion, unless the argument expression
4097 // has a type that is a derived class of the parameter type,
4098 // in which case the implicit conversion sequence is a
4099 // derived-to-base Conversion (13.3.3.1).
4100 ICS.setStandard();
4101 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004102 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4103 : ObjCConversion? ICK_Compatible_Conversion
4104 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004105 ICS.Standard.Third = ICK_Identity;
4106 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4107 ICS.Standard.setToType(0, T2);
4108 ICS.Standard.setToType(1, T1);
4109 ICS.Standard.setToType(2, T1);
4110 ICS.Standard.ReferenceBinding = true;
4111 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004112 ICS.Standard.IsLvalueReference = !isRValRef;
4113 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4114 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004115 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004116 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004118
Sebastian Redl4680bf22010-06-30 18:13:39 +00004119 // Nothing more to do: the inaccessibility/ambiguity check for
4120 // derived-to-base conversions is suppressed when we're
4121 // computing the implicit conversion sequence (C++
4122 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004124 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004125
Sebastian Redl4680bf22010-06-30 18:13:39 +00004126 // -- has a class type (i.e., T2 is a class type), where T1 is
4127 // not reference-related to T2, and can be implicitly
4128 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4129 // is reference-compatible with "cv3 T3" 92) (this
4130 // conversion is selected by enumerating the applicable
4131 // conversion functions (13.3.1.6) and choosing the best
4132 // one through overload resolution (13.3)),
4133 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004134 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004135 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004136 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4137 Init, T2, /*AllowRvalues=*/false,
4138 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004139 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004140 }
4141 }
4142
Sebastian Redl4680bf22010-06-30 18:13:39 +00004143 // -- Otherwise, the reference shall be an lvalue reference to a
4144 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004145 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004147 // We actually handle one oddity of C++ [over.ics.ref] at this
4148 // point, which is that, due to p2 (which short-circuits reference
4149 // binding by only attempting a simple conversion for non-direct
4150 // bindings) and p3's strange wording, we allow a const volatile
4151 // reference to bind to an rvalue. Hence the check for the presence
4152 // of "const" rather than checking for "const" being the only
4153 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004154 // This is also the point where rvalue references and lvalue inits no longer
4155 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004156 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004157 return ICS;
4158
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004159 // -- If the initializer expression
4160 //
4161 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004162 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004163 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4164 (InitCategory.isXValue() ||
4165 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4166 (InitCategory.isLValue() && T2->isFunctionType()))) {
4167 ICS.setStandard();
4168 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004170 : ObjCConversion? ICK_Compatible_Conversion
4171 : ICK_Identity;
4172 ICS.Standard.Third = ICK_Identity;
4173 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4174 ICS.Standard.setToType(0, T2);
4175 ICS.Standard.setToType(1, T1);
4176 ICS.Standard.setToType(2, T1);
4177 ICS.Standard.ReferenceBinding = true;
4178 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4179 // binding unless we're binding to a class prvalue.
4180 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4181 // allow the use of rvalue references in C++98/03 for the benefit of
4182 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004183 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004184 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004185 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004186 ICS.Standard.IsLvalueReference = !isRValRef;
4187 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004188 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004189 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004190 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004191 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004193 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004194
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004195 // -- has a class type (i.e., T2 is a class type), where T1 is not
4196 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197 // an xvalue, class prvalue, or function lvalue of type
4198 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004199 // "cv3 T3",
4200 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004202 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004203 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004204 // class subobject).
4205 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004207 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4208 Init, T2, /*AllowRvalues=*/true,
4209 AllowExplicit)) {
4210 // In the second case, if the reference is an rvalue reference
4211 // and the second standard conversion sequence of the
4212 // user-defined conversion sequence includes an lvalue-to-rvalue
4213 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004215 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4216 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4217
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004218 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004220
Douglas Gregorabe183d2010-04-13 16:31:36 +00004221 // -- Otherwise, a temporary of type "cv1 T1" is created and
4222 // initialized from the initializer expression using the
4223 // rules for a non-reference copy initialization (8.5). The
4224 // reference is then bound to the temporary. If T1 is
4225 // reference-related to T2, cv1 must be the same
4226 // cv-qualification as, or greater cv-qualification than,
4227 // cv2; otherwise, the program is ill-formed.
4228 if (RefRelationship == Sema::Ref_Related) {
4229 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4230 // we would be reference-compatible or reference-compatible with
4231 // added qualification. But that wasn't the case, so the reference
4232 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004233 //
4234 // Note that we only want to check address spaces and cvr-qualifiers here.
4235 // ObjC GC and lifetime qualifiers aren't important.
4236 Qualifiers T1Quals = T1.getQualifiers();
4237 Qualifiers T2Quals = T2.getQualifiers();
4238 T1Quals.removeObjCGCAttr();
4239 T1Quals.removeObjCLifetime();
4240 T2Quals.removeObjCGCAttr();
4241 T2Quals.removeObjCLifetime();
4242 if (!T1Quals.compatiblyIncludes(T2Quals))
4243 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004244 }
4245
4246 // If at least one of the types is a class type, the types are not
4247 // related, and we aren't allowed any user conversions, the
4248 // reference binding fails. This case is important for breaking
4249 // recursion, since TryImplicitConversion below will attempt to
4250 // create a temporary through the use of a copy constructor.
4251 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4252 (T1->isRecordType() || T2->isRecordType()))
4253 return ICS;
4254
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004255 // If T1 is reference-related to T2 and the reference is an rvalue
4256 // reference, the initializer expression shall not be an lvalue.
4257 if (RefRelationship >= Sema::Ref_Related &&
4258 isRValRef && Init->Classify(S.Context).isLValue())
4259 return ICS;
4260
Douglas Gregorabe183d2010-04-13 16:31:36 +00004261 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004262 // When a parameter of reference type is not bound directly to
4263 // an argument expression, the conversion sequence is the one
4264 // required to convert the argument expression to the
4265 // underlying type of the reference according to
4266 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4267 // to copy-initializing a temporary of the underlying type with
4268 // the argument expression. Any difference in top-level
4269 // cv-qualification is subsumed by the initialization itself
4270 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004271 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4272 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004273 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004274 /*CStyle=*/false,
4275 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004276
4277 // Of course, that's still a reference binding.
4278 if (ICS.isStandard()) {
4279 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004280 ICS.Standard.IsLvalueReference = !isRValRef;
4281 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4282 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004283 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004284 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004285 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004286 // Don't allow rvalue references to bind to lvalues.
4287 if (DeclType->isRValueReferenceType()) {
4288 if (const ReferenceType *RefType
4289 = ICS.UserDefined.ConversionFunction->getResultType()
4290 ->getAs<LValueReferenceType>()) {
4291 if (!RefType->getPointeeType()->isFunctionType()) {
4292 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4293 DeclType);
4294 return ICS;
4295 }
4296 }
4297 }
4298
Douglas Gregorabe183d2010-04-13 16:31:36 +00004299 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004300 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4301 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4302 ICS.UserDefined.After.BindsToRvalue = true;
4303 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4304 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004305 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004306
Douglas Gregorabe183d2010-04-13 16:31:36 +00004307 return ICS;
4308}
4309
Sebastian Redl5405b812011-10-16 18:19:34 +00004310static ImplicitConversionSequence
4311TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4312 bool SuppressUserConversions,
4313 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004314 bool AllowObjCWritebackConversion,
4315 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004316
4317/// TryListConversion - Try to copy-initialize a value of type ToType from the
4318/// initializer list From.
4319static ImplicitConversionSequence
4320TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4321 bool SuppressUserConversions,
4322 bool InOverloadResolution,
4323 bool AllowObjCWritebackConversion) {
4324 // C++11 [over.ics.list]p1:
4325 // When an argument is an initializer list, it is not an expression and
4326 // special rules apply for converting it to a parameter type.
4327
4328 ImplicitConversionSequence Result;
4329 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004330 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004331
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004332 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004333 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004334 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004335 return Result;
4336
Sebastian Redl5405b812011-10-16 18:19:34 +00004337 // C++11 [over.ics.list]p2:
4338 // If the parameter type is std::initializer_list<X> or "array of X" and
4339 // all the elements can be implicitly converted to X, the implicit
4340 // conversion sequence is the worst conversion necessary to convert an
4341 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004342 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004343 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004344 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004345 X = S.Context.getBaseElementType(ToType);
4346 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004347 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004348 if (!X.isNull()) {
4349 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4350 Expr *Init = From->getInit(i);
4351 ImplicitConversionSequence ICS =
4352 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4353 InOverloadResolution,
4354 AllowObjCWritebackConversion);
4355 // If a single element isn't convertible, fail.
4356 if (ICS.isBad()) {
4357 Result = ICS;
4358 break;
4359 }
4360 // Otherwise, look for the worst conversion.
4361 if (Result.isBad() ||
4362 CompareImplicitConversionSequences(S, ICS, Result) ==
4363 ImplicitConversionSequence::Worse)
4364 Result = ICS;
4365 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004366
4367 // For an empty list, we won't have computed any conversion sequence.
4368 // Introduce the identity conversion sequence.
4369 if (From->getNumInits() == 0) {
4370 Result.setStandard();
4371 Result.Standard.setAsIdentityConversion();
4372 Result.Standard.setFromType(ToType);
4373 Result.Standard.setAllToTypes(ToType);
4374 }
4375
Sebastian Redlfe592282012-01-17 22:49:48 +00004376 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004377 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004378 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004379 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004380
4381 // C++11 [over.ics.list]p3:
4382 // Otherwise, if the parameter is a non-aggregate class X and overload
4383 // resolution chooses a single best constructor [...] the implicit
4384 // conversion sequence is a user-defined conversion sequence. If multiple
4385 // constructors are viable but none is better than the others, the
4386 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004387 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4388 // This function can deal with initializer lists.
4389 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4390 /*AllowExplicit=*/false,
4391 InOverloadResolution, /*CStyle=*/false,
4392 AllowObjCWritebackConversion);
4393 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004394 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004395 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004396
4397 // C++11 [over.ics.list]p4:
4398 // Otherwise, if the parameter has an aggregate type which can be
4399 // initialized from the initializer list [...] the implicit conversion
4400 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004401 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004402 // Type is an aggregate, argument is an init list. At this point it comes
4403 // down to checking whether the initialization works.
4404 // FIXME: Find out whether this parameter is consumed or not.
4405 InitializedEntity Entity =
4406 InitializedEntity::InitializeParameter(S.Context, ToType,
4407 /*Consumed=*/false);
4408 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4409 Result.setUserDefined();
4410 Result.UserDefined.Before.setAsIdentityConversion();
4411 // Initializer lists don't have a type.
4412 Result.UserDefined.Before.setFromType(QualType());
4413 Result.UserDefined.Before.setAllToTypes(QualType());
4414
4415 Result.UserDefined.After.setAsIdentityConversion();
4416 Result.UserDefined.After.setFromType(ToType);
4417 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004418 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004419 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004420 return Result;
4421 }
4422
4423 // C++11 [over.ics.list]p5:
4424 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004425 if (ToType->isReferenceType()) {
4426 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4427 // mention initializer lists in any way. So we go by what list-
4428 // initialization would do and try to extrapolate from that.
4429
4430 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4431
4432 // If the initializer list has a single element that is reference-related
4433 // to the parameter type, we initialize the reference from that.
4434 if (From->getNumInits() == 1) {
4435 Expr *Init = From->getInit(0);
4436
4437 QualType T2 = Init->getType();
4438
4439 // If the initializer is the address of an overloaded function, try
4440 // to resolve the overloaded function. If all goes well, T2 is the
4441 // type of the resulting function.
4442 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4443 DeclAccessPair Found;
4444 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4445 Init, ToType, false, Found))
4446 T2 = Fn->getType();
4447 }
4448
4449 // Compute some basic properties of the types and the initializer.
4450 bool dummy1 = false;
4451 bool dummy2 = false;
4452 bool dummy3 = false;
4453 Sema::ReferenceCompareResult RefRelationship
4454 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4455 dummy2, dummy3);
4456
4457 if (RefRelationship >= Sema::Ref_Related)
4458 return TryReferenceInit(S, Init, ToType,
4459 /*FIXME:*/From->getLocStart(),
4460 SuppressUserConversions,
4461 /*AllowExplicit=*/false);
4462 }
4463
4464 // Otherwise, we bind the reference to a temporary created from the
4465 // initializer list.
4466 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4467 InOverloadResolution,
4468 AllowObjCWritebackConversion);
4469 if (Result.isFailure())
4470 return Result;
4471 assert(!Result.isEllipsis() &&
4472 "Sub-initialization cannot result in ellipsis conversion.");
4473
4474 // Can we even bind to a temporary?
4475 if (ToType->isRValueReferenceType() ||
4476 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4477 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4478 Result.UserDefined.After;
4479 SCS.ReferenceBinding = true;
4480 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4481 SCS.BindsToRvalue = true;
4482 SCS.BindsToFunctionLvalue = false;
4483 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4484 SCS.ObjCLifetimeConversionBinding = false;
4485 } else
4486 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4487 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004488 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004489 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004490
4491 // C++11 [over.ics.list]p6:
4492 // Otherwise, if the parameter type is not a class:
4493 if (!ToType->isRecordType()) {
4494 // - if the initializer list has one element, the implicit conversion
4495 // sequence is the one required to convert the element to the
4496 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004497 unsigned NumInits = From->getNumInits();
4498 if (NumInits == 1)
4499 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4500 SuppressUserConversions,
4501 InOverloadResolution,
4502 AllowObjCWritebackConversion);
4503 // - if the initializer list has no elements, the implicit conversion
4504 // sequence is the identity conversion.
4505 else if (NumInits == 0) {
4506 Result.setStandard();
4507 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004508 Result.Standard.setFromType(ToType);
4509 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004510 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004511 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004512 return Result;
4513 }
4514
4515 // C++11 [over.ics.list]p7:
4516 // In all cases other than those enumerated above, no conversion is possible
4517 return Result;
4518}
4519
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004520/// TryCopyInitialization - Try to copy-initialize a value of type
4521/// ToType from the expression From. Return the implicit conversion
4522/// sequence required to pass this argument, which may be a bad
4523/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004524/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004525/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004526static ImplicitConversionSequence
4527TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004528 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004529 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004530 bool AllowObjCWritebackConversion,
4531 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004532 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4533 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4534 InOverloadResolution,AllowObjCWritebackConversion);
4535
Douglas Gregorabe183d2010-04-13 16:31:36 +00004536 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004537 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004538 /*FIXME:*/From->getLocStart(),
4539 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004540 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004541
John McCall120d63c2010-08-24 20:38:10 +00004542 return TryImplicitConversion(S, From, ToType,
4543 SuppressUserConversions,
4544 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004545 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004546 /*CStyle=*/false,
4547 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004548}
4549
Anna Zaksf3546ee2011-07-28 19:46:48 +00004550static bool TryCopyInitialization(const CanQualType FromQTy,
4551 const CanQualType ToQTy,
4552 Sema &S,
4553 SourceLocation Loc,
4554 ExprValueKind FromVK) {
4555 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4556 ImplicitConversionSequence ICS =
4557 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4558
4559 return !ICS.isBad();
4560}
4561
Douglas Gregor96176b32008-11-18 23:14:02 +00004562/// TryObjectArgumentInitialization - Try to initialize the object
4563/// parameter of the given member function (@c Method) from the
4564/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004565static ImplicitConversionSequence
4566TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004567 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004568 CXXMethodDecl *Method,
4569 CXXRecordDecl *ActingContext) {
4570 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004571 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4572 // const volatile object.
4573 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4574 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004575 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004576
4577 // Set up the conversion sequence as a "bad" conversion, to allow us
4578 // to exit early.
4579 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004580
4581 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004582 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004583 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004584 FromType = PT->getPointeeType();
4585
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004586 // When we had a pointer, it's implicitly dereferenced, so we
4587 // better have an lvalue.
4588 assert(FromClassification.isLValue());
4589 }
4590
Anders Carlssona552f7c2009-05-01 18:34:30 +00004591 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004592
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004593 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004595 // parameter is
4596 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004597 // - "lvalue reference to cv X" for functions declared without a
4598 // ref-qualifier or with the & ref-qualifier
4599 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004600 // ref-qualifier
4601 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004602 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004603 // cv-qualification on the member function declaration.
4604 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004606 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004607 // (C++ [over.match.funcs]p5). We perform a simplified version of
4608 // reference binding here, that allows class rvalues to bind to
4609 // non-constant references.
4610
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004611 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004612 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004613 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004614 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004615 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004616 ICS.setBad(BadConversionSequence::bad_qualifiers,
4617 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004618 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004619 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004620
4621 // Check that we have either the same type or a derived type. It
4622 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004623 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004624 ImplicitConversionKind SecondKind;
4625 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4626 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004627 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004628 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004629 else {
John McCallb1bdc622010-02-25 01:37:24 +00004630 ICS.setBad(BadConversionSequence::unrelated_class,
4631 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004632 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004633 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004634
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004635 // Check the ref-qualifier.
4636 switch (Method->getRefQualifier()) {
4637 case RQ_None:
4638 // Do nothing; we don't care about lvalueness or rvalueness.
4639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004641 case RQ_LValue:
4642 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4643 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004645 ImplicitParamType);
4646 return ICS;
4647 }
4648 break;
4649
4650 case RQ_RValue:
4651 if (!FromClassification.isRValue()) {
4652 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004654 ImplicitParamType);
4655 return ICS;
4656 }
4657 break;
4658 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
Douglas Gregor96176b32008-11-18 23:14:02 +00004660 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004661 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004662 ICS.Standard.setAsIdentityConversion();
4663 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004664 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004665 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004666 ICS.Standard.ReferenceBinding = true;
4667 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004668 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004669 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004670 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4671 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4672 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004673 return ICS;
4674}
4675
4676/// PerformObjectArgumentInitialization - Perform initialization of
4677/// the implicit object parameter for the given Method with the given
4678/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004679ExprResult
4680Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004681 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004682 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004683 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004684 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004685 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004686 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004688 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004689 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004690 FromRecordType = PT->getPointeeType();
4691 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004692 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004693 } else {
4694 FromRecordType = From->getType();
4695 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004696 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004697 }
4698
John McCall701c89e2009-12-03 04:06:58 +00004699 // Note that we always use the true parent context when performing
4700 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004701 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004702 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4703 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004704 if (ICS.isBad()) {
4705 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4706 Qualifiers FromQs = FromRecordType.getQualifiers();
4707 Qualifiers ToQs = DestType.getQualifiers();
4708 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4709 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004710 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004711 diag::err_member_function_call_bad_cvr)
4712 << Method->getDeclName() << FromRecordType << (CVR - 1)
4713 << From->getSourceRange();
4714 Diag(Method->getLocation(), diag::note_previous_decl)
4715 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004716 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004717 }
4718 }
4719
Daniel Dunbar96a00142012-03-09 18:35:03 +00004720 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004721 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004722 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004723 }
Mike Stump1eb44332009-09-09 15:08:12 +00004724
John Wiegley429bb272011-04-08 18:41:53 +00004725 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4726 ExprResult FromRes =
4727 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4728 if (FromRes.isInvalid())
4729 return ExprError();
4730 From = FromRes.take();
4731 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004732
Douglas Gregor5fccd362010-03-03 23:55:11 +00004733 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004734 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004735 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004736 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004737}
4738
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004739/// TryContextuallyConvertToBool - Attempt to contextually convert the
4740/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004741static ImplicitConversionSequence
4742TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004743 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004744 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004745 // FIXME: Are these flags correct?
4746 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004747 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004748 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004749 /*CStyle=*/false,
4750 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004751}
4752
4753/// PerformContextuallyConvertToBool - Perform a contextual conversion
4754/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004755ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004756 if (checkPlaceholderForOverload(*this, From))
4757 return ExprError();
4758
John McCall120d63c2010-08-24 20:38:10 +00004759 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004760 if (!ICS.isBad())
4761 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004762
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004763 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004764 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004765 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004766 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004767 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004768}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004769
Richard Smith8ef7b202012-01-18 23:55:52 +00004770/// Check that the specified conversion is permitted in a converted constant
4771/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4772/// is acceptable.
4773static bool CheckConvertedConstantConversions(Sema &S,
4774 StandardConversionSequence &SCS) {
4775 // Since we know that the target type is an integral or unscoped enumeration
4776 // type, most conversion kinds are impossible. All possible First and Third
4777 // conversions are fine.
4778 switch (SCS.Second) {
4779 case ICK_Identity:
4780 case ICK_Integral_Promotion:
4781 case ICK_Integral_Conversion:
4782 return true;
4783
4784 case ICK_Boolean_Conversion:
4785 // Conversion from an integral or unscoped enumeration type to bool is
4786 // classified as ICK_Boolean_Conversion, but it's also an integral
4787 // conversion, so it's permitted in a converted constant expression.
4788 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4789 SCS.getToType(2)->isBooleanType();
4790
4791 case ICK_Floating_Integral:
4792 case ICK_Complex_Real:
4793 return false;
4794
4795 case ICK_Lvalue_To_Rvalue:
4796 case ICK_Array_To_Pointer:
4797 case ICK_Function_To_Pointer:
4798 case ICK_NoReturn_Adjustment:
4799 case ICK_Qualification:
4800 case ICK_Compatible_Conversion:
4801 case ICK_Vector_Conversion:
4802 case ICK_Vector_Splat:
4803 case ICK_Derived_To_Base:
4804 case ICK_Pointer_Conversion:
4805 case ICK_Pointer_Member:
4806 case ICK_Block_Pointer_Conversion:
4807 case ICK_Writeback_Conversion:
4808 case ICK_Floating_Promotion:
4809 case ICK_Complex_Promotion:
4810 case ICK_Complex_Conversion:
4811 case ICK_Floating_Conversion:
4812 case ICK_TransparentUnionConversion:
4813 llvm_unreachable("unexpected second conversion kind");
4814
4815 case ICK_Num_Conversion_Kinds:
4816 break;
4817 }
4818
4819 llvm_unreachable("unknown conversion kind");
4820}
4821
4822/// CheckConvertedConstantExpression - Check that the expression From is a
4823/// converted constant expression of type T, perform the conversion and produce
4824/// the converted expression, per C++11 [expr.const]p3.
4825ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4826 llvm::APSInt &Value,
4827 CCEKind CCE) {
4828 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4829 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4830
4831 if (checkPlaceholderForOverload(*this, From))
4832 return ExprError();
4833
4834 // C++11 [expr.const]p3 with proposed wording fixes:
4835 // A converted constant expression of type T is a core constant expression,
4836 // implicitly converted to a prvalue of type T, where the converted
4837 // expression is a literal constant expression and the implicit conversion
4838 // sequence contains only user-defined conversions, lvalue-to-rvalue
4839 // conversions, integral promotions, and integral conversions other than
4840 // narrowing conversions.
4841 ImplicitConversionSequence ICS =
4842 TryImplicitConversion(From, T,
4843 /*SuppressUserConversions=*/false,
4844 /*AllowExplicit=*/false,
4845 /*InOverloadResolution=*/false,
4846 /*CStyle=*/false,
4847 /*AllowObjcWritebackConversion=*/false);
4848 StandardConversionSequence *SCS = 0;
4849 switch (ICS.getKind()) {
4850 case ImplicitConversionSequence::StandardConversion:
4851 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004852 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004853 diag::err_typecheck_converted_constant_expression_disallowed)
4854 << From->getType() << From->getSourceRange() << T;
4855 SCS = &ICS.Standard;
4856 break;
4857 case ImplicitConversionSequence::UserDefinedConversion:
4858 // We are converting from class type to an integral or enumeration type, so
4859 // the Before sequence must be trivial.
4860 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel 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.UserDefined.After;
4865 break;
4866 case ImplicitConversionSequence::AmbiguousConversion:
4867 case ImplicitConversionSequence::BadConversion:
4868 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004869 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004870 diag::err_typecheck_converted_constant_expression)
4871 << From->getType() << From->getSourceRange() << T;
4872 return ExprError();
4873
4874 case ImplicitConversionSequence::EllipsisConversion:
4875 llvm_unreachable("ellipsis conversion in converted constant expression");
4876 }
4877
4878 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4879 if (Result.isInvalid())
4880 return Result;
4881
4882 // Check for a narrowing implicit conversion.
4883 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004884 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004885 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4886 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004887 case NK_Variable_Narrowing:
4888 // Implicit conversion to a narrower type, and the value is not a constant
4889 // expression. We'll diagnose this in a moment.
4890 case NK_Not_Narrowing:
4891 break;
4892
4893 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004894 Diag(From->getLocStart(),
4895 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4896 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004897 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004898 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004899 break;
4900
4901 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004902 Diag(From->getLocStart(),
4903 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4904 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004905 << CCE << /*Constant*/0 << From->getType() << T;
4906 break;
4907 }
4908
4909 // Check the expression is a constant expression.
4910 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4911 Expr::EvalResult Eval;
4912 Eval.Diag = &Notes;
4913
4914 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4915 // The expression can't be folded, so we can't keep it at this position in
4916 // the AST.
4917 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004918 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004919 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004920
4921 if (Notes.empty()) {
4922 // It's a constant expression.
4923 return Result;
4924 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004925 }
4926
4927 // It's not a constant expression. Produce an appropriate diagnostic.
4928 if (Notes.size() == 1 &&
4929 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4930 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4931 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004932 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004933 << CCE << From->getSourceRange();
4934 for (unsigned I = 0; I < Notes.size(); ++I)
4935 Diag(Notes[I].first, Notes[I].second);
4936 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004937 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004938}
4939
John McCall0bcc9bc2011-09-09 06:11:02 +00004940/// dropPointerConversions - If the given standard conversion sequence
4941/// involves any pointer conversions, remove them. This may change
4942/// the result type of the conversion sequence.
4943static void dropPointerConversion(StandardConversionSequence &SCS) {
4944 if (SCS.Second == ICK_Pointer_Conversion) {
4945 SCS.Second = ICK_Identity;
4946 SCS.Third = ICK_Identity;
4947 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4948 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004949}
John McCall120d63c2010-08-24 20:38:10 +00004950
John McCall0bcc9bc2011-09-09 06:11:02 +00004951/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4952/// convert the expression From to an Objective-C pointer type.
4953static ImplicitConversionSequence
4954TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4955 // Do an implicit conversion to 'id'.
4956 QualType Ty = S.Context.getObjCIdType();
4957 ImplicitConversionSequence ICS
4958 = TryImplicitConversion(S, From, Ty,
4959 // FIXME: Are these flags correct?
4960 /*SuppressUserConversions=*/false,
4961 /*AllowExplicit=*/true,
4962 /*InOverloadResolution=*/false,
4963 /*CStyle=*/false,
4964 /*AllowObjCWritebackConversion=*/false);
4965
4966 // Strip off any final conversions to 'id'.
4967 switch (ICS.getKind()) {
4968 case ImplicitConversionSequence::BadConversion:
4969 case ImplicitConversionSequence::AmbiguousConversion:
4970 case ImplicitConversionSequence::EllipsisConversion:
4971 break;
4972
4973 case ImplicitConversionSequence::UserDefinedConversion:
4974 dropPointerConversion(ICS.UserDefined.After);
4975 break;
4976
4977 case ImplicitConversionSequence::StandardConversion:
4978 dropPointerConversion(ICS.Standard);
4979 break;
4980 }
4981
4982 return ICS;
4983}
4984
4985/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4986/// conversion of the expression From to an Objective-C pointer type.
4987ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004988 if (checkPlaceholderForOverload(*this, From))
4989 return ExprError();
4990
John McCallc12c5bb2010-05-15 11:32:37 +00004991 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004992 ImplicitConversionSequence ICS =
4993 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004994 if (!ICS.isBad())
4995 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004996 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004997}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004998
Richard Smithf39aec12012-02-04 07:07:42 +00004999/// Determine whether the provided type is an integral type, or an enumeration
5000/// type of a permitted flavor.
5001static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5002 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5003 : T->isIntegralOrUnscopedEnumerationType();
5004}
5005
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005006/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005007/// enumeration type.
5008///
5009/// This routine will attempt to convert an expression of class type to an
5010/// integral or enumeration type, if that class type only has a single
5011/// conversion to an integral or enumeration type.
5012///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005013/// \param Loc The source location of the construct that requires the
5014/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005015///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005016/// \param FromE The expression we're converting from.
5017///
5018/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5019/// have integral or enumeration type.
5020///
5021/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5022/// incomplete class type.
5023///
5024/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5025/// explicit conversion function (because no implicit conversion functions
5026/// were available). This is a recovery mode.
5027///
5028/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5029/// showing which conversion was picked.
5030///
5031/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5032/// conversion function that could convert to integral or enumeration type.
5033///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005034/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005035/// usable conversion function.
5036///
5037/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5038/// function, which may be an extension in this case.
5039///
Richard Smithf39aec12012-02-04 07:07:42 +00005040/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5041/// enumerations should be considered.
5042///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005043/// \returns The expression, converted to an integral or enumeration type if
5044/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005045ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005046Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005047 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005048 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005049 // We can't perform any more checking for type-dependent expressions.
5050 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005051 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005052
Eli Friedmanceccab92012-01-26 00:26:18 +00005053 // Process placeholders immediately.
5054 if (From->hasPlaceholderType()) {
5055 ExprResult result = CheckPlaceholderExpr(From);
5056 if (result.isInvalid()) return result;
5057 From = result.take();
5058 }
5059
Douglas Gregorc30614b2010-06-29 23:17:37 +00005060 // If the expression already has integral or enumeration type, we're golden.
5061 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005062 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005063 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005064
5065 // FIXME: Check for missing '()' if T is a function type?
5066
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00005068 // expression of integral or enumeration type.
5069 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005070 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005071 if (!Diagnoser.Suppress)
5072 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005073 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005075
Douglas Gregorc30614b2010-06-29 23:17:37 +00005076 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005077 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005078 ICEConvertDiagnoser &Diagnoser;
5079 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005080
Douglas Gregorab41fe92012-05-04 22:38:52 +00005081 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5082 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005083
5084 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005085 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005086 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005087 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005088
5089 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005090 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregorc30614b2010-06-29 23:17:37 +00005092 // Look for a conversion to an integral or enumeration type.
5093 UnresolvedSet<4> ViableConversions;
5094 UnresolvedSet<4> ExplicitConversions;
5095 const UnresolvedSetImpl *Conversions
5096 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005097
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005098 bool HadMultipleCandidates = (Conversions->size() > 1);
5099
Douglas Gregorc30614b2010-06-29 23:17:37 +00005100 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101 E = Conversions->end();
5102 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005103 ++I) {
5104 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005105 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5106 if (isIntegralOrEnumerationType(
5107 Conversion->getConversionType().getNonReferenceType(),
5108 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005109 if (Conversion->isExplicit())
5110 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5111 else
5112 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5113 }
Richard Smithf39aec12012-02-04 07:07:42 +00005114 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005116
Douglas Gregorc30614b2010-06-29 23:17:37 +00005117 switch (ViableConversions.size()) {
5118 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005119 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120 DeclAccessPair Found = ExplicitConversions[0];
5121 CXXConversionDecl *Conversion
5122 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123
Douglas Gregorc30614b2010-06-29 23:17:37 +00005124 // The user probably meant to invoke the given explicit
5125 // conversion; use it.
5126 QualType ConvTy
5127 = Conversion->getConversionType().getNonReferenceType();
5128 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005129 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005130
Douglas Gregorab41fe92012-05-04 22:38:52 +00005131 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005132 << FixItHint::CreateInsertion(From->getLocStart(),
5133 "static_cast<" + TypeStr + ">(")
5134 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5135 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005136 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137
5138 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005139 // explicit conversion function.
5140 if (isSFINAEContext())
5141 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142
Douglas Gregorc30614b2010-06-29 23:17:37 +00005143 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005144 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5145 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005146 if (Result.isInvalid())
5147 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005148 // Record usage of conversion in an implicit cast.
5149 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5150 CK_UserDefinedConversion,
5151 Result.get(), 0,
5152 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005153 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005154
Douglas Gregorc30614b2010-06-29 23:17:37 +00005155 // We'll complain below about a non-integral condition type.
5156 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Douglas Gregorc30614b2010-06-29 23:17:37 +00005158 case 1: {
5159 // Apply this conversion.
5160 DeclAccessPair Found = ViableConversions[0];
5161 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005162
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005163 CXXConversionDecl *Conversion
5164 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5165 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005166 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005167 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005168 if (isSFINAEContext())
5169 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005170
Douglas Gregorab41fe92012-05-04 22:38:52 +00005171 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5172 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005173 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005174
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005175 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5176 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005177 if (Result.isInvalid())
5178 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005179 // Record usage of conversion in an implicit cast.
5180 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5181 CK_UserDefinedConversion,
5182 Result.get(), 0,
5183 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005184 break;
5185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186
Douglas Gregorc30614b2010-06-29 23:17:37 +00005187 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005188 if (Diagnoser.Suppress)
5189 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005190
Douglas Gregorab41fe92012-05-04 22:38:52 +00005191 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005192 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5193 CXXConversionDecl *Conv
5194 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5195 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005196 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005197 }
John McCall9ae2f072010-08-23 23:25:46 +00005198 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005199 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005200
Richard Smith282e7e62012-02-04 09:53:13 +00005201 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005202 !Diagnoser.Suppress) {
5203 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5204 << From->getSourceRange();
5205 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005206
Eli Friedmanceccab92012-01-26 00:26:18 +00005207 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005208}
5209
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005210/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005211/// candidate functions, using the given function call arguments. If
5212/// @p SuppressUserConversions, then don't allow user-defined
5213/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005214///
5215/// \para PartialOverloading true if we are performing "partial" overloading
5216/// based on an incomplete set of function arguments. This feature is used by
5217/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005218void
5219Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005220 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005221 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005222 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005223 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005224 bool PartialOverloading,
5225 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005226 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005227 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005228 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005229 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005230 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005231
Douglas Gregor88a35142008-12-22 05:46:06 +00005232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005233 if (!isa<CXXConstructorDecl>(Method)) {
5234 // If we get here, it's because we're calling a member function
5235 // that is named without a member access expression (e.g.,
5236 // "this->f") that was either written explicitly or created
5237 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005238 // function, e.g., X::f(). We use an empty type for the implied
5239 // object argument (C++ [over.call.func]p3), and the acting context
5240 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005241 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005242 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005243 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005244 return;
5245 }
5246 // We treat a constructor like a non-member function, since its object
5247 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005248 }
5249
Douglas Gregorfd476482009-11-13 23:59:09 +00005250 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005251 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005252
Douglas Gregor7edfb692009-11-23 12:27:39 +00005253 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005254 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005255
Douglas Gregor66724ea2009-11-14 01:20:54 +00005256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5257 // C++ [class.copy]p3:
5258 // A member function template is never instantiated to perform the copy
5259 // of a class object to an object of its class type.
5260 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005261 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005262 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005263 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5264 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005265 return;
5266 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005267
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005268 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005269 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005270 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005271 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005272 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005273 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005274 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005275 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005276
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005277 unsigned NumArgsInProto = Proto->getNumArgs();
5278
5279 // (C++ 13.3.2p2): A candidate function having fewer than m
5280 // parameters is viable only if it has an ellipsis in its parameter
5281 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005282 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005283 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005284 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005285 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005286 return;
5287 }
5288
5289 // (C++ 13.3.2p2): A candidate function having more than m parameters
5290 // is viable only if the (m+1)st parameter has a default argument
5291 // (8.3.6). For the purposes of overload resolution, the
5292 // parameter list is truncated on the right, so that there are
5293 // exactly m parameters.
5294 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005295 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005296 // Not enough arguments.
5297 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005298 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005299 return;
5300 }
5301
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005302 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005303 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005304 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5305 if (CheckCUDATarget(Caller, Function)) {
5306 Candidate.Viable = false;
5307 Candidate.FailureKind = ovl_fail_bad_target;
5308 return;
5309 }
5310
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005311 // Determine the implicit conversion sequences for each of the
5312 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005313 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005314 if (ArgIdx < NumArgsInProto) {
5315 // (C++ 13.3.2p3): for F to be a viable function, there shall
5316 // exist for each argument an implicit conversion sequence
5317 // (13.3.3.1) that converts that argument to the corresponding
5318 // parameter of F.
5319 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005320 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005321 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005322 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005323 /*InOverloadResolution=*/true,
5324 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005325 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005326 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005327 if (Candidate.Conversions[ArgIdx].isBad()) {
5328 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005329 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005330 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005331 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005332 } else {
5333 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5334 // argument for which there is no corresponding parameter is
5335 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005336 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005337 }
5338 }
5339}
5340
Douglas Gregor063daf62009-03-13 18:40:31 +00005341/// \brief Add all of the function declarations in the given function set to
5342/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005343void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005344 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005345 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005346 bool SuppressUserConversions,
5347 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005348 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005349 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5350 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005351 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005352 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005353 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005354 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005355 Args.slice(1), CandidateSet,
5356 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005357 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005358 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005359 SuppressUserConversions);
5360 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005361 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005362 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5363 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005364 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005365 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005366 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005367 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005368 Args[0]->Classify(Context), Args.slice(1),
5369 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005370 else
John McCall9aa472c2010-03-19 07:35:19 +00005371 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005372 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005373 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005374 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005375 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005376}
5377
John McCall314be4e2009-11-17 07:50:12 +00005378/// AddMethodCandidate - Adds a named decl (which is some kind of
5379/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005380void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005381 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005382 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005383 Expr **Args, unsigned NumArgs,
5384 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005385 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005386 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005387 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005388
5389 if (isa<UsingShadowDecl>(Decl))
5390 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005391
John McCall314be4e2009-11-17 07:50:12 +00005392 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5393 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5394 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005395 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5396 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005397 ObjectType, ObjectClassification,
5398 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005399 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005400 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005401 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005402 ObjectType, ObjectClassification,
5403 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005404 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005405 }
5406}
5407
Douglas Gregor96176b32008-11-18 23:14:02 +00005408/// AddMethodCandidate - Adds the given C++ member function to the set
5409/// of candidate functions, using the given function call arguments
5410/// and the object argument (@c Object). For example, in a call
5411/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5412/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5413/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005414/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005415void
John McCall9aa472c2010-03-19 07:35:19 +00005416Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005417 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005418 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005419 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005420 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005421 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005422 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005423 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005424 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005425 assert(!isa<CXXConstructorDecl>(Method) &&
5426 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005427
Douglas Gregor3f396022009-09-28 04:47:19 +00005428 if (!CandidateSet.isNewCandidate(Method))
5429 return;
5430
Douglas Gregor7edfb692009-11-23 12:27:39 +00005431 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005432 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005433
Douglas Gregor96176b32008-11-18 23:14:02 +00005434 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005435 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005436 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005437 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005438 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005439 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005440 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005441
5442 unsigned NumArgsInProto = Proto->getNumArgs();
5443
5444 // (C++ 13.3.2p2): A candidate function having fewer than m
5445 // parameters is viable only if it has an ellipsis in its parameter
5446 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005447 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005448 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005449 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005450 return;
5451 }
5452
5453 // (C++ 13.3.2p2): A candidate function having more than m parameters
5454 // is viable only if the (m+1)st parameter has a default argument
5455 // (8.3.6). For the purposes of overload resolution, the
5456 // parameter list is truncated on the right, so that there are
5457 // exactly m parameters.
5458 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005459 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005460 // Not enough arguments.
5461 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005462 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005463 return;
5464 }
5465
5466 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005467
John McCall701c89e2009-12-03 04:06:58 +00005468 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005469 // The implicit object argument is ignored.
5470 Candidate.IgnoreObjectArgument = true;
5471 else {
5472 // Determine the implicit conversion sequence for the object
5473 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005474 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005475 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5476 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005477 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005478 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005479 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005480 return;
5481 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005482 }
5483
5484 // Determine the implicit conversion sequences for each of the
5485 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005486 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005487 if (ArgIdx < NumArgsInProto) {
5488 // (C++ 13.3.2p3): for F to be a viable function, there shall
5489 // exist for each argument an implicit conversion sequence
5490 // (13.3.3.1) that converts that argument to the corresponding
5491 // parameter of F.
5492 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005493 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005494 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005495 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005496 /*InOverloadResolution=*/true,
5497 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005498 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005499 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005500 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005501 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005502 break;
5503 }
5504 } else {
5505 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5506 // argument for which there is no corresponding parameter is
5507 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005508 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005509 }
5510 }
5511}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005512
Douglas Gregor6b906862009-08-21 00:16:32 +00005513/// \brief Add a C++ member function template as a candidate to the candidate
5514/// set, using template argument deduction to produce an appropriate member
5515/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005516void
Douglas Gregor6b906862009-08-21 00:16:32 +00005517Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005518 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005519 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005520 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005521 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005522 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005523 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005524 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005525 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005526 if (!CandidateSet.isNewCandidate(MethodTmpl))
5527 return;
5528
Douglas Gregor6b906862009-08-21 00:16:32 +00005529 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005530 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005531 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005532 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005533 // candidate functions in the usual way.113) A given name can refer to one
5534 // or more function templates and also to a set of overloaded non-template
5535 // functions. In such a case, the candidate functions generated from each
5536 // function template are combined with the set of non-template candidate
5537 // functions.
John McCall5769d612010-02-08 23:07:23 +00005538 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005539 FunctionDecl *Specialization = 0;
5540 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005541 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5542 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005543 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005544 Candidate.FoundDecl = FoundDecl;
5545 Candidate.Function = MethodTmpl->getTemplatedDecl();
5546 Candidate.Viable = false;
5547 Candidate.FailureKind = ovl_fail_bad_deduction;
5548 Candidate.IsSurrogate = false;
5549 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005550 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005551 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005552 Info);
5553 return;
5554 }
Mike Stump1eb44332009-09-09 15:08:12 +00005555
Douglas Gregor6b906862009-08-21 00:16:32 +00005556 // Add the function template specialization produced by template argument
5557 // deduction as a candidate.
5558 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005559 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005560 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005561 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005562 ActingContext, ObjectType, ObjectClassification, Args,
5563 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005564}
5565
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005566/// \brief Add a C++ function template specialization as a candidate
5567/// in the candidate set, using template argument deduction to produce
5568/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005569void
Douglas Gregore53060f2009-06-25 22:08:12 +00005570Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005571 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005572 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005573 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005574 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005575 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005576 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5577 return;
5578
Douglas Gregore53060f2009-06-25 22:08:12 +00005579 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005580 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005581 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005582 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005583 // candidate functions in the usual way.113) A given name can refer to one
5584 // or more function templates and also to a set of overloaded non-template
5585 // functions. In such a case, the candidate functions generated from each
5586 // function template are combined with the set of non-template candidate
5587 // functions.
John McCall5769d612010-02-08 23:07:23 +00005588 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005589 FunctionDecl *Specialization = 0;
5590 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005591 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5592 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005593 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005594 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005595 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5596 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005597 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005598 Candidate.IsSurrogate = false;
5599 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005600 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005601 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005602 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005603 return;
5604 }
Mike Stump1eb44332009-09-09 15:08:12 +00005605
Douglas Gregore53060f2009-06-25 22:08:12 +00005606 // Add the function template specialization produced by template argument
5607 // deduction as a candidate.
5608 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005609 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005610 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005611}
Mike Stump1eb44332009-09-09 15:08:12 +00005612
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005613/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005614/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005615/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005616/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005617/// (which may or may not be the same type as the type that the
5618/// conversion function produces).
5619void
5620Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005621 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005622 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005623 Expr *From, QualType ToType,
5624 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005625 assert(!Conversion->getDescribedFunctionTemplate() &&
5626 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005627 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005628 if (!CandidateSet.isNewCandidate(Conversion))
5629 return;
5630
Douglas Gregor7edfb692009-11-23 12:27:39 +00005631 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005632 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005633
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005634 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005635 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005636 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005637 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005638 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005639 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005640 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005641 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005642 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005643 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005644 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005645
Douglas Gregorbca39322010-08-19 15:37:02 +00005646 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005647 // For conversion functions, the function is considered to be a member of
5648 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005649 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005650 //
5651 // Determine the implicit conversion sequence for the implicit
5652 // object parameter.
5653 QualType ImplicitParamType = From->getType();
5654 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5655 ImplicitParamType = FromPtrType->getPointeeType();
5656 CXXRecordDecl *ConversionContext
5657 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005658
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005659 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005660 = TryObjectArgumentInitialization(*this, From->getType(),
5661 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005662 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005663
John McCall1d318332010-01-12 00:44:57 +00005664 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005665 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005666 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005667 return;
5668 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005669
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005670 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005671 // derived to base as such conversions are given Conversion Rank. They only
5672 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5673 QualType FromCanon
5674 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5675 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5676 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5677 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005678 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005679 return;
5680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005681
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005682 // To determine what the conversion from the result of calling the
5683 // conversion function to the type we're eventually trying to
5684 // convert to (ToType), we need to synthesize a call to the
5685 // conversion function and attempt copy initialization from it. This
5686 // makes sure that we get the right semantics with respect to
5687 // lvalues/rvalues and the type. Fortunately, we can allocate this
5688 // call on the stack and we don't need its arguments to be
5689 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005690 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005691 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005692 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5693 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005694 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005695 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005696
Richard Smith87c1f1f2011-07-13 22:53:21 +00005697 QualType ConversionType = Conversion->getConversionType();
5698 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005699 Candidate.Viable = false;
5700 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5701 return;
5702 }
5703
Richard Smith87c1f1f2011-07-13 22:53:21 +00005704 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005705
Mike Stump1eb44332009-09-09 15:08:12 +00005706 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005707 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5708 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005709 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005710 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005711 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005712 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005713 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005714 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005715 /*InOverloadResolution=*/false,
5716 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005717
John McCall1d318332010-01-12 00:44:57 +00005718 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005719 case ImplicitConversionSequence::StandardConversion:
5720 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005721
Douglas Gregorc520c842010-04-12 23:42:09 +00005722 // C++ [over.ics.user]p3:
5723 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005724 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005725 // shall have exact match rank.
5726 if (Conversion->getPrimaryTemplate() &&
5727 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5728 Candidate.Viable = false;
5729 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5730 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005731
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005732 // C++0x [dcl.init.ref]p5:
5733 // In the second case, if the reference is an rvalue reference and
5734 // the second standard conversion sequence of the user-defined
5735 // conversion sequence includes an lvalue-to-rvalue conversion, the
5736 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005737 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005738 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5739 Candidate.Viable = false;
5740 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5741 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005742 break;
5743
5744 case ImplicitConversionSequence::BadConversion:
5745 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005746 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005747 break;
5748
5749 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005750 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005751 "Can only end up with a standard conversion sequence or failure");
5752 }
5753}
5754
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005755/// \brief Adds a conversion function template specialization
5756/// candidate to the overload set, using template argument deduction
5757/// to deduce the template arguments of the conversion function
5758/// template from the type that we are converting to (C++
5759/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005760void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005761Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005762 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005763 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005764 Expr *From, QualType ToType,
5765 OverloadCandidateSet &CandidateSet) {
5766 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5767 "Only conversion function templates permitted here");
5768
Douglas Gregor3f396022009-09-28 04:47:19 +00005769 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5770 return;
5771
John McCall5769d612010-02-08 23:07:23 +00005772 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005773 CXXConversionDecl *Specialization = 0;
5774 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005775 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005776 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005777 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005778 Candidate.FoundDecl = FoundDecl;
5779 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5780 Candidate.Viable = false;
5781 Candidate.FailureKind = ovl_fail_bad_deduction;
5782 Candidate.IsSurrogate = false;
5783 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005784 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005785 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005786 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005787 return;
5788 }
Mike Stump1eb44332009-09-09 15:08:12 +00005789
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005790 // Add the conversion function template specialization produced by
5791 // template argument deduction as a candidate.
5792 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005793 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005794 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005795}
5796
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005797/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5798/// converts the given @c Object to a function pointer via the
5799/// conversion function @c Conversion, and then attempts to call it
5800/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5801/// the type of function that we'll eventually be calling.
5802void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005803 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005804 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005805 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005806 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005807 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005808 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005809 if (!CandidateSet.isNewCandidate(Conversion))
5810 return;
5811
Douglas Gregor7edfb692009-11-23 12:27:39 +00005812 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005813 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005814
Ahmed Charles13a140c2012-02-25 11:00:22 +00005815 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005816 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005817 Candidate.Function = 0;
5818 Candidate.Surrogate = Conversion;
5819 Candidate.Viable = true;
5820 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005821 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005822 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005823
5824 // Determine the implicit conversion sequence for the implicit
5825 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005826 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005827 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005828 Object->Classify(Context),
5829 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005830 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005831 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005832 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005833 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005834 return;
5835 }
5836
5837 // The first conversion is actually a user-defined conversion whose
5838 // first conversion is ObjectInit's standard conversion (which is
5839 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005840 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005841 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005842 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005843 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005844 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005845 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005846 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005847 = Candidate.Conversions[0].UserDefined.Before;
5848 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5849
Mike Stump1eb44332009-09-09 15:08:12 +00005850 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005851 unsigned NumArgsInProto = Proto->getNumArgs();
5852
5853 // (C++ 13.3.2p2): A candidate function having fewer than m
5854 // parameters is viable only if it has an ellipsis in its parameter
5855 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005856 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005857 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005858 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005859 return;
5860 }
5861
5862 // Function types don't have any default arguments, so just check if
5863 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005864 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005865 // Not enough arguments.
5866 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005867 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005868 return;
5869 }
5870
5871 // Determine the implicit conversion sequences for each of the
5872 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005873 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 if (ArgIdx < NumArgsInProto) {
5875 // (C++ 13.3.2p3): for F to be a viable function, there shall
5876 // exist for each argument an implicit conversion sequence
5877 // (13.3.3.1) that converts that argument to the corresponding
5878 // parameter of F.
5879 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005880 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005881 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005882 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005883 /*InOverloadResolution=*/false,
5884 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005885 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005886 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005887 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005888 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005889 break;
5890 }
5891 } else {
5892 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5893 // argument for which there is no corresponding parameter is
5894 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005895 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005896 }
5897 }
5898}
5899
Douglas Gregor063daf62009-03-13 18:40:31 +00005900/// \brief Add overload candidates for overloaded operators that are
5901/// member functions.
5902///
5903/// Add the overloaded operator candidates that are member functions
5904/// for the operator Op that was used in an operator expression such
5905/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5906/// CandidateSet will store the added overload candidates. (C++
5907/// [over.match.oper]).
5908void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5909 SourceLocation OpLoc,
5910 Expr **Args, unsigned NumArgs,
5911 OverloadCandidateSet& CandidateSet,
5912 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005913 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5914
5915 // C++ [over.match.oper]p3:
5916 // For a unary operator @ with an operand of a type whose
5917 // cv-unqualified version is T1, and for a binary operator @ with
5918 // a left operand of a type whose cv-unqualified version is T1 and
5919 // a right operand of a type whose cv-unqualified version is T2,
5920 // three sets of candidate functions, designated member
5921 // candidates, non-member candidates and built-in candidates, are
5922 // constructed as follows:
5923 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005924
5925 // -- If T1 is a class type, the set of member candidates is the
5926 // result of the qualified lookup of T1::operator@
5927 // (13.3.1.1.1); otherwise, the set of member candidates is
5928 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005929 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005930 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005931 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005932 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005933
John McCalla24dc2e2009-11-17 02:14:36 +00005934 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5935 LookupQualifiedName(Operators, T1Rec->getDecl());
5936 Operators.suppressDiagnostics();
5937
Mike Stump1eb44332009-09-09 15:08:12 +00005938 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005939 OperEnd = Operators.end();
5940 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005941 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005942 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005943 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005944 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005945 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005946 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005947}
5948
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005949/// AddBuiltinCandidate - Add a candidate for a built-in
5950/// operator. ResultTy and ParamTys are the result and parameter types
5951/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005952/// arguments being passed to the candidate. IsAssignmentOperator
5953/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005954/// operator. NumContextualBoolArguments is the number of arguments
5955/// (at the beginning of the argument list) that will be contextually
5956/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005957void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005958 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005959 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005960 bool IsAssignmentOperator,
5961 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005962 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005963 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005964
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005965 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005966 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005967 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005968 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005969 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005970 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005971 Candidate.BuiltinTypes.ResultTy = ResultTy;
5972 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5973 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5974
5975 // Determine the implicit conversion sequences for each of the
5976 // arguments.
5977 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005978 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005979 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005980 // C++ [over.match.oper]p4:
5981 // For the built-in assignment operators, conversions of the
5982 // left operand are restricted as follows:
5983 // -- no temporaries are introduced to hold the left operand, and
5984 // -- no user-defined conversions are applied to the left
5985 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005986 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005987 //
5988 // We block these conversions by turning off user-defined
5989 // conversions, since that is the only way that initialization of
5990 // a reference to a non-class type can occur from something that
5991 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005992 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005993 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005994 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005995 Candidate.Conversions[ArgIdx]
5996 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005997 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005998 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005999 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006000 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006001 /*InOverloadResolution=*/false,
6002 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006003 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006004 }
John McCall1d318332010-01-12 00:44:57 +00006005 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006006 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006007 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006008 break;
6009 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006010 }
6011}
6012
6013/// BuiltinCandidateTypeSet - A set of types that will be used for the
6014/// candidate operator functions for built-in operators (C++
6015/// [over.built]). The types are separated into pointer types and
6016/// enumeration types.
6017class BuiltinCandidateTypeSet {
6018 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006019 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006020
6021 /// PointerTypes - The set of pointer types that will be used in the
6022 /// built-in candidates.
6023 TypeSet PointerTypes;
6024
Sebastian Redl78eb8742009-04-19 21:53:20 +00006025 /// MemberPointerTypes - The set of member pointer types that will be
6026 /// used in the built-in candidates.
6027 TypeSet MemberPointerTypes;
6028
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006029 /// EnumerationTypes - The set of enumeration types that will be
6030 /// used in the built-in candidates.
6031 TypeSet EnumerationTypes;
6032
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006033 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006034 /// candidates.
6035 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006036
6037 /// \brief A flag indicating non-record types are viable candidates
6038 bool HasNonRecordTypes;
6039
6040 /// \brief A flag indicating whether either arithmetic or enumeration types
6041 /// were present in the candidate set.
6042 bool HasArithmeticOrEnumeralTypes;
6043
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006044 /// \brief A flag indicating whether the nullptr type was present in the
6045 /// candidate set.
6046 bool HasNullPtrType;
6047
Douglas Gregor5842ba92009-08-24 15:23:48 +00006048 /// Sema - The semantic analysis instance where we are building the
6049 /// candidate type set.
6050 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006051
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006052 /// Context - The AST context in which we will build the type sets.
6053 ASTContext &Context;
6054
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006055 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6056 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006057 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006058
6059public:
6060 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006061 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006062
Mike Stump1eb44332009-09-09 15:08:12 +00006063 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006064 : HasNonRecordTypes(false),
6065 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006066 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006067 SemaRef(SemaRef),
6068 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006069
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006070 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006071 SourceLocation Loc,
6072 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006073 bool AllowExplicitConversions,
6074 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006075
6076 /// pointer_begin - First pointer type found;
6077 iterator pointer_begin() { return PointerTypes.begin(); }
6078
Sebastian Redl78eb8742009-04-19 21:53:20 +00006079 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006080 iterator pointer_end() { return PointerTypes.end(); }
6081
Sebastian Redl78eb8742009-04-19 21:53:20 +00006082 /// member_pointer_begin - First member pointer type found;
6083 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6084
6085 /// member_pointer_end - Past the last member pointer type found;
6086 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6087
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006088 /// enumeration_begin - First enumeration type found;
6089 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6090
Sebastian Redl78eb8742009-04-19 21:53:20 +00006091 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006092 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006093
Douglas Gregor26bcf672010-05-19 03:21:00 +00006094 iterator vector_begin() { return VectorTypes.begin(); }
6095 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006096
6097 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6098 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006099 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006100};
6101
Sebastian Redl78eb8742009-04-19 21:53:20 +00006102/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006103/// the set of pointer types along with any more-qualified variants of
6104/// that type. For example, if @p Ty is "int const *", this routine
6105/// will add "int const *", "int const volatile *", "int const
6106/// restrict *", and "int const volatile restrict *" to the set of
6107/// pointer types. Returns true if the add of @p Ty itself succeeded,
6108/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006109///
6110/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006111bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006112BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6113 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006114
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006115 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006116 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006117 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006118
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006119 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006120 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006121 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006122 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006123 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6124 PointeeTy = PTy->getPointeeType();
6125 buildObjCPtr = true;
6126 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006127 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006128 }
6129
Sebastian Redla9efada2009-11-18 20:39:26 +00006130 // Don't add qualified variants of arrays. For one, they're not allowed
6131 // (the qualifier would sink to the element type), and for another, the
6132 // only overload situation where it matters is subscript or pointer +- int,
6133 // and those shouldn't have qualifier variants anyway.
6134 if (PointeeTy->isArrayType())
6135 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006136
John McCall0953e762009-09-24 19:53:00 +00006137 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006138 bool hasVolatile = VisibleQuals.hasVolatile();
6139 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006140
John McCall0953e762009-09-24 19:53:00 +00006141 // Iterate through all strict supersets of BaseCVR.
6142 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6143 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006144 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006145 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006146
6147 // Skip over restrict if no restrict found anywhere in the types, or if
6148 // the type cannot be restrict-qualified.
6149 if ((CVR & Qualifiers::Restrict) &&
6150 (!hasRestrict ||
6151 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6152 continue;
6153
6154 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006155 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006156
6157 // Build qualified pointer type.
6158 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006159 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006160 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006161 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006162 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6163
6164 // Insert qualified pointer type.
6165 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006166 }
6167
6168 return true;
6169}
6170
Sebastian Redl78eb8742009-04-19 21:53:20 +00006171/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6172/// to the set of pointer types along with any more-qualified variants of
6173/// that type. For example, if @p Ty is "int const *", this routine
6174/// will add "int const *", "int const volatile *", "int const
6175/// restrict *", and "int const volatile restrict *" to the set of
6176/// pointer types. Returns true if the add of @p Ty itself succeeded,
6177/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006178///
6179/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006180bool
6181BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6182 QualType Ty) {
6183 // Insert this type.
6184 if (!MemberPointerTypes.insert(Ty))
6185 return false;
6186
John McCall0953e762009-09-24 19:53:00 +00006187 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6188 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006189
John McCall0953e762009-09-24 19:53:00 +00006190 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006191 // Don't add qualified variants of arrays. For one, they're not allowed
6192 // (the qualifier would sink to the element type), and for another, the
6193 // only overload situation where it matters is subscript or pointer +- int,
6194 // and those shouldn't have qualifier variants anyway.
6195 if (PointeeTy->isArrayType())
6196 return true;
John McCall0953e762009-09-24 19:53:00 +00006197 const Type *ClassTy = PointerTy->getClass();
6198
6199 // Iterate through all strict supersets of the pointee type's CVR
6200 // qualifiers.
6201 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6202 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6203 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006204
John McCall0953e762009-09-24 19:53:00 +00006205 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006206 MemberPointerTypes.insert(
6207 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006208 }
6209
6210 return true;
6211}
6212
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006213/// AddTypesConvertedFrom - Add each of the types to which the type @p
6214/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006215/// primarily interested in pointer types and enumeration types. We also
6216/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006217/// AllowUserConversions is true if we should look at the conversion
6218/// functions of a class type, and AllowExplicitConversions if we
6219/// should also include the explicit conversion functions of a class
6220/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006221void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006222BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006223 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006224 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006225 bool AllowExplicitConversions,
6226 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006227 // Only deal with canonical types.
6228 Ty = Context.getCanonicalType(Ty);
6229
6230 // Look through reference types; they aren't part of the type of an
6231 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006232 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233 Ty = RefTy->getPointeeType();
6234
John McCall3b657512011-01-19 10:06:00 +00006235 // If we're dealing with an array type, decay to the pointer.
6236 if (Ty->isArrayType())
6237 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6238
6239 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006240 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006241
Chandler Carruth6a577462010-12-13 01:44:01 +00006242 // Flag if we ever add a non-record type.
6243 const RecordType *TyRec = Ty->getAs<RecordType>();
6244 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6245
Chandler Carruth6a577462010-12-13 01:44:01 +00006246 // Flag if we encounter an arithmetic type.
6247 HasArithmeticOrEnumeralTypes =
6248 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6249
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006250 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6251 PointerTypes.insert(Ty);
6252 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006253 // Insert our type, and its more-qualified variants, into the set
6254 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006255 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006256 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006257 } else if (Ty->isMemberPointerType()) {
6258 // Member pointers are far easier, since the pointee can't be converted.
6259 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6260 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006261 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006262 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006263 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006264 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006265 // We treat vector types as arithmetic types in many contexts as an
6266 // extension.
6267 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006268 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006269 } else if (Ty->isNullPtrType()) {
6270 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006271 } else if (AllowUserConversions && TyRec) {
6272 // No conversion functions in incomplete types.
6273 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6274 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006275
Chandler Carruth6a577462010-12-13 01:44:01 +00006276 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6277 const UnresolvedSetImpl *Conversions
6278 = ClassDecl->getVisibleConversionFunctions();
6279 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6280 E = Conversions->end(); I != E; ++I) {
6281 NamedDecl *D = I.getDecl();
6282 if (isa<UsingShadowDecl>(D))
6283 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006284
Chandler Carruth6a577462010-12-13 01:44:01 +00006285 // Skip conversion function templates; they don't tell us anything
6286 // about which builtin types we can convert to.
6287 if (isa<FunctionTemplateDecl>(D))
6288 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006289
Chandler Carruth6a577462010-12-13 01:44:01 +00006290 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6291 if (AllowExplicitConversions || !Conv->isExplicit()) {
6292 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6293 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006294 }
6295 }
6296 }
6297}
6298
Douglas Gregor19b7b152009-08-24 13:43:27 +00006299/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6300/// the volatile- and non-volatile-qualified assignment operators for the
6301/// given type to the candidate set.
6302static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6303 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006304 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006305 unsigned NumArgs,
6306 OverloadCandidateSet &CandidateSet) {
6307 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006308
Douglas Gregor19b7b152009-08-24 13:43:27 +00006309 // T& operator=(T&, T)
6310 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6311 ParamTypes[1] = T;
6312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6313 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006314
Douglas Gregor19b7b152009-08-24 13:43:27 +00006315 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6316 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006317 ParamTypes[0]
6318 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006319 ParamTypes[1] = T;
6320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006321 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006322 }
6323}
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Sebastian Redl9994a342009-10-25 17:03:50 +00006325/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6326/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006327static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6328 Qualifiers VRQuals;
6329 const RecordType *TyRec;
6330 if (const MemberPointerType *RHSMPType =
6331 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006332 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006333 else
6334 TyRec = ArgExpr->getType()->getAs<RecordType>();
6335 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006336 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006337 VRQuals.addVolatile();
6338 VRQuals.addRestrict();
6339 return VRQuals;
6340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006341
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006342 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006343 if (!ClassDecl->hasDefinition())
6344 return VRQuals;
6345
John McCalleec51cf2010-01-20 00:46:10 +00006346 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006347 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006348
John McCalleec51cf2010-01-20 00:46:10 +00006349 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006350 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006351 NamedDecl *D = I.getDecl();
6352 if (isa<UsingShadowDecl>(D))
6353 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6354 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006355 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6356 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6357 CanTy = ResTypeRef->getPointeeType();
6358 // Need to go down the pointer/mempointer chain and add qualifiers
6359 // as see them.
6360 bool done = false;
6361 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006362 if (CanTy.isRestrictQualified())
6363 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006364 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6365 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006366 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006367 CanTy->getAs<MemberPointerType>())
6368 CanTy = ResTypeMPtr->getPointeeType();
6369 else
6370 done = true;
6371 if (CanTy.isVolatileQualified())
6372 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006373 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6374 return VRQuals;
6375 }
6376 }
6377 }
6378 return VRQuals;
6379}
John McCall00071ec2010-11-13 05:51:15 +00006380
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006381namespace {
John McCall00071ec2010-11-13 05:51:15 +00006382
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006383/// \brief Helper class to manage the addition of builtin operator overload
6384/// candidates. It provides shared state and utility methods used throughout
6385/// the process, as well as a helper method to add each group of builtin
6386/// operator overloads from the standard to a candidate set.
6387class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006388 // Common instance state available to all overload candidate addition methods.
6389 Sema &S;
6390 Expr **Args;
6391 unsigned NumArgs;
6392 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006393 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006394 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006395 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006396
Chandler Carruth6d695582010-12-12 10:35:00 +00006397 // Define some constants used to index and iterate over the arithemetic types
6398 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006399 // The "promoted arithmetic types" are the arithmetic
6400 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006401 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006402 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006403 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006404 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006405 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006406 LastPromotedArithmeticType = 11;
6407 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006408
Chandler Carruth6d695582010-12-12 10:35:00 +00006409 /// \brief Get the canonical type for a given arithmetic type index.
6410 CanQualType getArithmeticType(unsigned index) {
6411 assert(index < NumArithmeticTypes);
6412 static CanQualType ASTContext::* const
6413 ArithmeticTypes[NumArithmeticTypes] = {
6414 // Start of promoted types.
6415 &ASTContext::FloatTy,
6416 &ASTContext::DoubleTy,
6417 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006418
Chandler Carruth6d695582010-12-12 10:35:00 +00006419 // Start of integral types.
6420 &ASTContext::IntTy,
6421 &ASTContext::LongTy,
6422 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006423 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006424 &ASTContext::UnsignedIntTy,
6425 &ASTContext::UnsignedLongTy,
6426 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006427 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006428 // End of promoted types.
6429
6430 &ASTContext::BoolTy,
6431 &ASTContext::CharTy,
6432 &ASTContext::WCharTy,
6433 &ASTContext::Char16Ty,
6434 &ASTContext::Char32Ty,
6435 &ASTContext::SignedCharTy,
6436 &ASTContext::ShortTy,
6437 &ASTContext::UnsignedCharTy,
6438 &ASTContext::UnsignedShortTy,
6439 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006440 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006441 };
6442 return S.Context.*ArithmeticTypes[index];
6443 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006444
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006445 /// \brief Gets the canonical type resulting from the usual arithemetic
6446 /// converions for the given arithmetic types.
6447 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6448 // Accelerator table for performing the usual arithmetic conversions.
6449 // The rules are basically:
6450 // - if either is floating-point, use the wider floating-point
6451 // - if same signedness, use the higher rank
6452 // - if same size, use unsigned of the higher rank
6453 // - use the larger type
6454 // These rules, together with the axiom that higher ranks are
6455 // never smaller, are sufficient to precompute all of these results
6456 // *except* when dealing with signed types of higher rank.
6457 // (we could precompute SLL x UI for all known platforms, but it's
6458 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006459 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006460 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006461 Dep=-1,
6462 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006463 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006464 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006465 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006466/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6467/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6468/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6469/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6470/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6471/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6472/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6473/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6474/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6475/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6476/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006477 };
6478
6479 assert(L < LastPromotedArithmeticType);
6480 assert(R < LastPromotedArithmeticType);
6481 int Idx = ConversionsTable[L][R];
6482
6483 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006484 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006485
6486 // Slow path: we need to compare widths.
6487 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006488 CanQualType LT = getArithmeticType(L),
6489 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006490 unsigned LW = S.Context.getIntWidth(LT),
6491 RW = S.Context.getIntWidth(RT);
6492
6493 // If they're different widths, use the signed type.
6494 if (LW > RW) return LT;
6495 else if (LW < RW) return RT;
6496
6497 // Otherwise, use the unsigned type of the signed type's rank.
6498 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6499 assert(L == SLL || R == SLL);
6500 return S.Context.UnsignedLongLongTy;
6501 }
6502
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006503 /// \brief Helper method to factor out the common pattern of adding overloads
6504 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006505 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006506 bool HasVolatile,
6507 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006508 QualType ParamTypes[2] = {
6509 S.Context.getLValueReferenceType(CandidateTy),
6510 S.Context.IntTy
6511 };
6512
6513 // Non-volatile version.
6514 if (NumArgs == 1)
6515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6516 else
6517 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6518
6519 // Use a heuristic to reduce number of builtin candidates in the set:
6520 // add volatile version only if there are conversions to a volatile type.
6521 if (HasVolatile) {
6522 ParamTypes[0] =
6523 S.Context.getLValueReferenceType(
6524 S.Context.getVolatileType(CandidateTy));
6525 if (NumArgs == 1)
6526 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6527 else
6528 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6529 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006530
6531 // Add restrict version only if there are conversions to a restrict type
6532 // and our candidate type is a non-restrict-qualified pointer.
6533 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6534 !CandidateTy.isRestrictQualified()) {
6535 ParamTypes[0]
6536 = S.Context.getLValueReferenceType(
6537 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6538 if (NumArgs == 1)
6539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6540 else
6541 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6542
6543 if (HasVolatile) {
6544 ParamTypes[0]
6545 = S.Context.getLValueReferenceType(
6546 S.Context.getCVRQualifiedType(CandidateTy,
6547 (Qualifiers::Volatile |
6548 Qualifiers::Restrict)));
6549 if (NumArgs == 1)
6550 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6551 CandidateSet);
6552 else
6553 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6554 }
6555 }
6556
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006557 }
6558
6559public:
6560 BuiltinOperatorOverloadBuilder(
6561 Sema &S, Expr **Args, unsigned NumArgs,
6562 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006563 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006564 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006565 OverloadCandidateSet &CandidateSet)
6566 : S(S), Args(Args), NumArgs(NumArgs),
6567 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006568 HasArithmeticOrEnumeralCandidateType(
6569 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006570 CandidateTypes(CandidateTypes),
6571 CandidateSet(CandidateSet) {
6572 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006573 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006574 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006575 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006576 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006577 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006578 assert(getArithmeticType(FirstPromotedArithmeticType)
6579 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006580 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006581 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006582 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006583 "Invalid last promoted arithmetic type");
6584 }
6585
6586 // C++ [over.built]p3:
6587 //
6588 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6589 // is either volatile or empty, there exist candidate operator
6590 // functions of the form
6591 //
6592 // VQ T& operator++(VQ T&);
6593 // T operator++(VQ T&, int);
6594 //
6595 // C++ [over.built]p4:
6596 //
6597 // For every pair (T, VQ), where T is an arithmetic type other
6598 // than bool, and VQ is either volatile or empty, there exist
6599 // candidate operator functions of the form
6600 //
6601 // VQ T& operator--(VQ T&);
6602 // T operator--(VQ T&, int);
6603 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006604 if (!HasArithmeticOrEnumeralCandidateType)
6605 return;
6606
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006607 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6608 Arith < NumArithmeticTypes; ++Arith) {
6609 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006610 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006611 VisibleTypeConversionsQuals.hasVolatile(),
6612 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006613 }
6614 }
6615
6616 // C++ [over.built]p5:
6617 //
6618 // For every pair (T, VQ), where T is a cv-qualified or
6619 // cv-unqualified object type, and VQ is either volatile or
6620 // empty, there exist candidate operator functions of the form
6621 //
6622 // T*VQ& operator++(T*VQ&);
6623 // T*VQ& operator--(T*VQ&);
6624 // T* operator++(T*VQ&, int);
6625 // T* operator--(T*VQ&, int);
6626 void addPlusPlusMinusMinusPointerOverloads() {
6627 for (BuiltinCandidateTypeSet::iterator
6628 Ptr = CandidateTypes[0].pointer_begin(),
6629 PtrEnd = CandidateTypes[0].pointer_end();
6630 Ptr != PtrEnd; ++Ptr) {
6631 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006632 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006633 continue;
6634
6635 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006636 (!(*Ptr).isVolatileQualified() &&
6637 VisibleTypeConversionsQuals.hasVolatile()),
6638 (!(*Ptr).isRestrictQualified() &&
6639 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006640 }
6641 }
6642
6643 // C++ [over.built]p6:
6644 // For every cv-qualified or cv-unqualified object type T, there
6645 // exist candidate operator functions of the form
6646 //
6647 // T& operator*(T*);
6648 //
6649 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006650 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006651 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006652 // T& operator*(T*);
6653 void addUnaryStarPointerOverloads() {
6654 for (BuiltinCandidateTypeSet::iterator
6655 Ptr = CandidateTypes[0].pointer_begin(),
6656 PtrEnd = CandidateTypes[0].pointer_end();
6657 Ptr != PtrEnd; ++Ptr) {
6658 QualType ParamTy = *Ptr;
6659 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006660 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6661 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006662
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006663 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6664 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6665 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006666
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006667 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6668 &ParamTy, Args, 1, CandidateSet);
6669 }
6670 }
6671
6672 // C++ [over.built]p9:
6673 // For every promoted arithmetic type T, there exist candidate
6674 // operator functions of the form
6675 //
6676 // T operator+(T);
6677 // T operator-(T);
6678 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006679 if (!HasArithmeticOrEnumeralCandidateType)
6680 return;
6681
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006682 for (unsigned Arith = FirstPromotedArithmeticType;
6683 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006684 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006685 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6686 }
6687
6688 // Extension: We also add these operators for vector types.
6689 for (BuiltinCandidateTypeSet::iterator
6690 Vec = CandidateTypes[0].vector_begin(),
6691 VecEnd = CandidateTypes[0].vector_end();
6692 Vec != VecEnd; ++Vec) {
6693 QualType VecTy = *Vec;
6694 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6695 }
6696 }
6697
6698 // C++ [over.built]p8:
6699 // For every type T, there exist candidate operator functions of
6700 // the form
6701 //
6702 // T* operator+(T*);
6703 void addUnaryPlusPointerOverloads() {
6704 for (BuiltinCandidateTypeSet::iterator
6705 Ptr = CandidateTypes[0].pointer_begin(),
6706 PtrEnd = CandidateTypes[0].pointer_end();
6707 Ptr != PtrEnd; ++Ptr) {
6708 QualType ParamTy = *Ptr;
6709 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6710 }
6711 }
6712
6713 // C++ [over.built]p10:
6714 // For every promoted integral type T, there exist candidate
6715 // operator functions of the form
6716 //
6717 // T operator~(T);
6718 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006719 if (!HasArithmeticOrEnumeralCandidateType)
6720 return;
6721
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006722 for (unsigned Int = FirstPromotedIntegralType;
6723 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006724 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006725 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6726 }
6727
6728 // Extension: We also add this operator for vector types.
6729 for (BuiltinCandidateTypeSet::iterator
6730 Vec = CandidateTypes[0].vector_begin(),
6731 VecEnd = CandidateTypes[0].vector_end();
6732 Vec != VecEnd; ++Vec) {
6733 QualType VecTy = *Vec;
6734 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6735 }
6736 }
6737
6738 // C++ [over.match.oper]p16:
6739 // For every pointer to member type T, there exist candidate operator
6740 // functions of the form
6741 //
6742 // bool operator==(T,T);
6743 // bool operator!=(T,T);
6744 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6745 /// Set of (canonical) types that we've already handled.
6746 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6747
6748 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6749 for (BuiltinCandidateTypeSet::iterator
6750 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6751 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6752 MemPtr != MemPtrEnd;
6753 ++MemPtr) {
6754 // Don't add the same builtin candidate twice.
6755 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6756 continue;
6757
6758 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6759 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6760 CandidateSet);
6761 }
6762 }
6763 }
6764
6765 // C++ [over.built]p15:
6766 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006767 // For every T, where T is an enumeration type, a pointer type, or
6768 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006769 //
6770 // bool operator<(T, T);
6771 // bool operator>(T, T);
6772 // bool operator<=(T, T);
6773 // bool operator>=(T, T);
6774 // bool operator==(T, T);
6775 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006776 void addRelationalPointerOrEnumeralOverloads() {
6777 // C++ [over.built]p1:
6778 // If there is a user-written candidate with the same name and parameter
6779 // types as a built-in candidate operator function, the built-in operator
6780 // function is hidden and is not included in the set of candidate
6781 // functions.
6782 //
6783 // The text is actually in a note, but if we don't implement it then we end
6784 // up with ambiguities when the user provides an overloaded operator for
6785 // an enumeration type. Note that only enumeration types have this problem,
6786 // so we track which enumeration types we've seen operators for. Also, the
6787 // only other overloaded operator with enumeration argumenst, operator=,
6788 // cannot be overloaded for enumeration types, so this is the only place
6789 // where we must suppress candidates like this.
6790 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6791 UserDefinedBinaryOperators;
6792
6793 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6794 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6795 CandidateTypes[ArgIdx].enumeration_end()) {
6796 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6797 CEnd = CandidateSet.end();
6798 C != CEnd; ++C) {
6799 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6800 continue;
6801
6802 QualType FirstParamType =
6803 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6804 QualType SecondParamType =
6805 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6806
6807 // Skip if either parameter isn't of enumeral type.
6808 if (!FirstParamType->isEnumeralType() ||
6809 !SecondParamType->isEnumeralType())
6810 continue;
6811
6812 // Add this operator to the set of known user-defined operators.
6813 UserDefinedBinaryOperators.insert(
6814 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6815 S.Context.getCanonicalType(SecondParamType)));
6816 }
6817 }
6818 }
6819
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006820 /// Set of (canonical) types that we've already handled.
6821 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6822
6823 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6824 for (BuiltinCandidateTypeSet::iterator
6825 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6826 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6827 Ptr != PtrEnd; ++Ptr) {
6828 // Don't add the same builtin candidate twice.
6829 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6830 continue;
6831
6832 QualType ParamTypes[2] = { *Ptr, *Ptr };
6833 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6834 CandidateSet);
6835 }
6836 for (BuiltinCandidateTypeSet::iterator
6837 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6838 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6839 Enum != EnumEnd; ++Enum) {
6840 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6841
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006842 // Don't add the same builtin candidate twice, or if a user defined
6843 // candidate exists.
6844 if (!AddedTypes.insert(CanonType) ||
6845 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6846 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006847 continue;
6848
6849 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006850 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6851 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006852 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006853
6854 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6855 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6856 if (AddedTypes.insert(NullPtrTy) &&
6857 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6858 NullPtrTy))) {
6859 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6860 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6861 CandidateSet);
6862 }
6863 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006864 }
6865 }
6866
6867 // C++ [over.built]p13:
6868 //
6869 // For every cv-qualified or cv-unqualified object type T
6870 // there exist candidate operator functions of the form
6871 //
6872 // T* operator+(T*, ptrdiff_t);
6873 // T& operator[](T*, ptrdiff_t); [BELOW]
6874 // T* operator-(T*, ptrdiff_t);
6875 // T* operator+(ptrdiff_t, T*);
6876 // T& operator[](ptrdiff_t, T*); [BELOW]
6877 //
6878 // C++ [over.built]p14:
6879 //
6880 // For every T, where T is a pointer to object type, there
6881 // exist candidate operator functions of the form
6882 //
6883 // ptrdiff_t operator-(T, T);
6884 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6885 /// Set of (canonical) types that we've already handled.
6886 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6887
6888 for (int Arg = 0; Arg < 2; ++Arg) {
6889 QualType AsymetricParamTypes[2] = {
6890 S.Context.getPointerDiffType(),
6891 S.Context.getPointerDiffType(),
6892 };
6893 for (BuiltinCandidateTypeSet::iterator
6894 Ptr = CandidateTypes[Arg].pointer_begin(),
6895 PtrEnd = CandidateTypes[Arg].pointer_end();
6896 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006897 QualType PointeeTy = (*Ptr)->getPointeeType();
6898 if (!PointeeTy->isObjectType())
6899 continue;
6900
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006901 AsymetricParamTypes[Arg] = *Ptr;
6902 if (Arg == 0 || Op == OO_Plus) {
6903 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6904 // T* operator+(ptrdiff_t, T*);
6905 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6906 CandidateSet);
6907 }
6908 if (Op == OO_Minus) {
6909 // ptrdiff_t operator-(T, T);
6910 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6911 continue;
6912
6913 QualType ParamTypes[2] = { *Ptr, *Ptr };
6914 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6915 Args, 2, CandidateSet);
6916 }
6917 }
6918 }
6919 }
6920
6921 // C++ [over.built]p12:
6922 //
6923 // For every pair of promoted arithmetic types L and R, there
6924 // exist candidate operator functions of the form
6925 //
6926 // LR operator*(L, R);
6927 // LR operator/(L, R);
6928 // LR operator+(L, R);
6929 // LR operator-(L, R);
6930 // bool operator<(L, R);
6931 // bool operator>(L, R);
6932 // bool operator<=(L, R);
6933 // bool operator>=(L, R);
6934 // bool operator==(L, R);
6935 // bool operator!=(L, R);
6936 //
6937 // where LR is the result of the usual arithmetic conversions
6938 // between types L and R.
6939 //
6940 // C++ [over.built]p24:
6941 //
6942 // For every pair of promoted arithmetic types L and R, there exist
6943 // candidate operator functions of the form
6944 //
6945 // LR operator?(bool, L, R);
6946 //
6947 // where LR is the result of the usual arithmetic conversions
6948 // between types L and R.
6949 // Our candidates ignore the first parameter.
6950 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006951 if (!HasArithmeticOrEnumeralCandidateType)
6952 return;
6953
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006954 for (unsigned Left = FirstPromotedArithmeticType;
6955 Left < LastPromotedArithmeticType; ++Left) {
6956 for (unsigned Right = FirstPromotedArithmeticType;
6957 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006958 QualType LandR[2] = { getArithmeticType(Left),
6959 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006960 QualType Result =
6961 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006962 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006963 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6964 }
6965 }
6966
6967 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6968 // conditional operator for vector types.
6969 for (BuiltinCandidateTypeSet::iterator
6970 Vec1 = CandidateTypes[0].vector_begin(),
6971 Vec1End = CandidateTypes[0].vector_end();
6972 Vec1 != Vec1End; ++Vec1) {
6973 for (BuiltinCandidateTypeSet::iterator
6974 Vec2 = CandidateTypes[1].vector_begin(),
6975 Vec2End = CandidateTypes[1].vector_end();
6976 Vec2 != Vec2End; ++Vec2) {
6977 QualType LandR[2] = { *Vec1, *Vec2 };
6978 QualType Result = S.Context.BoolTy;
6979 if (!isComparison) {
6980 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6981 Result = *Vec1;
6982 else
6983 Result = *Vec2;
6984 }
6985
6986 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6987 }
6988 }
6989 }
6990
6991 // C++ [over.built]p17:
6992 //
6993 // For every pair of promoted integral types L and R, there
6994 // exist candidate operator functions of the form
6995 //
6996 // LR operator%(L, R);
6997 // LR operator&(L, R);
6998 // LR operator^(L, R);
6999 // LR operator|(L, R);
7000 // L operator<<(L, R);
7001 // L operator>>(L, R);
7002 //
7003 // where LR is the result of the usual arithmetic conversions
7004 // between types L and R.
7005 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007006 if (!HasArithmeticOrEnumeralCandidateType)
7007 return;
7008
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007009 for (unsigned Left = FirstPromotedIntegralType;
7010 Left < LastPromotedIntegralType; ++Left) {
7011 for (unsigned Right = FirstPromotedIntegralType;
7012 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007013 QualType LandR[2] = { getArithmeticType(Left),
7014 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007015 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7016 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007017 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007018 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7019 }
7020 }
7021 }
7022
7023 // C++ [over.built]p20:
7024 //
7025 // For every pair (T, VQ), where T is an enumeration or
7026 // pointer to member type and VQ is either volatile or
7027 // empty, there exist candidate operator functions of the form
7028 //
7029 // VQ T& operator=(VQ T&, T);
7030 void addAssignmentMemberPointerOrEnumeralOverloads() {
7031 /// Set of (canonical) types that we've already handled.
7032 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7033
7034 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7035 for (BuiltinCandidateTypeSet::iterator
7036 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7037 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7038 Enum != EnumEnd; ++Enum) {
7039 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7040 continue;
7041
7042 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7043 CandidateSet);
7044 }
7045
7046 for (BuiltinCandidateTypeSet::iterator
7047 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7048 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7049 MemPtr != MemPtrEnd; ++MemPtr) {
7050 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7051 continue;
7052
7053 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7054 CandidateSet);
7055 }
7056 }
7057 }
7058
7059 // C++ [over.built]p19:
7060 //
7061 // For every pair (T, VQ), where T is any type and VQ is either
7062 // volatile or empty, there exist candidate operator functions
7063 // of the form
7064 //
7065 // T*VQ& operator=(T*VQ&, T*);
7066 //
7067 // C++ [over.built]p21:
7068 //
7069 // For every pair (T, VQ), where T is a cv-qualified or
7070 // cv-unqualified object type and VQ is either volatile or
7071 // empty, there exist candidate operator functions of the form
7072 //
7073 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7074 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7075 void addAssignmentPointerOverloads(bool isEqualOp) {
7076 /// Set of (canonical) types that we've already handled.
7077 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7078
7079 for (BuiltinCandidateTypeSet::iterator
7080 Ptr = CandidateTypes[0].pointer_begin(),
7081 PtrEnd = CandidateTypes[0].pointer_end();
7082 Ptr != PtrEnd; ++Ptr) {
7083 // If this is operator=, keep track of the builtin candidates we added.
7084 if (isEqualOp)
7085 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007086 else if (!(*Ptr)->getPointeeType()->isObjectType())
7087 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007088
7089 // non-volatile version
7090 QualType ParamTypes[2] = {
7091 S.Context.getLValueReferenceType(*Ptr),
7092 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7093 };
7094 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7095 /*IsAssigmentOperator=*/ isEqualOp);
7096
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007097 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7098 VisibleTypeConversionsQuals.hasVolatile();
7099 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007100 // volatile version
7101 ParamTypes[0] =
7102 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7104 /*IsAssigmentOperator=*/isEqualOp);
7105 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007106
7107 if (!(*Ptr).isRestrictQualified() &&
7108 VisibleTypeConversionsQuals.hasRestrict()) {
7109 // restrict version
7110 ParamTypes[0]
7111 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7113 /*IsAssigmentOperator=*/isEqualOp);
7114
7115 if (NeedVolatile) {
7116 // volatile restrict version
7117 ParamTypes[0]
7118 = S.Context.getLValueReferenceType(
7119 S.Context.getCVRQualifiedType(*Ptr,
7120 (Qualifiers::Volatile |
7121 Qualifiers::Restrict)));
7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7123 CandidateSet,
7124 /*IsAssigmentOperator=*/isEqualOp);
7125 }
7126 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007127 }
7128
7129 if (isEqualOp) {
7130 for (BuiltinCandidateTypeSet::iterator
7131 Ptr = CandidateTypes[1].pointer_begin(),
7132 PtrEnd = CandidateTypes[1].pointer_end();
7133 Ptr != PtrEnd; ++Ptr) {
7134 // Make sure we don't add the same candidate twice.
7135 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7136 continue;
7137
Chandler Carruth6df868e2010-12-12 08:17:55 +00007138 QualType ParamTypes[2] = {
7139 S.Context.getLValueReferenceType(*Ptr),
7140 *Ptr,
7141 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007142
7143 // non-volatile version
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7145 /*IsAssigmentOperator=*/true);
7146
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007147 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7148 VisibleTypeConversionsQuals.hasVolatile();
7149 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007150 // volatile version
7151 ParamTypes[0] =
7152 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007153 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7154 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007155 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007156
7157 if (!(*Ptr).isRestrictQualified() &&
7158 VisibleTypeConversionsQuals.hasRestrict()) {
7159 // restrict version
7160 ParamTypes[0]
7161 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7163 CandidateSet, /*IsAssigmentOperator=*/true);
7164
7165 if (NeedVolatile) {
7166 // volatile restrict version
7167 ParamTypes[0]
7168 = S.Context.getLValueReferenceType(
7169 S.Context.getCVRQualifiedType(*Ptr,
7170 (Qualifiers::Volatile |
7171 Qualifiers::Restrict)));
7172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7173 CandidateSet, /*IsAssigmentOperator=*/true);
7174
7175 }
7176 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007177 }
7178 }
7179 }
7180
7181 // C++ [over.built]p18:
7182 //
7183 // For every triple (L, VQ, R), where L is an arithmetic type,
7184 // VQ is either volatile or empty, and R is a promoted
7185 // arithmetic type, there exist candidate operator functions of
7186 // the form
7187 //
7188 // VQ L& operator=(VQ L&, R);
7189 // VQ L& operator*=(VQ L&, R);
7190 // VQ L& operator/=(VQ L&, R);
7191 // VQ L& operator+=(VQ L&, R);
7192 // VQ L& operator-=(VQ L&, R);
7193 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007194 if (!HasArithmeticOrEnumeralCandidateType)
7195 return;
7196
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007197 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7198 for (unsigned Right = FirstPromotedArithmeticType;
7199 Right < LastPromotedArithmeticType; ++Right) {
7200 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007201 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007202
7203 // Add this built-in operator as a candidate (VQ is empty).
7204 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007205 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7207 /*IsAssigmentOperator=*/isEqualOp);
7208
7209 // Add this built-in operator as a candidate (VQ is 'volatile').
7210 if (VisibleTypeConversionsQuals.hasVolatile()) {
7211 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007212 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007213 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007214 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7215 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007216 /*IsAssigmentOperator=*/isEqualOp);
7217 }
7218 }
7219 }
7220
7221 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7222 for (BuiltinCandidateTypeSet::iterator
7223 Vec1 = CandidateTypes[0].vector_begin(),
7224 Vec1End = CandidateTypes[0].vector_end();
7225 Vec1 != Vec1End; ++Vec1) {
7226 for (BuiltinCandidateTypeSet::iterator
7227 Vec2 = CandidateTypes[1].vector_begin(),
7228 Vec2End = CandidateTypes[1].vector_end();
7229 Vec2 != Vec2End; ++Vec2) {
7230 QualType ParamTypes[2];
7231 ParamTypes[1] = *Vec2;
7232 // Add this built-in operator as a candidate (VQ is empty).
7233 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7235 /*IsAssigmentOperator=*/isEqualOp);
7236
7237 // Add this built-in operator as a candidate (VQ is 'volatile').
7238 if (VisibleTypeConversionsQuals.hasVolatile()) {
7239 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7240 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007241 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7242 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 /*IsAssigmentOperator=*/isEqualOp);
7244 }
7245 }
7246 }
7247 }
7248
7249 // C++ [over.built]p22:
7250 //
7251 // For every triple (L, VQ, R), where L is an integral type, VQ
7252 // is either volatile or empty, and R is a promoted integral
7253 // type, there exist candidate operator functions of the form
7254 //
7255 // VQ L& operator%=(VQ L&, R);
7256 // VQ L& operator<<=(VQ L&, R);
7257 // VQ L& operator>>=(VQ L&, R);
7258 // VQ L& operator&=(VQ L&, R);
7259 // VQ L& operator^=(VQ L&, R);
7260 // VQ L& operator|=(VQ L&, R);
7261 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007262 if (!HasArithmeticOrEnumeralCandidateType)
7263 return;
7264
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007265 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7266 for (unsigned Right = FirstPromotedIntegralType;
7267 Right < LastPromotedIntegralType; ++Right) {
7268 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007269 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007270
7271 // Add this built-in operator as a candidate (VQ is empty).
7272 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007273 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7275 if (VisibleTypeConversionsQuals.hasVolatile()) {
7276 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007277 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007278 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7279 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7281 CandidateSet);
7282 }
7283 }
7284 }
7285 }
7286
7287 // C++ [over.operator]p23:
7288 //
7289 // There also exist candidate operator functions of the form
7290 //
7291 // bool operator!(bool);
7292 // bool operator&&(bool, bool);
7293 // bool operator||(bool, bool);
7294 void addExclaimOverload() {
7295 QualType ParamTy = S.Context.BoolTy;
7296 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7297 /*IsAssignmentOperator=*/false,
7298 /*NumContextualBoolArguments=*/1);
7299 }
7300 void addAmpAmpOrPipePipeOverload() {
7301 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7302 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7303 /*IsAssignmentOperator=*/false,
7304 /*NumContextualBoolArguments=*/2);
7305 }
7306
7307 // C++ [over.built]p13:
7308 //
7309 // For every cv-qualified or cv-unqualified object type T there
7310 // exist candidate operator functions of the form
7311 //
7312 // T* operator+(T*, ptrdiff_t); [ABOVE]
7313 // T& operator[](T*, ptrdiff_t);
7314 // T* operator-(T*, ptrdiff_t); [ABOVE]
7315 // T* operator+(ptrdiff_t, T*); [ABOVE]
7316 // T& operator[](ptrdiff_t, T*);
7317 void addSubscriptOverloads() {
7318 for (BuiltinCandidateTypeSet::iterator
7319 Ptr = CandidateTypes[0].pointer_begin(),
7320 PtrEnd = CandidateTypes[0].pointer_end();
7321 Ptr != PtrEnd; ++Ptr) {
7322 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7323 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007324 if (!PointeeType->isObjectType())
7325 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007326
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007327 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7328
7329 // T& operator[](T*, ptrdiff_t)
7330 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7331 }
7332
7333 for (BuiltinCandidateTypeSet::iterator
7334 Ptr = CandidateTypes[1].pointer_begin(),
7335 PtrEnd = CandidateTypes[1].pointer_end();
7336 Ptr != PtrEnd; ++Ptr) {
7337 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7338 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007339 if (!PointeeType->isObjectType())
7340 continue;
7341
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007342 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7343
7344 // T& operator[](ptrdiff_t, T*)
7345 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7346 }
7347 }
7348
7349 // C++ [over.built]p11:
7350 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7351 // C1 is the same type as C2 or is a derived class of C2, T is an object
7352 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7353 // there exist candidate operator functions of the form
7354 //
7355 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7356 //
7357 // where CV12 is the union of CV1 and CV2.
7358 void addArrowStarOverloads() {
7359 for (BuiltinCandidateTypeSet::iterator
7360 Ptr = CandidateTypes[0].pointer_begin(),
7361 PtrEnd = CandidateTypes[0].pointer_end();
7362 Ptr != PtrEnd; ++Ptr) {
7363 QualType C1Ty = (*Ptr);
7364 QualType C1;
7365 QualifierCollector Q1;
7366 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7367 if (!isa<RecordType>(C1))
7368 continue;
7369 // heuristic to reduce number of builtin candidates in the set.
7370 // Add volatile/restrict version only if there are conversions to a
7371 // volatile/restrict type.
7372 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7373 continue;
7374 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7375 continue;
7376 for (BuiltinCandidateTypeSet::iterator
7377 MemPtr = CandidateTypes[1].member_pointer_begin(),
7378 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7379 MemPtr != MemPtrEnd; ++MemPtr) {
7380 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7381 QualType C2 = QualType(mptr->getClass(), 0);
7382 C2 = C2.getUnqualifiedType();
7383 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7384 break;
7385 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7386 // build CV12 T&
7387 QualType T = mptr->getPointeeType();
7388 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7389 T.isVolatileQualified())
7390 continue;
7391 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7392 T.isRestrictQualified())
7393 continue;
7394 T = Q1.apply(S.Context, T);
7395 QualType ResultTy = S.Context.getLValueReferenceType(T);
7396 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7397 }
7398 }
7399 }
7400
7401 // Note that we don't consider the first argument, since it has been
7402 // contextually converted to bool long ago. The candidates below are
7403 // therefore added as binary.
7404 //
7405 // C++ [over.built]p25:
7406 // For every type T, where T is a pointer, pointer-to-member, or scoped
7407 // enumeration type, there exist candidate operator functions of the form
7408 //
7409 // T operator?(bool, T, T);
7410 //
7411 void addConditionalOperatorOverloads() {
7412 /// Set of (canonical) types that we've already handled.
7413 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7414
7415 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7416 for (BuiltinCandidateTypeSet::iterator
7417 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7418 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7419 Ptr != PtrEnd; ++Ptr) {
7420 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7421 continue;
7422
7423 QualType ParamTypes[2] = { *Ptr, *Ptr };
7424 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7425 }
7426
7427 for (BuiltinCandidateTypeSet::iterator
7428 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7429 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7430 MemPtr != MemPtrEnd; ++MemPtr) {
7431 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7432 continue;
7433
7434 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7435 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7436 }
7437
David Blaikie4e4d0842012-03-11 07:00:24 +00007438 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007439 for (BuiltinCandidateTypeSet::iterator
7440 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7441 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7442 Enum != EnumEnd; ++Enum) {
7443 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7444 continue;
7445
7446 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7447 continue;
7448
7449 QualType ParamTypes[2] = { *Enum, *Enum };
7450 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7451 }
7452 }
7453 }
7454 }
7455};
7456
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007457} // end anonymous namespace
7458
7459/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7460/// operator overloads to the candidate set (C++ [over.built]), based
7461/// on the operator @p Op and the arguments given. For example, if the
7462/// operator is a binary '+', this routine might add "int
7463/// operator+(int, int)" to cover integer addition.
7464void
7465Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7466 SourceLocation OpLoc,
7467 Expr **Args, unsigned NumArgs,
7468 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007469 // Find all of the types that the arguments can convert to, but only
7470 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007471 // that make use of these types. Also record whether we encounter non-record
7472 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007473 Qualifiers VisibleTypeConversionsQuals;
7474 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007475 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7476 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007477
7478 bool HasNonRecordCandidateType = false;
7479 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007480 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007481 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7482 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7483 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7484 OpLoc,
7485 true,
7486 (Op == OO_Exclaim ||
7487 Op == OO_AmpAmp ||
7488 Op == OO_PipePipe),
7489 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007490 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7491 CandidateTypes[ArgIdx].hasNonRecordTypes();
7492 HasArithmeticOrEnumeralCandidateType =
7493 HasArithmeticOrEnumeralCandidateType ||
7494 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007495 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007496
Chandler Carruth6a577462010-12-13 01:44:01 +00007497 // Exit early when no non-record types have been added to the candidate set
7498 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007499 //
7500 // We can't exit early for !, ||, or &&, since there we have always have
7501 // 'bool' overloads.
7502 if (!HasNonRecordCandidateType &&
7503 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007504 return;
7505
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007506 // Setup an object to manage the common state for building overloads.
7507 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7508 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007509 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007510 CandidateTypes, CandidateSet);
7511
7512 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007513 switch (Op) {
7514 case OO_None:
7515 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007516 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007517
Chandler Carruthabb71842010-12-12 08:51:33 +00007518 case OO_New:
7519 case OO_Delete:
7520 case OO_Array_New:
7521 case OO_Array_Delete:
7522 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007523 llvm_unreachable(
7524 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007525
7526 case OO_Comma:
7527 case OO_Arrow:
7528 // C++ [over.match.oper]p3:
7529 // -- For the operator ',', the unary operator '&', or the
7530 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007531 break;
7532
7533 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007534 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007535 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007536 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007537
7538 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007539 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007540 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007541 } else {
7542 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7543 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7544 }
Douglas Gregor74253732008-11-19 15:42:04 +00007545 break;
7546
Chandler Carruthabb71842010-12-12 08:51:33 +00007547 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007548 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007549 OpBuilder.addUnaryStarPointerOverloads();
7550 else
7551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7552 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007553
Chandler Carruthabb71842010-12-12 08:51:33 +00007554 case OO_Slash:
7555 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007556 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007557
7558 case OO_PlusPlus:
7559 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007560 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7561 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007562 break;
7563
Douglas Gregor19b7b152009-08-24 13:43:27 +00007564 case OO_EqualEqual:
7565 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007566 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007567 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007568
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007569 case OO_Less:
7570 case OO_Greater:
7571 case OO_LessEqual:
7572 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007573 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007574 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7575 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007576
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007577 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007578 case OO_Caret:
7579 case OO_Pipe:
7580 case OO_LessLess:
7581 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007582 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007583 break;
7584
Chandler Carruthabb71842010-12-12 08:51:33 +00007585 case OO_Amp: // '&' is either unary or binary
7586 if (NumArgs == 1)
7587 // C++ [over.match.oper]p3:
7588 // -- For the operator ',', the unary operator '&', or the
7589 // operator '->', the built-in candidates set is empty.
7590 break;
7591
7592 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7593 break;
7594
7595 case OO_Tilde:
7596 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7597 break;
7598
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007599 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007600 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007601 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007602
7603 case OO_PlusEqual:
7604 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007605 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007606 // Fall through.
7607
7608 case OO_StarEqual:
7609 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007610 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007611 break;
7612
7613 case OO_PercentEqual:
7614 case OO_LessLessEqual:
7615 case OO_GreaterGreaterEqual:
7616 case OO_AmpEqual:
7617 case OO_CaretEqual:
7618 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007619 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007620 break;
7621
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007622 case OO_Exclaim:
7623 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007624 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007625
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007626 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007627 case OO_PipePipe:
7628 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007630
7631 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007633 break;
7634
7635 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007636 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007637 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007638
7639 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007640 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007641 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7642 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007643 }
7644}
7645
Douglas Gregorfa047642009-02-04 00:32:51 +00007646/// \brief Add function candidates found via argument-dependent lookup
7647/// to the set of overloading candidates.
7648///
7649/// This routine performs argument-dependent name lookup based on the
7650/// given function name (which may also be an operator name) and adds
7651/// all of the overload candidates found by ADL to the overload
7652/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007653void
Douglas Gregorfa047642009-02-04 00:32:51 +00007654Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007655 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007656 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007657 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007658 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007659 bool PartialOverloading,
7660 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007661 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007662
John McCalla113e722010-01-26 06:04:06 +00007663 // FIXME: This approach for uniquing ADL results (and removing
7664 // redundant candidates from the set) relies on pointer-equality,
7665 // which means we need to key off the canonical decl. However,
7666 // always going back to the canonical decl might not get us the
7667 // right set of default arguments. What default arguments are
7668 // we supposed to consider on ADL candidates, anyway?
7669
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007670 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007671 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007672 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007673
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007674 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007675 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7676 CandEnd = CandidateSet.end();
7677 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007678 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007679 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007680 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007681 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007682 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007683
7684 // For each of the ADL candidates we found, add it to the overload
7685 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007686 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007687 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007689 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007690 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007691
Ahmed Charles13a140c2012-02-25 11:00:22 +00007692 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7693 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007694 } else
John McCall6e266892010-01-26 03:27:55 +00007695 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007696 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007697 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007698 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007699}
7700
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007701/// isBetterOverloadCandidate - Determines whether the first overload
7702/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007703bool
John McCall120d63c2010-08-24 20:38:10 +00007704isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007705 const OverloadCandidate &Cand1,
7706 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007707 SourceLocation Loc,
7708 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007709 // Define viable functions to be better candidates than non-viable
7710 // functions.
7711 if (!Cand2.Viable)
7712 return Cand1.Viable;
7713 else if (!Cand1.Viable)
7714 return false;
7715
Douglas Gregor88a35142008-12-22 05:46:06 +00007716 // C++ [over.match.best]p1:
7717 //
7718 // -- if F is a static member function, ICS1(F) is defined such
7719 // that ICS1(F) is neither better nor worse than ICS1(G) for
7720 // any function G, and, symmetrically, ICS1(G) is neither
7721 // better nor worse than ICS1(F).
7722 unsigned StartArg = 0;
7723 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7724 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007725
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007726 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007727 // A viable function F1 is defined to be a better function than another
7728 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007729 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007730 unsigned NumArgs = Cand1.NumConversions;
7731 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007732 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007733 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007734 switch (CompareImplicitConversionSequences(S,
7735 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007736 Cand2.Conversions[ArgIdx])) {
7737 case ImplicitConversionSequence::Better:
7738 // Cand1 has a better conversion sequence.
7739 HasBetterConversion = true;
7740 break;
7741
7742 case ImplicitConversionSequence::Worse:
7743 // Cand1 can't be better than Cand2.
7744 return false;
7745
7746 case ImplicitConversionSequence::Indistinguishable:
7747 // Do nothing.
7748 break;
7749 }
7750 }
7751
Mike Stump1eb44332009-09-09 15:08:12 +00007752 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007753 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007754 if (HasBetterConversion)
7755 return true;
7756
Mike Stump1eb44332009-09-09 15:08:12 +00007757 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007758 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007759 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007760 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7761 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007762
7763 // -- F1 and F2 are function template specializations, and the function
7764 // template for F1 is more specialized than the template for F2
7765 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007766 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007767 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007768 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007769 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007770 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7771 Cand2.Function->getPrimaryTemplate(),
7772 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007773 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007774 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007775 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007776 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007777 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007778
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007779 // -- the context is an initialization by user-defined conversion
7780 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7781 // from the return type of F1 to the destination type (i.e.,
7782 // the type of the entity being initialized) is a better
7783 // conversion sequence than the standard conversion sequence
7784 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007785 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007786 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007787 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007788 // First check whether we prefer one of the conversion functions over the
7789 // other. This only distinguishes the results in non-standard, extension
7790 // cases such as the conversion from a lambda closure type to a function
7791 // pointer or block.
7792 ImplicitConversionSequence::CompareKind FuncResult
7793 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7794 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7795 return FuncResult;
7796
John McCall120d63c2010-08-24 20:38:10 +00007797 switch (CompareStandardConversionSequences(S,
7798 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007799 Cand2.FinalConversion)) {
7800 case ImplicitConversionSequence::Better:
7801 // Cand1 has a better conversion sequence.
7802 return true;
7803
7804 case ImplicitConversionSequence::Worse:
7805 // Cand1 can't be better than Cand2.
7806 return false;
7807
7808 case ImplicitConversionSequence::Indistinguishable:
7809 // Do nothing
7810 break;
7811 }
7812 }
7813
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007814 return false;
7815}
7816
Mike Stump1eb44332009-09-09 15:08:12 +00007817/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007818/// within an overload candidate set.
7819///
7820/// \param CandidateSet the set of candidate functions.
7821///
7822/// \param Loc the location of the function name (or operator symbol) for
7823/// which overload resolution occurs.
7824///
Mike Stump1eb44332009-09-09 15:08:12 +00007825/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007826/// function, Best points to the candidate function found.
7827///
7828/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007829OverloadingResult
7830OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007831 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007832 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007833 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007834 Best = end();
7835 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7836 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007837 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007838 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007839 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007840 }
7841
7842 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007843 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007844 return OR_No_Viable_Function;
7845
7846 // Make sure that this function is better than every other viable
7847 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007848 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007849 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007850 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007851 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007852 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007853 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007854 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007855 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007856 }
Mike Stump1eb44332009-09-09 15:08:12 +00007857
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007858 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007859 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007860 (Best->Function->isDeleted() ||
7861 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007862 return OR_Deleted;
7863
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007864 return OR_Success;
7865}
7866
John McCall3c80f572010-01-12 02:15:36 +00007867namespace {
7868
7869enum OverloadCandidateKind {
7870 oc_function,
7871 oc_method,
7872 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007873 oc_function_template,
7874 oc_method_template,
7875 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007876 oc_implicit_default_constructor,
7877 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007878 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007879 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007880 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007881 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007882};
7883
John McCall220ccbf2010-01-13 00:25:19 +00007884OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7885 FunctionDecl *Fn,
7886 std::string &Description) {
7887 bool isTemplate = false;
7888
7889 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7890 isTemplate = true;
7891 Description = S.getTemplateArgumentBindingsText(
7892 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7893 }
John McCallb1622a12010-01-06 09:43:14 +00007894
7895 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007896 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007897 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007898
Sebastian Redlf677ea32011-02-05 19:23:19 +00007899 if (Ctor->getInheritedConstructor())
7900 return oc_implicit_inherited_constructor;
7901
Sean Hunt82713172011-05-25 23:16:36 +00007902 if (Ctor->isDefaultConstructor())
7903 return oc_implicit_default_constructor;
7904
7905 if (Ctor->isMoveConstructor())
7906 return oc_implicit_move_constructor;
7907
7908 assert(Ctor->isCopyConstructor() &&
7909 "unexpected sort of implicit constructor");
7910 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007911 }
7912
7913 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7914 // This actually gets spelled 'candidate function' for now, but
7915 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007916 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007917 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007918
Sean Hunt82713172011-05-25 23:16:36 +00007919 if (Meth->isMoveAssignmentOperator())
7920 return oc_implicit_move_assignment;
7921
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007922 if (Meth->isCopyAssignmentOperator())
7923 return oc_implicit_copy_assignment;
7924
7925 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7926 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007927 }
7928
John McCall220ccbf2010-01-13 00:25:19 +00007929 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007930}
7931
Sebastian Redlf677ea32011-02-05 19:23:19 +00007932void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7933 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7934 if (!Ctor) return;
7935
7936 Ctor = Ctor->getInheritedConstructor();
7937 if (!Ctor) return;
7938
7939 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7940}
7941
John McCall3c80f572010-01-12 02:15:36 +00007942} // end anonymous namespace
7943
7944// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007945void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007946 std::string FnDesc;
7947 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007948 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7949 << (unsigned) K << FnDesc;
7950 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7951 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007952 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007953}
7954
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007955//Notes the location of all overload candidates designated through
7956// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007957void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007958 assert(OverloadedExpr->getType() == Context.OverloadTy);
7959
7960 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7961 OverloadExpr *OvlExpr = Ovl.Expression;
7962
7963 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7964 IEnd = OvlExpr->decls_end();
7965 I != IEnd; ++I) {
7966 if (FunctionTemplateDecl *FunTmpl =
7967 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007968 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007969 } else if (FunctionDecl *Fun
7970 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007971 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007972 }
7973 }
7974}
7975
John McCall1d318332010-01-12 00:44:57 +00007976/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7977/// "lead" diagnostic; it will be given two arguments, the source and
7978/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007979void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7980 Sema &S,
7981 SourceLocation CaretLoc,
7982 const PartialDiagnostic &PDiag) const {
7983 S.Diag(CaretLoc, PDiag)
7984 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007985 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007986 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7987 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007988 }
John McCall81201622010-01-08 04:41:39 +00007989}
7990
John McCall1d318332010-01-12 00:44:57 +00007991namespace {
7992
John McCalladbb8f82010-01-13 09:16:55 +00007993void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7994 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7995 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007996 assert(Cand->Function && "for now, candidate must be a function");
7997 FunctionDecl *Fn = Cand->Function;
7998
7999 // There's a conversion slot for the object argument if this is a
8000 // non-constructor method. Note that 'I' corresponds the
8001 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008002 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008003 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008004 if (I == 0)
8005 isObjectArgument = true;
8006 else
8007 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008008 }
8009
John McCall220ccbf2010-01-13 00:25:19 +00008010 std::string FnDesc;
8011 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8012
John McCalladbb8f82010-01-13 09:16:55 +00008013 Expr *FromExpr = Conv.Bad.FromExpr;
8014 QualType FromTy = Conv.Bad.getFromType();
8015 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008016
John McCall5920dbb2010-02-02 02:42:52 +00008017 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008018 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008019 Expr *E = FromExpr->IgnoreParens();
8020 if (isa<UnaryOperator>(E))
8021 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008022 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008023
8024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8025 << (unsigned) FnKind << FnDesc
8026 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8027 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008028 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008029 return;
8030 }
8031
John McCall258b2032010-01-23 08:10:49 +00008032 // Do some hand-waving analysis to see if the non-viability is due
8033 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008034 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8035 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8036 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8037 CToTy = RT->getPointeeType();
8038 else {
8039 // TODO: detect and diagnose the full richness of const mismatches.
8040 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8041 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8042 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8043 }
8044
8045 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8046 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008047 Qualifiers FromQs = CFromTy.getQualifiers();
8048 Qualifiers ToQs = CToTy.getQualifiers();
8049
8050 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8051 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8052 << (unsigned) FnKind << FnDesc
8053 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8054 << FromTy
8055 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8056 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008057 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008058 return;
8059 }
8060
John McCallf85e1932011-06-15 23:02:42 +00008061 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008063 << (unsigned) FnKind << FnDesc
8064 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8065 << FromTy
8066 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8067 << (unsigned) isObjectArgument << I+1;
8068 MaybeEmitInheritedConstructorNote(S, Fn);
8069 return;
8070 }
8071
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008072 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8073 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8074 << (unsigned) FnKind << FnDesc
8075 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8076 << FromTy
8077 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8078 << (unsigned) isObjectArgument << I+1;
8079 MaybeEmitInheritedConstructorNote(S, Fn);
8080 return;
8081 }
8082
John McCall651f3ee2010-01-14 03:28:57 +00008083 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8084 assert(CVR && "unexpected qualifiers mismatch");
8085
8086 if (isObjectArgument) {
8087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8088 << (unsigned) FnKind << FnDesc
8089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8090 << FromTy << (CVR - 1);
8091 } else {
8092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8093 << (unsigned) FnKind << FnDesc
8094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8095 << FromTy << (CVR - 1) << I+1;
8096 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008097 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008098 return;
8099 }
8100
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008101 // Special diagnostic for failure to convert an initializer list, since
8102 // telling the user that it has type void is not useful.
8103 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8105 << (unsigned) FnKind << FnDesc
8106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8107 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8108 MaybeEmitInheritedConstructorNote(S, Fn);
8109 return;
8110 }
8111
John McCall258b2032010-01-23 08:10:49 +00008112 // Diagnose references or pointers to incomplete types differently,
8113 // since it's far from impossible that the incompleteness triggered
8114 // the failure.
8115 QualType TempFromTy = FromTy.getNonReferenceType();
8116 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8117 TempFromTy = PTy->getPointeeType();
8118 if (TempFromTy->isIncompleteType()) {
8119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8120 << (unsigned) FnKind << FnDesc
8121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8122 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008123 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008124 return;
8125 }
8126
Douglas Gregor85789812010-06-30 23:01:39 +00008127 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008128 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008129 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8130 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8131 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8132 FromPtrTy->getPointeeType()) &&
8133 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8134 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008135 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008136 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008137 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008138 }
8139 } else if (const ObjCObjectPointerType *FromPtrTy
8140 = FromTy->getAs<ObjCObjectPointerType>()) {
8141 if (const ObjCObjectPointerType *ToPtrTy
8142 = ToTy->getAs<ObjCObjectPointerType>())
8143 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8144 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8145 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8146 FromPtrTy->getPointeeType()) &&
8147 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008148 BaseToDerivedConversion = 2;
8149 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8150 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8151 !FromTy->isIncompleteType() &&
8152 !ToRefTy->getPointeeType()->isIncompleteType() &&
8153 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8154 BaseToDerivedConversion = 3;
8155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008156
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008157 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008158 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008159 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008160 << (unsigned) FnKind << FnDesc
8161 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008162 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008163 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008164 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008165 return;
8166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008167
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008168 if (isa<ObjCObjectPointerType>(CFromTy) &&
8169 isa<PointerType>(CToTy)) {
8170 Qualifiers FromQs = CFromTy.getQualifiers();
8171 Qualifiers ToQs = CToTy.getQualifiers();
8172 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8174 << (unsigned) FnKind << FnDesc
8175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8176 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8177 MaybeEmitInheritedConstructorNote(S, Fn);
8178 return;
8179 }
8180 }
8181
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008182 // Emit the generic diagnostic and, optionally, add the hints to it.
8183 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8184 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008186 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8187 << (unsigned) (Cand->Fix.Kind);
8188
8189 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008190 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8191 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008192 FDiag << *HI;
8193 S.Diag(Fn->getLocation(), FDiag);
8194
Sebastian Redlf677ea32011-02-05 19:23:19 +00008195 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008196}
8197
8198void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8199 unsigned NumFormalArgs) {
8200 // TODO: treat calls to a missing default constructor as a special case
8201
8202 FunctionDecl *Fn = Cand->Function;
8203 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8204
8205 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008206
Douglas Gregor439d3c32011-05-05 00:13:13 +00008207 // With invalid overloaded operators, it's possible that we think we
8208 // have an arity mismatch when it fact it looks like we have the
8209 // right number of arguments, because only overloaded operators have
8210 // the weird behavior of overloading member and non-member functions.
8211 // Just don't report anything.
8212 if (Fn->isInvalidDecl() &&
8213 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8214 return;
8215
John McCalladbb8f82010-01-13 09:16:55 +00008216 // at least / at most / exactly
8217 unsigned mode, modeCount;
8218 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008219 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8220 (Cand->FailureKind == ovl_fail_bad_deduction &&
8221 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008222 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008223 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008224 mode = 0; // "at least"
8225 else
8226 mode = 2; // "exactly"
8227 modeCount = MinParams;
8228 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008229 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8230 (Cand->FailureKind == ovl_fail_bad_deduction &&
8231 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008232 if (MinParams != FnTy->getNumArgs())
8233 mode = 1; // "at most"
8234 else
8235 mode = 2; // "exactly"
8236 modeCount = FnTy->getNumArgs();
8237 }
8238
8239 std::string Description;
8240 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8241
Richard Smithf7b80562012-05-11 05:16:41 +00008242 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8244 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8245 << Fn->getParamDecl(0) << NumFormalArgs;
8246 else
8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8249 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008250 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008251}
8252
John McCall342fec42010-02-01 18:53:26 +00008253/// Diagnose a failed template-argument deduction.
8254void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008255 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008256 FunctionDecl *Fn = Cand->Function; // pattern
8257
Douglas Gregora9333192010-05-08 17:41:32 +00008258 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008259 NamedDecl *ParamD;
8260 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8261 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8262 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008263 switch (Cand->DeductionFailure.Result) {
8264 case Sema::TDK_Success:
8265 llvm_unreachable("TDK_success while diagnosing bad deduction");
8266
8267 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008268 assert(ParamD && "no parameter found for incomplete deduction result");
8269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8270 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008271 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008272 return;
8273 }
8274
John McCall57e97782010-08-05 09:05:08 +00008275 case Sema::TDK_Underqualified: {
8276 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8277 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8278
8279 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8280
8281 // Param will have been canonicalized, but it should just be a
8282 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008283 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008284 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008285 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008286 assert(S.Context.hasSameType(Param, NonCanonParam));
8287
8288 // Arg has also been canonicalized, but there's nothing we can do
8289 // about that. It also doesn't matter as much, because it won't
8290 // have any template parameters in it (because deduction isn't
8291 // done on dependent types).
8292 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8293
8294 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8295 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008296 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008297 return;
8298 }
8299
8300 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008301 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008302 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008303 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008304 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008305 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008306 which = 1;
8307 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008308 which = 2;
8309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008310
Douglas Gregora9333192010-05-08 17:41:32 +00008311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008312 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008313 << *Cand->DeductionFailure.getFirstArg()
8314 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008315 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008316 return;
8317 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008318
Douglas Gregorf1a84452010-05-08 19:15:54 +00008319 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008320 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008321 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008322 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008323 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8324 << ParamD->getDeclName();
8325 else {
8326 int index = 0;
8327 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8328 index = TTP->getIndex();
8329 else if (NonTypeTemplateParmDecl *NTTP
8330 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8331 index = NTTP->getIndex();
8332 else
8333 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008334 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008335 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8336 << (index + 1);
8337 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008338 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008339 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008340
Douglas Gregora18592e2010-05-08 18:13:28 +00008341 case Sema::TDK_TooManyArguments:
8342 case Sema::TDK_TooFewArguments:
8343 DiagnoseArityMismatch(S, Cand, NumArgs);
8344 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008345
8346 case Sema::TDK_InstantiationDepth:
8347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008348 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008349 return;
8350
8351 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008352 // Format the template argument list into the argument string.
8353 llvm::SmallString<128> TemplateArgString;
8354 if (TemplateArgumentList *Args =
8355 Cand->DeductionFailure.getTemplateArgumentList()) {
8356 TemplateArgString = " ";
8357 TemplateArgString += S.getTemplateArgumentBindingsText(
8358 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8359 }
8360
Richard Smith4493c0a2012-05-09 05:17:00 +00008361 // If this candidate was disabled by enable_if, say so.
8362 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8363 if (PDiag && PDiag->second.getDiagID() ==
8364 diag::err_typename_nested_not_found_enable_if) {
8365 // FIXME: Use the source range of the condition, and the fully-qualified
8366 // name of the enable_if template. These are both present in PDiag.
8367 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8368 << "'enable_if'" << TemplateArgString;
8369 return;
8370 }
8371
Richard Smithb8590f32012-05-07 09:03:25 +00008372 // Format the SFINAE diagnostic into the argument string.
8373 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8374 // formatted message in another diagnostic.
8375 llvm::SmallString<128> SFINAEArgString;
8376 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008377 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008378 SFINAEArgString = ": ";
8379 R = SourceRange(PDiag->first, PDiag->first);
8380 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8381 }
8382
Douglas Gregorec20f462010-05-08 20:07:26 +00008383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008384 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008385 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008386 return;
8387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008388
John McCall342fec42010-02-01 18:53:26 +00008389 // TODO: diagnose these individually, then kill off
8390 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008391 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008392 case Sema::TDK_FailedOverloadResolution:
8393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008394 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008395 return;
8396 }
8397}
8398
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008399/// CUDA: diagnose an invalid call across targets.
8400void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8401 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8402 FunctionDecl *Callee = Cand->Function;
8403
8404 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8405 CalleeTarget = S.IdentifyCUDATarget(Callee);
8406
8407 std::string FnDesc;
8408 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8409
8410 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8411 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8412}
8413
John McCall342fec42010-02-01 18:53:26 +00008414/// Generates a 'note' diagnostic for an overload candidate. We've
8415/// already generated a primary error at the call site.
8416///
8417/// It really does need to be a single diagnostic with its caret
8418/// pointed at the candidate declaration. Yes, this creates some
8419/// major challenges of technical writing. Yes, this makes pointing
8420/// out problems with specific arguments quite awkward. It's still
8421/// better than generating twenty screens of text for every failed
8422/// overload.
8423///
8424/// It would be great to be able to express per-candidate problems
8425/// more richly for those diagnostic clients that cared, but we'd
8426/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008427void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008428 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008429 FunctionDecl *Fn = Cand->Function;
8430
John McCall81201622010-01-08 04:41:39 +00008431 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008432 if (Cand->Viable && (Fn->isDeleted() ||
8433 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008434 std::string FnDesc;
8435 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008436
8437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008438 << FnKind << FnDesc
8439 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008440 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008441 return;
John McCall81201622010-01-08 04:41:39 +00008442 }
8443
John McCall220ccbf2010-01-13 00:25:19 +00008444 // We don't really have anything else to say about viable candidates.
8445 if (Cand->Viable) {
8446 S.NoteOverloadCandidate(Fn);
8447 return;
8448 }
John McCall1d318332010-01-12 00:44:57 +00008449
John McCalladbb8f82010-01-13 09:16:55 +00008450 switch (Cand->FailureKind) {
8451 case ovl_fail_too_many_arguments:
8452 case ovl_fail_too_few_arguments:
8453 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008454
John McCalladbb8f82010-01-13 09:16:55 +00008455 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008456 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008457
John McCall717e8912010-01-23 05:17:32 +00008458 case ovl_fail_trivial_conversion:
8459 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008460 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008461 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008462
John McCallb1bdc622010-02-25 01:37:24 +00008463 case ovl_fail_bad_conversion: {
8464 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008465 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008466 if (Cand->Conversions[I].isBad())
8467 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008468
John McCalladbb8f82010-01-13 09:16:55 +00008469 // FIXME: this currently happens when we're called from SemaInit
8470 // when user-conversion overload fails. Figure out how to handle
8471 // those conditions and diagnose them well.
8472 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008473 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008474
8475 case ovl_fail_bad_target:
8476 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008477 }
John McCalla1d7d622010-01-08 00:58:21 +00008478}
8479
8480void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8481 // Desugar the type of the surrogate down to a function type,
8482 // retaining as many typedefs as possible while still showing
8483 // the function type (and, therefore, its parameter types).
8484 QualType FnType = Cand->Surrogate->getConversionType();
8485 bool isLValueReference = false;
8486 bool isRValueReference = false;
8487 bool isPointer = false;
8488 if (const LValueReferenceType *FnTypeRef =
8489 FnType->getAs<LValueReferenceType>()) {
8490 FnType = FnTypeRef->getPointeeType();
8491 isLValueReference = true;
8492 } else if (const RValueReferenceType *FnTypeRef =
8493 FnType->getAs<RValueReferenceType>()) {
8494 FnType = FnTypeRef->getPointeeType();
8495 isRValueReference = true;
8496 }
8497 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8498 FnType = FnTypePtr->getPointeeType();
8499 isPointer = true;
8500 }
8501 // Desugar down to a function type.
8502 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8503 // Reconstruct the pointer/reference as appropriate.
8504 if (isPointer) FnType = S.Context.getPointerType(FnType);
8505 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8506 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8507
8508 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8509 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008510 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008511}
8512
8513void NoteBuiltinOperatorCandidate(Sema &S,
8514 const char *Opc,
8515 SourceLocation OpLoc,
8516 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008517 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008518 std::string TypeStr("operator");
8519 TypeStr += Opc;
8520 TypeStr += "(";
8521 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008522 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008523 TypeStr += ")";
8524 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8525 } else {
8526 TypeStr += ", ";
8527 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8528 TypeStr += ")";
8529 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8530 }
8531}
8532
8533void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8534 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008535 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008536 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8537 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008538 if (ICS.isBad()) break; // all meaningless after first invalid
8539 if (!ICS.isAmbiguous()) continue;
8540
John McCall120d63c2010-08-24 20:38:10 +00008541 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008542 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008543 }
8544}
8545
John McCall1b77e732010-01-15 23:32:50 +00008546SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8547 if (Cand->Function)
8548 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008549 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008550 return Cand->Surrogate->getLocation();
8551 return SourceLocation();
8552}
8553
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008554static unsigned
8555RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008556 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008557 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008558 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008559
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008560 case Sema::TDK_Incomplete:
8561 return 1;
8562
8563 case Sema::TDK_Underqualified:
8564 case Sema::TDK_Inconsistent:
8565 return 2;
8566
8567 case Sema::TDK_SubstitutionFailure:
8568 case Sema::TDK_NonDeducedMismatch:
8569 return 3;
8570
8571 case Sema::TDK_InstantiationDepth:
8572 case Sema::TDK_FailedOverloadResolution:
8573 return 4;
8574
8575 case Sema::TDK_InvalidExplicitArguments:
8576 return 5;
8577
8578 case Sema::TDK_TooManyArguments:
8579 case Sema::TDK_TooFewArguments:
8580 return 6;
8581 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008582 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008583}
8584
John McCallbf65c0b2010-01-12 00:48:53 +00008585struct CompareOverloadCandidatesForDisplay {
8586 Sema &S;
8587 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008588
8589 bool operator()(const OverloadCandidate *L,
8590 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008591 // Fast-path this check.
8592 if (L == R) return false;
8593
John McCall81201622010-01-08 04:41:39 +00008594 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008595 if (L->Viable) {
8596 if (!R->Viable) return true;
8597
8598 // TODO: introduce a tri-valued comparison for overload
8599 // candidates. Would be more worthwhile if we had a sort
8600 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008601 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8602 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008603 } else if (R->Viable)
8604 return false;
John McCall81201622010-01-08 04:41:39 +00008605
John McCall1b77e732010-01-15 23:32:50 +00008606 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008607
John McCall1b77e732010-01-15 23:32:50 +00008608 // Criteria by which we can sort non-viable candidates:
8609 if (!L->Viable) {
8610 // 1. Arity mismatches come after other candidates.
8611 if (L->FailureKind == ovl_fail_too_many_arguments ||
8612 L->FailureKind == ovl_fail_too_few_arguments)
8613 return false;
8614 if (R->FailureKind == ovl_fail_too_many_arguments ||
8615 R->FailureKind == ovl_fail_too_few_arguments)
8616 return true;
John McCall81201622010-01-08 04:41:39 +00008617
John McCall717e8912010-01-23 05:17:32 +00008618 // 2. Bad conversions come first and are ordered by the number
8619 // of bad conversions and quality of good conversions.
8620 if (L->FailureKind == ovl_fail_bad_conversion) {
8621 if (R->FailureKind != ovl_fail_bad_conversion)
8622 return true;
8623
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008624 // The conversion that can be fixed with a smaller number of changes,
8625 // comes first.
8626 unsigned numLFixes = L->Fix.NumConversionsFixed;
8627 unsigned numRFixes = R->Fix.NumConversionsFixed;
8628 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8629 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008630 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008631 if (numLFixes < numRFixes)
8632 return true;
8633 else
8634 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008635 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008636
John McCall717e8912010-01-23 05:17:32 +00008637 // If there's any ordering between the defined conversions...
8638 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008639 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008640
8641 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008642 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008643 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008644 switch (CompareImplicitConversionSequences(S,
8645 L->Conversions[I],
8646 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008647 case ImplicitConversionSequence::Better:
8648 leftBetter++;
8649 break;
8650
8651 case ImplicitConversionSequence::Worse:
8652 leftBetter--;
8653 break;
8654
8655 case ImplicitConversionSequence::Indistinguishable:
8656 break;
8657 }
8658 }
8659 if (leftBetter > 0) return true;
8660 if (leftBetter < 0) return false;
8661
8662 } else if (R->FailureKind == ovl_fail_bad_conversion)
8663 return false;
8664
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008665 if (L->FailureKind == ovl_fail_bad_deduction) {
8666 if (R->FailureKind != ovl_fail_bad_deduction)
8667 return true;
8668
8669 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8670 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008671 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008672 } else if (R->FailureKind == ovl_fail_bad_deduction)
8673 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008674
John McCall1b77e732010-01-15 23:32:50 +00008675 // TODO: others?
8676 }
8677
8678 // Sort everything else by location.
8679 SourceLocation LLoc = GetLocationForCandidate(L);
8680 SourceLocation RLoc = GetLocationForCandidate(R);
8681
8682 // Put candidates without locations (e.g. builtins) at the end.
8683 if (LLoc.isInvalid()) return false;
8684 if (RLoc.isInvalid()) return true;
8685
8686 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008687 }
8688};
8689
John McCall717e8912010-01-23 05:17:32 +00008690/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008691/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008692void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008693 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008694 assert(!Cand->Viable);
8695
8696 // Don't do anything on failures other than bad conversion.
8697 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8698
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008699 // We only want the FixIts if all the arguments can be corrected.
8700 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008701 // Use a implicit copy initialization to check conversion fixes.
8702 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008703
John McCall717e8912010-01-23 05:17:32 +00008704 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008705 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008706 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008707 while (true) {
8708 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8709 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008710 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008711 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008712 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008713 }
John McCall717e8912010-01-23 05:17:32 +00008714 }
8715
8716 if (ConvIdx == ConvCount)
8717 return;
8718
John McCallb1bdc622010-02-25 01:37:24 +00008719 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8720 "remaining conversion is initialized?");
8721
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008722 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008723 // operation somehow.
8724 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008725
8726 const FunctionProtoType* Proto;
8727 unsigned ArgIdx = ConvIdx;
8728
8729 if (Cand->IsSurrogate) {
8730 QualType ConvType
8731 = Cand->Surrogate->getConversionType().getNonReferenceType();
8732 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8733 ConvType = ConvPtrType->getPointeeType();
8734 Proto = ConvType->getAs<FunctionProtoType>();
8735 ArgIdx--;
8736 } else if (Cand->Function) {
8737 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8738 if (isa<CXXMethodDecl>(Cand->Function) &&
8739 !isa<CXXConstructorDecl>(Cand->Function))
8740 ArgIdx--;
8741 } else {
8742 // Builtin binary operator with a bad first conversion.
8743 assert(ConvCount <= 3);
8744 for (; ConvIdx != ConvCount; ++ConvIdx)
8745 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008746 = TryCopyInitialization(S, Args[ConvIdx],
8747 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008748 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008749 /*InOverloadResolution*/ true,
8750 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008751 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008752 return;
8753 }
8754
8755 // Fill in the rest of the conversions.
8756 unsigned NumArgsInProto = Proto->getNumArgs();
8757 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008758 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008759 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008760 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008761 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008762 /*InOverloadResolution=*/true,
8763 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008764 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008765 // Store the FixIt in the candidate if it exists.
8766 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008767 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008768 }
John McCall717e8912010-01-23 05:17:32 +00008769 else
8770 Cand->Conversions[ConvIdx].setEllipsis();
8771 }
8772}
8773
John McCalla1d7d622010-01-08 00:58:21 +00008774} // end anonymous namespace
8775
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008776/// PrintOverloadCandidates - When overload resolution fails, prints
8777/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008778/// set.
John McCall120d63c2010-08-24 20:38:10 +00008779void OverloadCandidateSet::NoteCandidates(Sema &S,
8780 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008781 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008782 const char *Opc,
8783 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008784 // Sort the candidates by viability and position. Sorting directly would
8785 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008786 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008787 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8788 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008789 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008790 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008791 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008792 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008793 if (Cand->Function || Cand->IsSurrogate)
8794 Cands.push_back(Cand);
8795 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8796 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008797 }
8798 }
8799
John McCallbf65c0b2010-01-12 00:48:53 +00008800 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008801 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008802
John McCall1d318332010-01-12 00:44:57 +00008803 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008804
Chris Lattner5f9e2722011-07-23 10:55:15 +00008805 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008806 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8807 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008808 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008809 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8810 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008811
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008812 // Set an arbitrary limit on the number of candidate functions we'll spam
8813 // the user with. FIXME: This limit should depend on details of the
8814 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008815 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008816 break;
8817 }
8818 ++CandsShown;
8819
John McCalla1d7d622010-01-08 00:58:21 +00008820 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008821 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008822 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008823 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008824 else {
8825 assert(Cand->Viable &&
8826 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008827 // Generally we only see ambiguities including viable builtin
8828 // operators if overload resolution got screwed up by an
8829 // ambiguous user-defined conversion.
8830 //
8831 // FIXME: It's quite possible for different conversions to see
8832 // different ambiguities, though.
8833 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008834 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008835 ReportedAmbiguousConversions = true;
8836 }
John McCalla1d7d622010-01-08 00:58:21 +00008837
John McCall1d318332010-01-12 00:44:57 +00008838 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008839 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008840 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008841 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008842
8843 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008844 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008845}
8846
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008847// [PossiblyAFunctionType] --> [Return]
8848// NonFunctionType --> NonFunctionType
8849// R (A) --> R(A)
8850// R (*)(A) --> R (A)
8851// R (&)(A) --> R (A)
8852// R (S::*)(A) --> R (A)
8853QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8854 QualType Ret = PossiblyAFunctionType;
8855 if (const PointerType *ToTypePtr =
8856 PossiblyAFunctionType->getAs<PointerType>())
8857 Ret = ToTypePtr->getPointeeType();
8858 else if (const ReferenceType *ToTypeRef =
8859 PossiblyAFunctionType->getAs<ReferenceType>())
8860 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008861 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008862 PossiblyAFunctionType->getAs<MemberPointerType>())
8863 Ret = MemTypePtr->getPointeeType();
8864 Ret =
8865 Context.getCanonicalType(Ret).getUnqualifiedType();
8866 return Ret;
8867}
Douglas Gregor904eed32008-11-10 20:40:00 +00008868
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008869// A helper class to help with address of function resolution
8870// - allows us to avoid passing around all those ugly parameters
8871class AddressOfFunctionResolver
8872{
8873 Sema& S;
8874 Expr* SourceExpr;
8875 const QualType& TargetType;
8876 QualType TargetFunctionType; // Extracted function type from target type
8877
8878 bool Complain;
8879 //DeclAccessPair& ResultFunctionAccessPair;
8880 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008881
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008882 bool TargetTypeIsNonStaticMemberFunction;
8883 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008884
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008885 OverloadExpr::FindResult OvlExprInfo;
8886 OverloadExpr *OvlExpr;
8887 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008888 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008889
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008890public:
8891 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8892 const QualType& TargetType, bool Complain)
8893 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8894 Complain(Complain), Context(S.getASTContext()),
8895 TargetTypeIsNonStaticMemberFunction(
8896 !!TargetType->getAs<MemberPointerType>()),
8897 FoundNonTemplateFunction(false),
8898 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8899 OvlExpr(OvlExprInfo.Expression)
8900 {
8901 ExtractUnqualifiedFunctionTypeFromTargetType();
8902
8903 if (!TargetFunctionType->isFunctionType()) {
8904 if (OvlExpr->hasExplicitTemplateArgs()) {
8905 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008906 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008907 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008908
8909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8910 if (!Method->isStatic()) {
8911 // If the target type is a non-function type and the function
8912 // found is a non-static member function, pretend as if that was
8913 // the target, it's the only possible type to end up with.
8914 TargetTypeIsNonStaticMemberFunction = true;
8915
8916 // And skip adding the function if its not in the proper form.
8917 // We'll diagnose this due to an empty set of functions.
8918 if (!OvlExprInfo.HasFormOfMemberPointer)
8919 return;
8920 }
8921 }
8922
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008923 Matches.push_back(std::make_pair(dap,Fn));
8924 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008925 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008926 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008927 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008928
8929 if (OvlExpr->hasExplicitTemplateArgs())
8930 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008931
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008932 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8933 // C++ [over.over]p4:
8934 // If more than one function is selected, [...]
8935 if (Matches.size() > 1) {
8936 if (FoundNonTemplateFunction)
8937 EliminateAllTemplateMatches();
8938 else
8939 EliminateAllExceptMostSpecializedTemplate();
8940 }
8941 }
8942 }
8943
8944private:
8945 bool isTargetTypeAFunction() const {
8946 return TargetFunctionType->isFunctionType();
8947 }
8948
8949 // [ToType] [Return]
8950
8951 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8952 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8953 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8954 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8955 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8956 }
8957
8958 // return true if any matching specializations were found
8959 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8960 const DeclAccessPair& CurAccessFunPair) {
8961 if (CXXMethodDecl *Method
8962 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8963 // Skip non-static function templates when converting to pointer, and
8964 // static when converting to member pointer.
8965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8966 return false;
8967 }
8968 else if (TargetTypeIsNonStaticMemberFunction)
8969 return false;
8970
8971 // C++ [over.over]p2:
8972 // If the name is a function template, template argument deduction is
8973 // done (14.8.2.2), and if the argument deduction succeeds, the
8974 // resulting template argument list is used to generate a single
8975 // function template specialization, which is added to the set of
8976 // overloaded functions considered.
8977 FunctionDecl *Specialization = 0;
8978 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8979 if (Sema::TemplateDeductionResult Result
8980 = S.DeduceTemplateArguments(FunctionTemplate,
8981 &OvlExplicitTemplateArgs,
8982 TargetFunctionType, Specialization,
8983 Info)) {
8984 // FIXME: make a note of the failed deduction for diagnostics.
8985 (void)Result;
8986 return false;
8987 }
8988
8989 // Template argument deduction ensures that we have an exact match.
8990 // This function template specicalization works.
8991 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8992 assert(TargetFunctionType
8993 == Context.getCanonicalType(Specialization->getType()));
8994 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8995 return true;
8996 }
8997
8998 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8999 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009000 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009001 // Skip non-static functions when converting to pointer, and static
9002 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009003 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9004 return false;
9005 }
9006 else if (TargetTypeIsNonStaticMemberFunction)
9007 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009008
Chandler Carruthbd647292009-12-29 06:17:27 +00009009 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009010 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009011 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9012 if (S.CheckCUDATarget(Caller, FunDecl))
9013 return false;
9014
Douglas Gregor43c79c22009-12-09 00:47:37 +00009015 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009016 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9017 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009018 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9019 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009020 Matches.push_back(std::make_pair(CurAccessFunPair,
9021 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009022 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009023 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009024 }
Mike Stump1eb44332009-09-09 15:08:12 +00009025 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009026
9027 return false;
9028 }
9029
9030 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9031 bool Ret = false;
9032
9033 // If the overload expression doesn't have the form of a pointer to
9034 // member, don't try to convert it to a pointer-to-member type.
9035 if (IsInvalidFormOfPointerToMemberFunction())
9036 return false;
9037
9038 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9039 E = OvlExpr->decls_end();
9040 I != E; ++I) {
9041 // Look through any using declarations to find the underlying function.
9042 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9043
9044 // C++ [over.over]p3:
9045 // Non-member functions and static member functions match
9046 // targets of type "pointer-to-function" or "reference-to-function."
9047 // Nonstatic member functions match targets of
9048 // type "pointer-to-member-function."
9049 // Note that according to DR 247, the containing class does not matter.
9050 if (FunctionTemplateDecl *FunctionTemplate
9051 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9052 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9053 Ret = true;
9054 }
9055 // If we have explicit template arguments supplied, skip non-templates.
9056 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9057 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9058 Ret = true;
9059 }
9060 assert(Ret || Matches.empty());
9061 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009062 }
9063
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009064 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009065 // [...] and any given function template specialization F1 is
9066 // eliminated if the set contains a second function template
9067 // specialization whose function template is more specialized
9068 // than the function template of F1 according to the partial
9069 // ordering rules of 14.5.5.2.
9070
9071 // The algorithm specified above is quadratic. We instead use a
9072 // two-pass algorithm (similar to the one used to identify the
9073 // best viable function in an overload set) that identifies the
9074 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009075
9076 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9077 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9078 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009079
John McCallc373d482010-01-27 01:50:18 +00009080 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009081 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9082 TPOC_Other, 0, SourceExpr->getLocStart(),
9083 S.PDiag(),
9084 S.PDiag(diag::err_addr_ovl_ambiguous)
9085 << Matches[0].second->getDeclName(),
9086 S.PDiag(diag::note_ovl_candidate)
9087 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009088 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009089
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009090 if (Result != MatchesCopy.end()) {
9091 // Make it the first and only element
9092 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9093 Matches[0].second = cast<FunctionDecl>(*Result);
9094 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009095 }
9096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009097
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009098 void EliminateAllTemplateMatches() {
9099 // [...] any function template specializations in the set are
9100 // eliminated if the set also contains a non-template function, [...]
9101 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9102 if (Matches[I].second->getPrimaryTemplate() == 0)
9103 ++I;
9104 else {
9105 Matches[I] = Matches[--N];
9106 Matches.set_size(N);
9107 }
9108 }
9109 }
9110
9111public:
9112 void ComplainNoMatchesFound() const {
9113 assert(Matches.empty());
9114 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9115 << OvlExpr->getName() << TargetFunctionType
9116 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009117 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009118 }
9119
9120 bool IsInvalidFormOfPointerToMemberFunction() const {
9121 return TargetTypeIsNonStaticMemberFunction &&
9122 !OvlExprInfo.HasFormOfMemberPointer;
9123 }
9124
9125 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9126 // TODO: Should we condition this on whether any functions might
9127 // have matched, or is it more appropriate to do that in callers?
9128 // TODO: a fixit wouldn't hurt.
9129 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9130 << TargetType << OvlExpr->getSourceRange();
9131 }
9132
9133 void ComplainOfInvalidConversion() const {
9134 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9135 << OvlExpr->getName() << TargetType;
9136 }
9137
9138 void ComplainMultipleMatchesFound() const {
9139 assert(Matches.size() > 1);
9140 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9141 << OvlExpr->getName()
9142 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009143 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009145
9146 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9147
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009148 int getNumMatches() const { return Matches.size(); }
9149
9150 FunctionDecl* getMatchingFunctionDecl() const {
9151 if (Matches.size() != 1) return 0;
9152 return Matches[0].second;
9153 }
9154
9155 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9156 if (Matches.size() != 1) return 0;
9157 return &Matches[0].first;
9158 }
9159};
9160
9161/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9162/// an overloaded function (C++ [over.over]), where @p From is an
9163/// expression with overloaded function type and @p ToType is the type
9164/// we're trying to resolve to. For example:
9165///
9166/// @code
9167/// int f(double);
9168/// int f(int);
9169///
9170/// int (*pfd)(double) = f; // selects f(double)
9171/// @endcode
9172///
9173/// This routine returns the resulting FunctionDecl if it could be
9174/// resolved, and NULL otherwise. When @p Complain is true, this
9175/// routine will emit diagnostics if there is an error.
9176FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009177Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9178 QualType TargetType,
9179 bool Complain,
9180 DeclAccessPair &FoundResult,
9181 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009182 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009183
9184 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9185 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009186 int NumMatches = Resolver.getNumMatches();
9187 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009188 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009189 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9190 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9191 else
9192 Resolver.ComplainNoMatchesFound();
9193 }
9194 else if (NumMatches > 1 && Complain)
9195 Resolver.ComplainMultipleMatchesFound();
9196 else if (NumMatches == 1) {
9197 Fn = Resolver.getMatchingFunctionDecl();
9198 assert(Fn);
9199 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009200 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009201 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009202 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009203 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009204
9205 if (pHadMultipleCandidates)
9206 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009207 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009208}
9209
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009210/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009211/// resolve that overloaded function expression down to a single function.
9212///
9213/// This routine can only resolve template-ids that refer to a single function
9214/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009215/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009216/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009217FunctionDecl *
9218Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9219 bool Complain,
9220 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009221 // C++ [over.over]p1:
9222 // [...] [Note: any redundant set of parentheses surrounding the
9223 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009224 // C++ [over.over]p1:
9225 // [...] The overloaded function name can be preceded by the &
9226 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009227
Douglas Gregor4b52e252009-12-21 23:17:24 +00009228 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009229 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009230 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009231
9232 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009233 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009234
Douglas Gregor4b52e252009-12-21 23:17:24 +00009235 // Look through all of the overloaded functions, searching for one
9236 // whose type matches exactly.
9237 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009238 for (UnresolvedSetIterator I = ovl->decls_begin(),
9239 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009240 // C++0x [temp.arg.explicit]p3:
9241 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009242 // where deduction is not done, if a template argument list is
9243 // specified and it, along with any default template arguments,
9244 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009245 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009246 FunctionTemplateDecl *FunctionTemplate
9247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009248
Douglas Gregor4b52e252009-12-21 23:17:24 +00009249 // C++ [over.over]p2:
9250 // If the name is a function template, template argument deduction is
9251 // done (14.8.2.2), and if the argument deduction succeeds, the
9252 // resulting template argument list is used to generate a single
9253 // function template specialization, which is added to the set of
9254 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009255 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009256 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009257 if (TemplateDeductionResult Result
9258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9259 Specialization, Info)) {
9260 // FIXME: make a note of the failed deduction for diagnostics.
9261 (void)Result;
9262 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009263 }
9264
John McCall864c0412011-04-26 20:42:42 +00009265 assert(Specialization && "no specialization and no error?");
9266
Douglas Gregor4b52e252009-12-21 23:17:24 +00009267 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009268 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009269 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009270 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9271 << ovl->getName();
9272 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009273 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009274 return 0;
John McCall864c0412011-04-26 20:42:42 +00009275 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009276
John McCall864c0412011-04-26 20:42:42 +00009277 Matched = Specialization;
9278 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009280
Douglas Gregor4b52e252009-12-21 23:17:24 +00009281 return Matched;
9282}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009283
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009284
9285
9286
John McCall6dbba4f2011-10-11 23:14:30 +00009287// Resolve and fix an overloaded expression that can be resolved
9288// because it identifies a single function template specialization.
9289//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009290// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009291//
9292// Return true if it was logically possible to so resolve the
9293// expression, regardless of whether or not it succeeded. Always
9294// returns true if 'complain' is set.
9295bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9296 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9297 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009298 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009299 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009300 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009301
John McCall6dbba4f2011-10-11 23:14:30 +00009302 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009303
John McCall864c0412011-04-26 20:42:42 +00009304 DeclAccessPair found;
9305 ExprResult SingleFunctionExpression;
9306 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9307 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009308 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009309 SrcExpr = ExprError();
9310 return true;
9311 }
John McCall864c0412011-04-26 20:42:42 +00009312
9313 // It is only correct to resolve to an instance method if we're
9314 // resolving a form that's permitted to be a pointer to member.
9315 // Otherwise we'll end up making a bound member expression, which
9316 // is illegal in all the contexts we resolve like this.
9317 if (!ovl.HasFormOfMemberPointer &&
9318 isa<CXXMethodDecl>(fn) &&
9319 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009320 if (!complain) return false;
9321
9322 Diag(ovl.Expression->getExprLoc(),
9323 diag::err_bound_member_function)
9324 << 0 << ovl.Expression->getSourceRange();
9325
9326 // TODO: I believe we only end up here if there's a mix of
9327 // static and non-static candidates (otherwise the expression
9328 // would have 'bound member' type, not 'overload' type).
9329 // Ideally we would note which candidate was chosen and why
9330 // the static candidates were rejected.
9331 SrcExpr = ExprError();
9332 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009333 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009334
John McCall864c0412011-04-26 20:42:42 +00009335 // Fix the expresion to refer to 'fn'.
9336 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009337 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009338
9339 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009340 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009341 SingleFunctionExpression =
9342 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009343 if (SingleFunctionExpression.isInvalid()) {
9344 SrcExpr = ExprError();
9345 return true;
9346 }
9347 }
John McCall864c0412011-04-26 20:42:42 +00009348 }
9349
9350 if (!SingleFunctionExpression.isUsable()) {
9351 if (complain) {
9352 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9353 << ovl.Expression->getName()
9354 << DestTypeForComplaining
9355 << OpRangeForComplaining
9356 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009357 NoteAllOverloadCandidates(SrcExpr.get());
9358
9359 SrcExpr = ExprError();
9360 return true;
9361 }
9362
9363 return false;
John McCall864c0412011-04-26 20:42:42 +00009364 }
9365
John McCall6dbba4f2011-10-11 23:14:30 +00009366 SrcExpr = SingleFunctionExpression;
9367 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009368}
9369
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009370/// \brief Add a single candidate to the overload set.
9371static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009372 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009373 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009374 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009375 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009376 bool PartialOverloading,
9377 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009378 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009379 if (isa<UsingShadowDecl>(Callee))
9380 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9381
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009382 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009383 if (ExplicitTemplateArgs) {
9384 assert(!KnownValid && "Explicit template arguments?");
9385 return;
9386 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009387 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9388 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009389 return;
John McCallba135432009-11-21 08:51:07 +00009390 }
9391
9392 if (FunctionTemplateDecl *FuncTemplate
9393 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009394 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009395 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009396 return;
9397 }
9398
Richard Smith2ced0442011-06-26 22:19:54 +00009399 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009400}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009401
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009402/// \brief Add the overload candidates named by callee and/or found by argument
9403/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009404void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009405 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009406 OverloadCandidateSet &CandidateSet,
9407 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009408
9409#ifndef NDEBUG
9410 // Verify that ArgumentDependentLookup is consistent with the rules
9411 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009412 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009413 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9414 // and let Y be the lookup set produced by argument dependent
9415 // lookup (defined as follows). If X contains
9416 //
9417 // -- a declaration of a class member, or
9418 //
9419 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009420 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009421 //
9422 // -- a declaration that is neither a function or a function
9423 // template
9424 //
9425 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009426
John McCall3b4294e2009-12-16 12:17:52 +00009427 if (ULE->requiresADL()) {
9428 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9429 E = ULE->decls_end(); I != E; ++I) {
9430 assert(!(*I)->getDeclContext()->isRecord());
9431 assert(isa<UsingShadowDecl>(*I) ||
9432 !(*I)->getDeclContext()->isFunctionOrMethod());
9433 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009434 }
9435 }
9436#endif
9437
John McCall3b4294e2009-12-16 12:17:52 +00009438 // It would be nice to avoid this copy.
9439 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009440 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009441 if (ULE->hasExplicitTemplateArgs()) {
9442 ULE->copyTemplateArgumentsInto(TABuffer);
9443 ExplicitTemplateArgs = &TABuffer;
9444 }
9445
9446 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9447 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009448 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9449 CandidateSet, PartialOverloading,
9450 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009451
John McCall3b4294e2009-12-16 12:17:52 +00009452 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009453 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009454 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009455 Args, ExplicitTemplateArgs,
9456 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009457 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009458}
John McCall578b69b2009-12-16 08:11:27 +00009459
Richard Smithf50e88a2011-06-05 22:42:48 +00009460/// Attempt to recover from an ill-formed use of a non-dependent name in a
9461/// template, where the non-dependent name was declared after the template
9462/// was defined. This is common in code written for a compilers which do not
9463/// correctly implement two-stage name lookup.
9464///
9465/// Returns true if a viable candidate was found and a diagnostic was issued.
9466static bool
9467DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9468 const CXXScopeSpec &SS, LookupResult &R,
9469 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009470 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009471 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9472 return false;
9473
9474 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009475 if (DC->isTransparentContext())
9476 continue;
9477
Richard Smithf50e88a2011-06-05 22:42:48 +00009478 SemaRef.LookupQualifiedName(R, DC);
9479
9480 if (!R.empty()) {
9481 R.suppressDiagnostics();
9482
9483 if (isa<CXXRecordDecl>(DC)) {
9484 // Don't diagnose names we find in classes; we get much better
9485 // diagnostics for these from DiagnoseEmptyLookup.
9486 R.clear();
9487 return false;
9488 }
9489
9490 OverloadCandidateSet Candidates(FnLoc);
9491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9492 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009493 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009494 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009495
9496 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009497 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009498 // No viable functions. Don't bother the user with notes for functions
9499 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009500 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009501 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009502 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009503
9504 // Find the namespaces where ADL would have looked, and suggest
9505 // declaring the function there instead.
9506 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9507 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009508 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009509 AssociatedNamespaces,
9510 AssociatedClasses);
9511 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009512 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009513 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009514 for (Sema::AssociatedNamespaceSet::iterator
9515 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009516 end = AssociatedNamespaces.end(); it != end; ++it) {
9517 if (!Std->Encloses(*it))
9518 SuggestedNamespaces.insert(*it);
9519 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009520 } else {
9521 // Lacking the 'std::' namespace, use all of the associated namespaces.
9522 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009523 }
9524
9525 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9526 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009527 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009528 SemaRef.Diag(Best->Function->getLocation(),
9529 diag::note_not_found_by_two_phase_lookup)
9530 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009531 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009532 SemaRef.Diag(Best->Function->getLocation(),
9533 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009534 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009535 } else {
9536 // FIXME: It would be useful to list the associated namespaces here,
9537 // but the diagnostics infrastructure doesn't provide a way to produce
9538 // a localized representation of a list of items.
9539 SemaRef.Diag(Best->Function->getLocation(),
9540 diag::note_not_found_by_two_phase_lookup)
9541 << R.getLookupName() << 2;
9542 }
9543
9544 // Try to recover by calling this function.
9545 return true;
9546 }
9547
9548 R.clear();
9549 }
9550
9551 return false;
9552}
9553
9554/// Attempt to recover from ill-formed use of a non-dependent operator in a
9555/// template, where the non-dependent operator was declared after the template
9556/// was defined.
9557///
9558/// Returns true if a viable candidate was found and a diagnostic was issued.
9559static bool
9560DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9561 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009562 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009563 DeclarationName OpName =
9564 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9565 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9566 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009567 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009568}
9569
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009570namespace {
9571// Callback to limit the allowed keywords and to only accept typo corrections
9572// that are keywords or whose decls refer to functions (or template functions)
9573// that accept the given number of arguments.
9574class RecoveryCallCCC : public CorrectionCandidateCallback {
9575 public:
9576 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9577 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009578 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009579 WantRemainingKeywords = false;
9580 }
9581
9582 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9583 if (!candidate.getCorrectionDecl())
9584 return candidate.isKeyword();
9585
9586 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9587 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9588 FunctionDecl *FD = 0;
9589 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9590 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9591 FD = FTD->getTemplatedDecl();
9592 if (!HasExplicitTemplateArgs && !FD) {
9593 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9594 // If the Decl is neither a function nor a template function,
9595 // determine if it is a pointer or reference to a function. If so,
9596 // check against the number of arguments expected for the pointee.
9597 QualType ValType = cast<ValueDecl>(ND)->getType();
9598 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9599 ValType = ValType->getPointeeType();
9600 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9601 if (FPT->getNumArgs() == NumArgs)
9602 return true;
9603 }
9604 }
9605 if (FD && FD->getNumParams() >= NumArgs &&
9606 FD->getMinRequiredArguments() <= NumArgs)
9607 return true;
9608 }
9609 return false;
9610 }
9611
9612 private:
9613 unsigned NumArgs;
9614 bool HasExplicitTemplateArgs;
9615};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009616
9617// Callback that effectively disabled typo correction
9618class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9619 public:
9620 NoTypoCorrectionCCC() {
9621 WantTypeSpecifiers = false;
9622 WantExpressionKeywords = false;
9623 WantCXXNamedCasts = false;
9624 WantRemainingKeywords = false;
9625 }
9626
9627 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9628 return false;
9629 }
9630};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009631}
9632
John McCall578b69b2009-12-16 08:11:27 +00009633/// Attempts to recover from a call where no functions were found.
9634///
9635/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009636static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009637BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009638 UnresolvedLookupExpr *ULE,
9639 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009640 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009641 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009642 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009643
9644 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009645 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009646 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009647
John McCall3b4294e2009-12-16 12:17:52 +00009648 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009649 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009650 if (ULE->hasExplicitTemplateArgs()) {
9651 ULE->copyTemplateArgumentsInto(TABuffer);
9652 ExplicitTemplateArgs = &TABuffer;
9653 }
9654
John McCall578b69b2009-12-16 08:11:27 +00009655 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9656 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009657 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009658 NoTypoCorrectionCCC RejectAll;
9659 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9660 (CorrectionCandidateCallback*)&Validator :
9661 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009662 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009663 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009664 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009665 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009666 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009667 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009668
John McCall3b4294e2009-12-16 12:17:52 +00009669 assert(!R.empty() && "lookup results empty despite recovery");
9670
9671 // Build an implicit member call if appropriate. Just drop the
9672 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009673 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009674 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009675 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9676 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009677 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009678 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009679 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009680 else
9681 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9682
9683 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009684 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009685
9686 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009687 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009688 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009689 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009690 MultiExprArg(Args.data(), Args.size()),
9691 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009692}
Douglas Gregord7a95972010-06-08 17:35:15 +00009693
Douglas Gregorf6b89692008-11-26 05:54:23 +00009694/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009695/// (which eventually refers to the declaration Func) and the call
9696/// arguments Args/NumArgs, attempt to resolve the function call down
9697/// to a specific function. If overload resolution succeeds, returns
9698/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009699/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009700/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009701ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009702Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009703 SourceLocation LParenLoc,
9704 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009705 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009706 Expr *ExecConfig,
9707 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009708#ifndef NDEBUG
9709 if (ULE->requiresADL()) {
9710 // To do ADL, we must have found an unqualified name.
9711 assert(!ULE->getQualifier() && "qualified name with ADL");
9712
9713 // We don't perform ADL for implicit declarations of builtins.
9714 // Verify that this was correctly set up.
9715 FunctionDecl *F;
9716 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9717 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9718 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009719 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009720
John McCall3b4294e2009-12-16 12:17:52 +00009721 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009722 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009723 } else
9724 assert(!ULE->isStdAssociatedNamespace() &&
9725 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009726#endif
9727
John McCall5acb0c92011-10-17 18:40:02 +00009728 UnbridgedCastsSet UnbridgedCasts;
9729 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9730 return ExprError();
9731
John McCall5769d612010-02-08 23:07:23 +00009732 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009733
John McCall3b4294e2009-12-16 12:17:52 +00009734 // Add the functions denoted by the callee to the set of candidate
9735 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009736 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9737 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009738
9739 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009740 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9741 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009742 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009743 // In Microsoft mode, if we are inside a template class member function then
9744 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009745 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009746 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009747 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009748 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009749 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9750 Context.DependentTy, VK_RValue,
9751 RParenLoc);
9752 CE->setTypeDependent(true);
9753 return Owned(CE);
9754 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009755 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9756 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009757 RParenLoc, /*EmptyLookup=*/true,
9758 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009759 }
John McCall578b69b2009-12-16 08:11:27 +00009760
John McCall5acb0c92011-10-17 18:40:02 +00009761 UnbridgedCasts.restore();
9762
Douglas Gregorf6b89692008-11-26 05:54:23 +00009763 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009764 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009765 case OR_Success: {
9766 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009767 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009768 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009769 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009770 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009771 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9772 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009773 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009774
Richard Smithf50e88a2011-06-05 22:42:48 +00009775 case OR_No_Viable_Function: {
9776 // Try to recover by looking for viable functions which the user might
9777 // have meant to call.
9778 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009779 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9780 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009781 /*EmptyLookup=*/false,
9782 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009783 if (!Recovery.isInvalid())
9784 return Recovery;
9785
Daniel Dunbar96a00142012-03-09 18:35:03 +00009786 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009787 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009788 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009789 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9790 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009791 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009792 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009793
9794 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009795 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009796 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009797 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9798 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009799 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009800
9801 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009802 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009803 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009804 << Best->Function->isDeleted()
9805 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009806 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009807 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9809 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009810
9811 // We emitted an error for the unvailable/deleted function call but keep
9812 // the call in the AST.
9813 FunctionDecl *FDecl = Best->Function;
9814 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9815 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9816 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009817 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009818 }
9819
Douglas Gregorff331c12010-07-25 18:17:45 +00009820 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009821 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009822}
9823
John McCall6e266892010-01-26 03:27:55 +00009824static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009825 return Functions.size() > 1 ||
9826 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9827}
9828
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009829/// \brief Create a unary operation that may resolve to an overloaded
9830/// operator.
9831///
9832/// \param OpLoc The location of the operator itself (e.g., '*').
9833///
9834/// \param OpcIn The UnaryOperator::Opcode that describes this
9835/// operator.
9836///
9837/// \param Functions The set of non-member functions that will be
9838/// considered by overload resolution. The caller needs to build this
9839/// set based on the context using, e.g.,
9840/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9841/// set should not contain any member functions; those will be added
9842/// by CreateOverloadedUnaryOp().
9843///
9844/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009845ExprResult
John McCall6e266892010-01-26 03:27:55 +00009846Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9847 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009848 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009849 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009850
9851 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9852 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9853 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009854 // TODO: provide better source location info.
9855 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009856
John McCall5acb0c92011-10-17 18:40:02 +00009857 if (checkPlaceholderForOverload(*this, Input))
9858 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009859
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009860 Expr *Args[2] = { Input, 0 };
9861 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009862
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009863 // For post-increment and post-decrement, add the implicit '0' as
9864 // the second argument, so that we know this is a post-increment or
9865 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009866 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009867 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009868 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9869 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009870 NumArgs = 2;
9871 }
9872
9873 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009874 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009875 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009876 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009877 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009878 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009879 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009880
John McCallc373d482010-01-27 01:50:18 +00009881 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009882 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009883 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009884 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009885 /*ADL*/ true, IsOverloaded(Fns),
9886 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009887 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009888 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009889 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009890 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009891 OpLoc));
9892 }
9893
9894 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009895 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009896
9897 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009898 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9899 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009900
9901 // Add operator candidates that are member functions.
9902 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9903
John McCall6e266892010-01-26 03:27:55 +00009904 // Add candidates from ADL.
9905 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009906 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009907 /*ExplicitTemplateArgs*/ 0,
9908 CandidateSet);
9909
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009910 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009911 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009912
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009913 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9914
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009915 // Perform overload resolution.
9916 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009917 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009918 case OR_Success: {
9919 // We found a built-in operator or an overloaded operator.
9920 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009921
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009922 if (FnDecl) {
9923 // We matched an overloaded operator. Build a call to that
9924 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009925
Eli Friedman5f2987c2012-02-02 03:46:19 +00009926 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009927
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009928 // Convert the arguments.
9929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009930 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009931
John Wiegley429bb272011-04-08 18:41:53 +00009932 ExprResult InputRes =
9933 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9934 Best->FoundDecl, Method);
9935 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009936 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009937 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009938 } else {
9939 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009940 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009941 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009942 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009943 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009944 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009945 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009946 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009947 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009948 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009949 }
9950
John McCallb697e082010-05-06 18:15:07 +00009951 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9952
John McCallf89e55a2010-11-18 06:31:45 +00009953 // Determine the result type.
9954 QualType ResultTy = FnDecl->getResultType();
9955 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9956 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009957
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009958 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009959 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009960 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009961 if (FnExpr.isInvalid())
9962 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009963
Eli Friedman4c3b8962009-11-18 03:58:17 +00009964 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009965 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009966 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009967 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009968
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009969 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009970 FnDecl))
9971 return ExprError();
9972
John McCall9ae2f072010-08-23 23:25:46 +00009973 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009974 } else {
9975 // We matched a built-in operator. Convert the arguments, then
9976 // break out so that we will build the appropriate built-in
9977 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009978 ExprResult InputRes =
9979 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9980 Best->Conversions[0], AA_Passing);
9981 if (InputRes.isInvalid())
9982 return ExprError();
9983 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009984 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009985 }
John Wiegley429bb272011-04-08 18:41:53 +00009986 }
9987
9988 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009989 // This is an erroneous use of an operator which can be overloaded by
9990 // a non-member function. Check for non-member operators which were
9991 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009992 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9993 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009994 // FIXME: Recover by calling the found function.
9995 return ExprError();
9996
John Wiegley429bb272011-04-08 18:41:53 +00009997 // No viable function; fall through to handling this as a
9998 // built-in operator, which will produce an error message for us.
9999 break;
10000
10001 case OR_Ambiguous:
10002 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10003 << UnaryOperator::getOpcodeStr(Opc)
10004 << Input->getType()
10005 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010006 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10007 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010008 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10009 return ExprError();
10010
10011 case OR_Deleted:
10012 Diag(OpLoc, diag::err_ovl_deleted_oper)
10013 << Best->Function->isDeleted()
10014 << UnaryOperator::getOpcodeStr(Opc)
10015 << getDeletedOrUnavailableSuffix(Best->Function)
10016 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10018 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010019 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010020 return ExprError();
10021 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010022
10023 // Either we found no viable overloaded operator or we matched a
10024 // built-in operator. In either case, fall through to trying to
10025 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010026 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010027}
10028
Douglas Gregor063daf62009-03-13 18:40:31 +000010029/// \brief Create a binary operation that may resolve to an overloaded
10030/// operator.
10031///
10032/// \param OpLoc The location of the operator itself (e.g., '+').
10033///
10034/// \param OpcIn The BinaryOperator::Opcode that describes this
10035/// operator.
10036///
10037/// \param Functions The set of non-member functions that will be
10038/// considered by overload resolution. The caller needs to build this
10039/// set based on the context using, e.g.,
10040/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10041/// set should not contain any member functions; those will be added
10042/// by CreateOverloadedBinOp().
10043///
10044/// \param LHS Left-hand argument.
10045/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010046ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010047Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010048 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010049 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010050 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010051 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010052 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010053
10054 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10055 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10056 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10057
10058 // If either side is type-dependent, create an appropriate dependent
10059 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010060 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010061 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010062 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010063 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010064 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010065 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010066 Context.DependentTy,
10067 VK_RValue, OK_Ordinary,
10068 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010069
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010070 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10071 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010072 VK_LValue,
10073 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010074 Context.DependentTy,
10075 Context.DependentTy,
10076 OpLoc));
10077 }
John McCall6e266892010-01-26 03:27:55 +000010078
10079 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010080 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010081 // TODO: provide better source location info in DNLoc component.
10082 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010083 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010084 = UnresolvedLookupExpr::Create(Context, NamingClass,
10085 NestedNameSpecifierLoc(), OpNameInfo,
10086 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010087 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +000010088 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +000010089 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +000010090 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010091 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +000010092 OpLoc));
10093 }
10094
John McCall5acb0c92011-10-17 18:40:02 +000010095 // Always do placeholder-like conversions on the RHS.
10096 if (checkPlaceholderForOverload(*this, Args[1]))
10097 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010098
John McCall3c3b7f92011-10-25 17:37:35 +000010099 // Do placeholder-like conversion on the LHS; note that we should
10100 // not get here with a PseudoObject LHS.
10101 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010102 if (checkPlaceholderForOverload(*this, Args[0]))
10103 return ExprError();
10104
Sebastian Redl275c2b42009-11-18 23:10:33 +000010105 // If this is the assignment operator, we only perform overload resolution
10106 // if the left-hand side is a class or enumeration type. This is actually
10107 // a hack. The standard requires that we do overload resolution between the
10108 // various built-in candidates, but as DR507 points out, this can lead to
10109 // problems. So we do it this way, which pretty much follows what GCC does.
10110 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010111 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010113
John McCall0e800c92010-12-04 08:14:53 +000010114 // If this is the .* operator, which is not overloadable, just
10115 // create a built-in binary operator.
10116 if (Opc == BO_PtrMemD)
10117 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10118
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010119 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010120 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010121
10122 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010123 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010124
10125 // Add operator candidates that are member functions.
10126 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10127
John McCall6e266892010-01-26 03:27:55 +000010128 // Add candidates from ADL.
10129 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010130 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010131 /*ExplicitTemplateArgs*/ 0,
10132 CandidateSet);
10133
Douglas Gregor063daf62009-03-13 18:40:31 +000010134 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010135 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010136
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10138
Douglas Gregor063daf62009-03-13 18:40:31 +000010139 // Perform overload resolution.
10140 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010141 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010142 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010143 // We found a built-in operator or an overloaded operator.
10144 FunctionDecl *FnDecl = Best->Function;
10145
10146 if (FnDecl) {
10147 // We matched an overloaded operator. Build a call to that
10148 // operator.
10149
Eli Friedman5f2987c2012-02-02 03:46:19 +000010150 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010151
Douglas Gregor063daf62009-03-13 18:40:31 +000010152 // Convert the arguments.
10153 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010154 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010155 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010156
Chandler Carruth6df868e2010-12-12 08:17:55 +000010157 ExprResult Arg1 =
10158 PerformCopyInitialization(
10159 InitializedEntity::InitializeParameter(Context,
10160 FnDecl->getParamDecl(0)),
10161 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010162 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010163 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010164
John Wiegley429bb272011-04-08 18:41:53 +000010165 ExprResult Arg0 =
10166 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10167 Best->FoundDecl, Method);
10168 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010169 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010170 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010171 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010172 } else {
10173 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010174 ExprResult Arg0 = PerformCopyInitialization(
10175 InitializedEntity::InitializeParameter(Context,
10176 FnDecl->getParamDecl(0)),
10177 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010178 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010179 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010180
Chandler Carruth6df868e2010-12-12 08:17:55 +000010181 ExprResult Arg1 =
10182 PerformCopyInitialization(
10183 InitializedEntity::InitializeParameter(Context,
10184 FnDecl->getParamDecl(1)),
10185 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010186 if (Arg1.isInvalid())
10187 return ExprError();
10188 Args[0] = LHS = Arg0.takeAs<Expr>();
10189 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010190 }
10191
John McCallb697e082010-05-06 18:15:07 +000010192 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10193
John McCallf89e55a2010-11-18 06:31:45 +000010194 // Determine the result type.
10195 QualType ResultTy = FnDecl->getResultType();
10196 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10197 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010198
10199 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010200 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10201 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010202 if (FnExpr.isInvalid())
10203 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010204
John McCall9ae2f072010-08-23 23:25:46 +000010205 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010206 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010207 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010208
10209 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010210 FnDecl))
10211 return ExprError();
10212
John McCall9ae2f072010-08-23 23:25:46 +000010213 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010214 } else {
10215 // We matched a built-in operator. Convert the arguments, then
10216 // break out so that we will build the appropriate built-in
10217 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010218 ExprResult ArgsRes0 =
10219 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10220 Best->Conversions[0], AA_Passing);
10221 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010222 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010223 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010224
John Wiegley429bb272011-04-08 18:41:53 +000010225 ExprResult ArgsRes1 =
10226 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10227 Best->Conversions[1], AA_Passing);
10228 if (ArgsRes1.isInvalid())
10229 return ExprError();
10230 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010231 break;
10232 }
10233 }
10234
Douglas Gregor33074752009-09-30 21:46:01 +000010235 case OR_No_Viable_Function: {
10236 // C++ [over.match.oper]p9:
10237 // If the operator is the operator , [...] and there are no
10238 // viable functions, then the operator is assumed to be the
10239 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010240 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010241 break;
10242
Chandler Carruth6df868e2010-12-12 08:17:55 +000010243 // For class as left operand for assignment or compound assigment
10244 // operator do not fall through to handling in built-in, but report that
10245 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010246 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010247 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010248 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010249 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10250 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010251 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010252 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010253 // This is an erroneous use of an operator which can be overloaded by
10254 // a non-member function. Check for non-member operators which were
10255 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010256 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010257 // FIXME: Recover by calling the found function.
10258 return ExprError();
10259
Douglas Gregor33074752009-09-30 21:46:01 +000010260 // No viable function; try to create a built-in operation, which will
10261 // produce an error. Then, show the non-viable candidates.
10262 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010263 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010264 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010265 "C++ binary operator overloading is missing candidates!");
10266 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010267 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010268 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010269 return move(Result);
10270 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010271
10272 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010273 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010274 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010275 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010276 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010277 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010278 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010279 return ExprError();
10280
10281 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010282 if (isImplicitlyDeleted(Best->Function)) {
10283 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10284 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10285 << getSpecialMember(Method)
10286 << BinaryOperator::getOpcodeStr(Opc)
10287 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010288
10289 if (getSpecialMember(Method) != CXXInvalid) {
10290 // The user probably meant to call this special member. Just
10291 // explain why it's deleted.
10292 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010293 return ExprError();
10294 }
10295 } else {
10296 Diag(OpLoc, diag::err_ovl_deleted_oper)
10297 << Best->Function->isDeleted()
10298 << BinaryOperator::getOpcodeStr(Opc)
10299 << getDeletedOrUnavailableSuffix(Best->Function)
10300 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10301 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010302 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010303 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010304 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010305 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010306
Douglas Gregor33074752009-09-30 21:46:01 +000010307 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010309}
10310
John McCall60d7b3a2010-08-24 06:29:42 +000010311ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010312Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10313 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010314 Expr *Base, Expr *Idx) {
10315 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010316 DeclarationName OpName =
10317 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10318
10319 // If either side is type-dependent, create an appropriate dependent
10320 // expression.
10321 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10322
John McCallc373d482010-01-27 01:50:18 +000010323 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010324 // CHECKME: no 'operator' keyword?
10325 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10326 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010327 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010328 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010329 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010330 /*ADL*/ true, /*Overloaded*/ false,
10331 UnresolvedSetIterator(),
10332 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010333 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010334
Sebastian Redlf322ed62009-10-29 20:17:01 +000010335 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10336 Args, 2,
10337 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010338 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010339 RLoc));
10340 }
10341
John McCall5acb0c92011-10-17 18:40:02 +000010342 // Handle placeholders on both operands.
10343 if (checkPlaceholderForOverload(*this, Args[0]))
10344 return ExprError();
10345 if (checkPlaceholderForOverload(*this, Args[1]))
10346 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010347
Sebastian Redlf322ed62009-10-29 20:17:01 +000010348 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010349 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010350
10351 // Subscript can only be overloaded as a member function.
10352
10353 // Add operator candidates that are member functions.
10354 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10355
10356 // Add builtin operator candidates.
10357 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10358
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010359 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10360
Sebastian Redlf322ed62009-10-29 20:17:01 +000010361 // Perform overload resolution.
10362 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010363 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010364 case OR_Success: {
10365 // We found a built-in operator or an overloaded operator.
10366 FunctionDecl *FnDecl = Best->Function;
10367
10368 if (FnDecl) {
10369 // We matched an overloaded operator. Build a call to that
10370 // operator.
10371
Eli Friedman5f2987c2012-02-02 03:46:19 +000010372 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010373
John McCall9aa472c2010-03-19 07:35:19 +000010374 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010375 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010376
Sebastian Redlf322ed62009-10-29 20:17:01 +000010377 // Convert the arguments.
10378 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010379 ExprResult Arg0 =
10380 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10381 Best->FoundDecl, Method);
10382 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010383 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010384 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010385
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010386 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010387 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010388 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010389 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010390 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010391 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010392 Owned(Args[1]));
10393 if (InputInit.isInvalid())
10394 return ExprError();
10395
10396 Args[1] = InputInit.takeAs<Expr>();
10397
Sebastian Redlf322ed62009-10-29 20:17:01 +000010398 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010399 QualType ResultTy = FnDecl->getResultType();
10400 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10401 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010402
10403 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010404 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10405 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010406 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10407 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010408 OpLocInfo.getLoc(),
10409 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010410 if (FnExpr.isInvalid())
10411 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010412
John McCall9ae2f072010-08-23 23:25:46 +000010413 CXXOperatorCallExpr *TheCall =
10414 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010415 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010416 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010417
John McCall9ae2f072010-08-23 23:25:46 +000010418 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010419 FnDecl))
10420 return ExprError();
10421
John McCall9ae2f072010-08-23 23:25:46 +000010422 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010423 } else {
10424 // We matched a built-in operator. Convert the arguments, then
10425 // break out so that we will build the appropriate built-in
10426 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010427 ExprResult ArgsRes0 =
10428 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10429 Best->Conversions[0], AA_Passing);
10430 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010431 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010432 Args[0] = ArgsRes0.take();
10433
10434 ExprResult ArgsRes1 =
10435 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10436 Best->Conversions[1], AA_Passing);
10437 if (ArgsRes1.isInvalid())
10438 return ExprError();
10439 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010440
10441 break;
10442 }
10443 }
10444
10445 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010446 if (CandidateSet.empty())
10447 Diag(LLoc, diag::err_ovl_no_oper)
10448 << Args[0]->getType() << /*subscript*/ 0
10449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10450 else
10451 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10452 << Args[0]->getType()
10453 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010455 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010456 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010457 }
10458
10459 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010460 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010461 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010462 << Args[0]->getType() << Args[1]->getType()
10463 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010464 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010465 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010466 return ExprError();
10467
10468 case OR_Deleted:
10469 Diag(LLoc, diag::err_ovl_deleted_oper)
10470 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010471 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010472 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010474 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010475 return ExprError();
10476 }
10477
10478 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010479 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010480}
10481
Douglas Gregor88a35142008-12-22 05:46:06 +000010482/// BuildCallToMemberFunction - Build a call to a member
10483/// function. MemExpr is the expression that refers to the member
10484/// function (and includes the object parameter), Args/NumArgs are the
10485/// arguments to the function call (not including the object
10486/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010487/// expression refers to a non-static member function or an overloaded
10488/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010489ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010490Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10491 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010492 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010493 assert(MemExprE->getType() == Context.BoundMemberTy ||
10494 MemExprE->getType() == Context.OverloadTy);
10495
Douglas Gregor88a35142008-12-22 05:46:06 +000010496 // Dig out the member expression. This holds both the object
10497 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010498 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010499
John McCall864c0412011-04-26 20:42:42 +000010500 // Determine whether this is a call to a pointer-to-member function.
10501 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10502 assert(op->getType() == Context.BoundMemberTy);
10503 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10504
10505 QualType fnType =
10506 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10507
10508 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10509 QualType resultType = proto->getCallResultType(Context);
10510 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10511
10512 // Check that the object type isn't more qualified than the
10513 // member function we're calling.
10514 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10515
10516 QualType objectType = op->getLHS()->getType();
10517 if (op->getOpcode() == BO_PtrMemI)
10518 objectType = objectType->castAs<PointerType>()->getPointeeType();
10519 Qualifiers objectQuals = objectType.getQualifiers();
10520
10521 Qualifiers difference = objectQuals - funcQuals;
10522 difference.removeObjCGCAttr();
10523 difference.removeAddressSpace();
10524 if (difference) {
10525 std::string qualsString = difference.getAsString();
10526 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10527 << fnType.getUnqualifiedType()
10528 << qualsString
10529 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10530 }
10531
10532 CXXMemberCallExpr *call
10533 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10534 resultType, valueKind, RParenLoc);
10535
10536 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010537 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010538 call, 0))
10539 return ExprError();
10540
10541 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10542 return ExprError();
10543
10544 return MaybeBindToTemporary(call);
10545 }
10546
John McCall5acb0c92011-10-17 18:40:02 +000010547 UnbridgedCastsSet UnbridgedCasts;
10548 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10549 return ExprError();
10550
John McCall129e2df2009-11-30 22:42:35 +000010551 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010552 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010553 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010554 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010555 if (isa<MemberExpr>(NakedMemExpr)) {
10556 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010557 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010558 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010559 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010560 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010561 } else {
10562 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010563 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010564
John McCall701c89e2009-12-03 04:06:58 +000010565 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010566 Expr::Classification ObjectClassification
10567 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10568 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010569
Douglas Gregor88a35142008-12-22 05:46:06 +000010570 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010571 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010572
John McCallaa81e162009-12-01 22:10:20 +000010573 // FIXME: avoid copy.
10574 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10575 if (UnresExpr->hasExplicitTemplateArgs()) {
10576 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10577 TemplateArgs = &TemplateArgsBuffer;
10578 }
10579
John McCall129e2df2009-11-30 22:42:35 +000010580 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10581 E = UnresExpr->decls_end(); I != E; ++I) {
10582
John McCall701c89e2009-12-03 04:06:58 +000010583 NamedDecl *Func = *I;
10584 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10585 if (isa<UsingShadowDecl>(Func))
10586 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10587
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010588
Francois Pichetdbee3412011-01-18 05:04:39 +000010589 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010590 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010591 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10592 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010593 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010594 // If explicit template arguments were provided, we can't call a
10595 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010596 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010597 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010598
John McCall9aa472c2010-03-19 07:35:19 +000010599 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010600 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010601 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010602 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010603 } else {
John McCall129e2df2009-11-30 22:42:35 +000010604 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010605 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010606 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010607 llvm::makeArrayRef(Args, NumArgs),
10608 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010609 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010610 }
Douglas Gregordec06662009-08-21 18:42:58 +000010611 }
Mike Stump1eb44332009-09-09 15:08:12 +000010612
John McCall129e2df2009-11-30 22:42:35 +000010613 DeclarationName DeclName = UnresExpr->getMemberName();
10614
John McCall5acb0c92011-10-17 18:40:02 +000010615 UnbridgedCasts.restore();
10616
Douglas Gregor88a35142008-12-22 05:46:06 +000010617 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010618 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010619 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010620 case OR_Success:
10621 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010622 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010623 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010624 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010625 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010626 break;
10627
10628 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010629 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010630 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010631 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10633 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010634 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010635 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010636
10637 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010638 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010639 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10641 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010642 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010643 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010644
10645 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010646 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010647 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010648 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010649 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010650 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10652 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010653 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010654 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010655 }
10656
John McCall6bb80172010-03-30 21:47:33 +000010657 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010658
John McCallaa81e162009-12-01 22:10:20 +000010659 // If overload resolution picked a static member, build a
10660 // non-member call based on that function.
10661 if (Method->isStatic()) {
10662 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10663 Args, NumArgs, RParenLoc);
10664 }
10665
John McCall129e2df2009-11-30 22:42:35 +000010666 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010667 }
10668
John McCallf89e55a2010-11-18 06:31:45 +000010669 QualType ResultType = Method->getResultType();
10670 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10671 ResultType = ResultType.getNonLValueExprType(Context);
10672
Douglas Gregor88a35142008-12-22 05:46:06 +000010673 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010674 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010675 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010676 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010677
Anders Carlssoneed3e692009-10-10 00:06:20 +000010678 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010679 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010680 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010681 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010682
Douglas Gregor88a35142008-12-22 05:46:06 +000010683 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010684 // We only need to do this if there was actually an overload; otherwise
10685 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010686 if (!Method->isStatic()) {
10687 ExprResult ObjectArg =
10688 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10689 FoundDecl, Method);
10690 if (ObjectArg.isInvalid())
10691 return ExprError();
10692 MemExpr->setBase(ObjectArg.take());
10693 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010694
10695 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010696 const FunctionProtoType *Proto =
10697 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010698 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010699 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010700 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010701
Eli Friedmane61eb042012-02-18 04:48:30 +000010702 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10703
John McCall9ae2f072010-08-23 23:25:46 +000010704 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010705 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010706
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010707 if ((isa<CXXConstructorDecl>(CurContext) ||
10708 isa<CXXDestructorDecl>(CurContext)) &&
10709 TheCall->getMethodDecl()->isPure()) {
10710 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10711
Chandler Carruthae198062011-06-27 08:31:58 +000010712 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010713 Diag(MemExpr->getLocStart(),
10714 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10715 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10716 << MD->getParent()->getDeclName();
10717
10718 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010719 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010720 }
John McCall9ae2f072010-08-23 23:25:46 +000010721 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010722}
10723
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010724/// BuildCallToObjectOfClassType - Build a call to an object of class
10725/// type (C++ [over.call.object]), which can end up invoking an
10726/// overloaded function call operator (@c operator()) or performing a
10727/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010728ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010729Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010730 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010731 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010732 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010733 if (checkPlaceholderForOverload(*this, Obj))
10734 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010735 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010736
10737 UnbridgedCastsSet UnbridgedCasts;
10738 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10739 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010740
John Wiegley429bb272011-04-08 18:41:53 +000010741 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10742 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010743
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010744 // C++ [over.call.object]p1:
10745 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010746 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010747 // candidate functions includes at least the function call
10748 // operators of T. The function call operators of T are obtained by
10749 // ordinary lookup of the name operator() in the context of
10750 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010751 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010752 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010753
John Wiegley429bb272011-04-08 18:41:53 +000010754 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010755 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010756 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010757
John McCalla24dc2e2009-11-17 02:14:36 +000010758 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10759 LookupQualifiedName(R, Record->getDecl());
10760 R.suppressDiagnostics();
10761
Douglas Gregor593564b2009-11-15 07:48:03 +000010762 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010763 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010764 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10765 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010766 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010768
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010769 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010770 // In addition, for each (non-explicit in C++0x) conversion function
10771 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010772 //
10773 // operator conversion-type-id () cv-qualifier;
10774 //
10775 // where cv-qualifier is the same cv-qualification as, or a
10776 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010777 // denotes the type "pointer to function of (P1,...,Pn) returning
10778 // R", or the type "reference to pointer to function of
10779 // (P1,...,Pn) returning R", or the type "reference to function
10780 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010781 // is also considered as a candidate function. Similarly,
10782 // surrogate call functions are added to the set of candidate
10783 // functions for each conversion function declared in an
10784 // accessible base class provided the function is not hidden
10785 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010786 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010787 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010788 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010789 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010790 NamedDecl *D = *I;
10791 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10792 if (isa<UsingShadowDecl>(D))
10793 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010794
Douglas Gregor4a27d702009-10-21 06:18:39 +000010795 // Skip over templated conversion functions; they aren't
10796 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010797 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010798 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010799
John McCall701c89e2009-12-03 04:06:58 +000010800 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010801 if (!Conv->isExplicit()) {
10802 // Strip the reference type (if any) and then the pointer type (if
10803 // any) to get down to what might be a function type.
10804 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10805 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10806 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010807
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010808 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10809 {
10810 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010811 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10812 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010813 }
10814 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010815 }
Mike Stump1eb44332009-09-09 15:08:12 +000010816
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010817 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10818
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010819 // Perform overload resolution.
10820 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010821 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010822 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010823 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010824 // Overload resolution succeeded; we'll build the appropriate call
10825 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010826 break;
10827
10828 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010829 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010830 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010831 << Object.get()->getType() << /*call*/ 1
10832 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010833 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010834 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010835 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010836 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010837 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10838 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010839 break;
10840
10841 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010842 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010843 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010844 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010845 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10846 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010847 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010848
10849 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010850 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010851 diag::err_ovl_deleted_object_call)
10852 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010853 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010854 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010855 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10857 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010858 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010859 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010860
Douglas Gregorff331c12010-07-25 18:17:45 +000010861 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010862 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010863
John McCall5acb0c92011-10-17 18:40:02 +000010864 UnbridgedCasts.restore();
10865
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010866 if (Best->Function == 0) {
10867 // Since there is no function declaration, this is one of the
10868 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010869 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010870 = cast<CXXConversionDecl>(
10871 Best->Conversions[0].UserDefined.ConversionFunction);
10872
John Wiegley429bb272011-04-08 18:41:53 +000010873 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010874 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010875
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010876 // We selected one of the surrogate functions that converts the
10877 // object parameter to a function pointer. Perform the conversion
10878 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010879
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010880 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010881 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010882 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10883 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010884 if (Call.isInvalid())
10885 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010886 // Record usage of conversion in an implicit cast.
10887 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10888 CK_UserDefinedConversion,
10889 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010890
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010891 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010892 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010893 }
10894
Eli Friedman5f2987c2012-02-02 03:46:19 +000010895 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010896 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010897 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010898
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010899 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10900 // that calls this method, using Object for the implicit object
10901 // parameter and passing along the remaining arguments.
10902 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010903 const FunctionProtoType *Proto =
10904 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010905
10906 unsigned NumArgsInProto = Proto->getNumArgs();
10907 unsigned NumArgsToCheck = NumArgs;
10908
10909 // Build the full argument list for the method call (the
10910 // implicit object parameter is placed at the beginning of the
10911 // list).
10912 Expr **MethodArgs;
10913 if (NumArgs < NumArgsInProto) {
10914 NumArgsToCheck = NumArgsInProto;
10915 MethodArgs = new Expr*[NumArgsInProto + 1];
10916 } else {
10917 MethodArgs = new Expr*[NumArgs + 1];
10918 }
John Wiegley429bb272011-04-08 18:41:53 +000010919 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10921 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010922
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010923 DeclarationNameInfo OpLocInfo(
10924 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10925 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010926 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010927 HadMultipleCandidates,
10928 OpLocInfo.getLoc(),
10929 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010930 if (NewFn.isInvalid())
10931 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010932
10933 // Once we've built TheCall, all of the expressions are properly
10934 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010935 QualType ResultTy = Method->getResultType();
10936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10937 ResultTy = ResultTy.getNonLValueExprType(Context);
10938
John McCall9ae2f072010-08-23 23:25:46 +000010939 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010940 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010941 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010942 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010943 delete [] MethodArgs;
10944
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010945 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010946 Method))
10947 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010948
Douglas Gregor518fda12009-01-13 05:10:00 +000010949 // We may have default arguments. If so, we need to allocate more
10950 // slots in the call for them.
10951 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010952 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010953 else if (NumArgs > NumArgsInProto)
10954 NumArgsToCheck = NumArgsInProto;
10955
Chris Lattner312531a2009-04-12 08:11:20 +000010956 bool IsError = false;
10957
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010958 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010959 ExprResult ObjRes =
10960 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10961 Best->FoundDecl, Method);
10962 if (ObjRes.isInvalid())
10963 IsError = true;
10964 else
10965 Object = move(ObjRes);
10966 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010967
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010968 // Check the argument types.
10969 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010970 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010971 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010972 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010973
Douglas Gregor518fda12009-01-13 05:10:00 +000010974 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010975
John McCall60d7b3a2010-08-24 06:29:42 +000010976 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010977 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010978 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010979 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010980 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010981
Anders Carlsson3faa4862010-01-29 18:43:53 +000010982 IsError |= InputInit.isInvalid();
10983 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010984 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010985 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010986 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10987 if (DefArg.isInvalid()) {
10988 IsError = true;
10989 break;
10990 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010991
Douglas Gregord47c47d2009-11-09 19:27:57 +000010992 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010993 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010994
10995 TheCall->setArg(i + 1, Arg);
10996 }
10997
10998 // If this is a variadic call, handle args passed through "...".
10999 if (Proto->isVariadic()) {
11000 // Promote the arguments (C99 6.5.2.2p7).
11001 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011002 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11003 IsError |= Arg.isInvalid();
11004 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011005 }
11006 }
11007
Chris Lattner312531a2009-04-12 08:11:20 +000011008 if (IsError) return true;
11009
Eli Friedmane61eb042012-02-18 04:48:30 +000011010 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11011
John McCall9ae2f072010-08-23 23:25:46 +000011012 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000011013 return true;
11014
John McCall182f7092010-08-24 06:09:16 +000011015 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011016}
11017
Douglas Gregor8ba10742008-11-20 16:27:02 +000011018/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011019/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011020/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011021ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011022Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011023 assert(Base->getType()->isRecordType() &&
11024 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011025
John McCall5acb0c92011-10-17 18:40:02 +000011026 if (checkPlaceholderForOverload(*this, Base))
11027 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011028
John McCall5769d612010-02-08 23:07:23 +000011029 SourceLocation Loc = Base->getExprLoc();
11030
Douglas Gregor8ba10742008-11-20 16:27:02 +000011031 // C++ [over.ref]p1:
11032 //
11033 // [...] An expression x->m is interpreted as (x.operator->())->m
11034 // for a class object x of type T if T::operator->() exists and if
11035 // the operator is selected as the best match function by the
11036 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011037 DeclarationName OpName =
11038 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011039 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011040 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011041
John McCall5769d612010-02-08 23:07:23 +000011042 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011043 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011044 return ExprError();
11045
John McCalla24dc2e2009-11-17 02:14:36 +000011046 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11047 LookupQualifiedName(R, BaseRecord->getDecl());
11048 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011049
11050 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011051 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011052 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11053 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011054 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011055
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011056 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11057
Douglas Gregor8ba10742008-11-20 16:27:02 +000011058 // Perform overload resolution.
11059 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011060 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011061 case OR_Success:
11062 // Overload resolution succeeded; we'll build the call below.
11063 break;
11064
11065 case OR_No_Viable_Function:
11066 if (CandidateSet.empty())
11067 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011068 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011069 else
11070 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011071 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011073 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011074
11075 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011076 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11077 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011078 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011079 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011080
11081 case OR_Deleted:
11082 Diag(OpLoc, diag::err_ovl_deleted_oper)
11083 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011084 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011085 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011086 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011088 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011089 }
11090
Eli Friedman5f2987c2012-02-02 03:46:19 +000011091 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011092 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011093 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011094
Douglas Gregor8ba10742008-11-20 16:27:02 +000011095 // Convert the object parameter.
11096 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011097 ExprResult BaseResult =
11098 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11099 Best->FoundDecl, Method);
11100 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011101 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011102 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011103
Douglas Gregor8ba10742008-11-20 16:27:02 +000011104 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011105 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011106 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011107 if (FnExpr.isInvalid())
11108 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011109
John McCallf89e55a2010-11-18 06:31:45 +000011110 QualType ResultTy = Method->getResultType();
11111 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11112 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011113 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011114 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000011115 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011116
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011117 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011118 Method))
11119 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011120
11121 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011122}
11123
Richard Smith36f5cfe2012-03-09 08:00:36 +000011124/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11125/// a literal operator described by the provided lookup results.
11126ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11127 DeclarationNameInfo &SuffixInfo,
11128 ArrayRef<Expr*> Args,
11129 SourceLocation LitEndLoc,
11130 TemplateArgumentListInfo *TemplateArgs) {
11131 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011132
Richard Smith36f5cfe2012-03-09 08:00:36 +000011133 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11134 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11135 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011136
Richard Smith36f5cfe2012-03-09 08:00:36 +000011137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11138
Richard Smith36f5cfe2012-03-09 08:00:36 +000011139 // Perform overload resolution. This will usually be trivial, but might need
11140 // to perform substitutions for a literal operator template.
11141 OverloadCandidateSet::iterator Best;
11142 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11143 case OR_Success:
11144 case OR_Deleted:
11145 break;
11146
11147 case OR_No_Viable_Function:
11148 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11149 << R.getLookupName();
11150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11151 return ExprError();
11152
11153 case OR_Ambiguous:
11154 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11155 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11156 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011157 }
11158
Richard Smith36f5cfe2012-03-09 08:00:36 +000011159 FunctionDecl *FD = Best->Function;
11160 MarkFunctionReferenced(UDSuffixLoc, FD);
11161 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011162
Richard Smith36f5cfe2012-03-09 08:00:36 +000011163 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11164 SuffixInfo.getLoc(),
11165 SuffixInfo.getInfo());
11166 if (Fn.isInvalid())
11167 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011168
11169 // Check the argument types. This should almost always be a no-op, except
11170 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011171 Expr *ConvArgs[2];
11172 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11173 ExprResult InputInit = PerformCopyInitialization(
11174 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11175 SourceLocation(), Args[ArgIdx]);
11176 if (InputInit.isInvalid())
11177 return true;
11178 ConvArgs[ArgIdx] = InputInit.take();
11179 }
11180
Richard Smith9fcce652012-03-07 08:35:16 +000011181 QualType ResultTy = FD->getResultType();
11182 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11183 ResultTy = ResultTy.getNonLValueExprType(Context);
11184
Richard Smith9fcce652012-03-07 08:35:16 +000011185 UserDefinedLiteral *UDL =
11186 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11187 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11188
11189 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11190 return ExprError();
11191
11192 if (CheckFunctionCall(FD, UDL))
11193 return ExprError();
11194
11195 return MaybeBindToTemporary(UDL);
11196}
11197
Douglas Gregor904eed32008-11-10 20:40:00 +000011198/// FixOverloadedFunctionReference - E is an expression that refers to
11199/// a C++ overloaded function (possibly with some parentheses and
11200/// perhaps a '&' around it). We have resolved the overloaded function
11201/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011202/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011203Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011204 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011205 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011206 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11207 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011208 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011209 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011210
Douglas Gregor699ee522009-11-20 19:42:02 +000011211 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011212 }
11213
Douglas Gregor699ee522009-11-20 19:42:02 +000011214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011215 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11216 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011217 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011218 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011219 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011220 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011221 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011222 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011223
11224 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011225 ICE->getCastKind(),
11226 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011227 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011228 }
11229
Douglas Gregor699ee522009-11-20 19:42:02 +000011230 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011231 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011232 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11234 if (Method->isStatic()) {
11235 // Do nothing: static member functions aren't any different
11236 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011237 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011238 // Fix the sub expression, which really has to be an
11239 // UnresolvedLookupExpr holding an overloaded member function
11240 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011241 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11242 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011243 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011244 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011245
John McCallba135432009-11-21 08:51:07 +000011246 assert(isa<DeclRefExpr>(SubExpr)
11247 && "fixed to something other than a decl ref");
11248 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11249 && "fixed to a member ref with no nested name qualifier");
11250
11251 // We have taken the address of a pointer to member
11252 // function. Perform the computation here so that we get the
11253 // appropriate pointer to member type.
11254 QualType ClassType
11255 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11256 QualType MemPtrType
11257 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11258
John McCallf89e55a2010-11-18 06:31:45 +000011259 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11260 VK_RValue, OK_Ordinary,
11261 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011262 }
11263 }
John McCall6bb80172010-03-30 21:47:33 +000011264 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11265 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011266 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011267 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011268
John McCall2de56d12010-08-25 11:45:40 +000011269 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011270 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011271 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011272 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011273 }
John McCallba135432009-11-21 08:51:07 +000011274
11275 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011276 // FIXME: avoid copy.
11277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011278 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011279 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11280 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011281 }
11282
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011283 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11284 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011285 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011286 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011287 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011288 ULE->getNameLoc(),
11289 Fn->getType(),
11290 VK_LValue,
11291 Found.getDecl(),
11292 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011293 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011294 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11295 return DRE;
John McCallba135432009-11-21 08:51:07 +000011296 }
11297
John McCall129e2df2009-11-30 22:42:35 +000011298 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011299 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011300 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11301 if (MemExpr->hasExplicitTemplateArgs()) {
11302 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11303 TemplateArgs = &TemplateArgsBuffer;
11304 }
John McCalld5532b62009-11-23 01:53:49 +000011305
John McCallaa81e162009-12-01 22:10:20 +000011306 Expr *Base;
11307
John McCallf89e55a2010-11-18 06:31:45 +000011308 // If we're filling in a static method where we used to have an
11309 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011310 if (MemExpr->isImplicitAccess()) {
11311 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011312 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11313 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011314 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011315 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011316 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011317 MemExpr->getMemberLoc(),
11318 Fn->getType(),
11319 VK_LValue,
11320 Found.getDecl(),
11321 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011322 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011323 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11324 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011325 } else {
11326 SourceLocation Loc = MemExpr->getMemberLoc();
11327 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011328 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011329 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011330 Base = new (Context) CXXThisExpr(Loc,
11331 MemExpr->getBaseType(),
11332 /*isImplicit=*/true);
11333 }
John McCallaa81e162009-12-01 22:10:20 +000011334 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011335 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011336
John McCallf5307512011-04-27 00:36:17 +000011337 ExprValueKind valueKind;
11338 QualType type;
11339 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11340 valueKind = VK_LValue;
11341 type = Fn->getType();
11342 } else {
11343 valueKind = VK_RValue;
11344 type = Context.BoundMemberTy;
11345 }
11346
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011347 MemberExpr *ME = MemberExpr::Create(Context, Base,
11348 MemExpr->isArrow(),
11349 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011350 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011351 Fn,
11352 Found,
11353 MemExpr->getMemberNameInfo(),
11354 TemplateArgs,
11355 type, valueKind, OK_Ordinary);
11356 ME->setHadMultipleCandidates(true);
11357 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011359
John McCall3fa5cae2010-10-26 07:05:15 +000011360 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011361}
11362
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011363ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011364 DeclAccessPair Found,
11365 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011366 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011367}
11368
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011369} // end namespace clang