blob: dec49357fef37e522d1cad89d13dffbeb3f6cdbd [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"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
John McCallf89e55a2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley429bb272011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000047}
48
John McCall120d63c2010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
52 bool CStyle);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000053
54static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
55 QualType &ToType,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
58 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000059static OverloadingResult
60IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
63 bool AllowExplicit);
64
65
66static ImplicitConversionSequence::CompareKind
67CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71static ImplicitConversionSequence::CompareKind
72CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
75
76static ImplicitConversionSequence::CompareKind
77CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
80
81
82
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083/// GetConversionCategory - Retrieve the implicit conversion
84/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000085ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000086GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
89 ICC_Identity,
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000093 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094 ICC_Qualification_Adjustment,
95 ICC_Promotion,
96 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000097 ICC_Promotion,
98 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000106 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000107 ICC_Conversion,
108 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109 ICC_Conversion
110 };
111 return Category[(int)Kind];
112}
113
114/// GetConversionRank - Retrieve the implicit conversion rank
115/// corresponding to the given implicit conversion kind.
116ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000124 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000125 ICR_Promotion,
126 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000127 ICR_Promotion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000135 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000136 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000137 ICR_Conversion,
138 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000139 ICR_Complex_Real_Conversion,
140 ICR_Conversion,
141 ICR_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142 };
143 return Rank[(int)Kind];
144}
145
146/// GetImplicitConversionName - Return the name of this kind of
147/// implicit conversion.
148const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 "No conversion",
151 "Lvalue-to-rvalue",
152 "Array-to-pointer",
153 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000154 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000155 "Qualification",
156 "Integral promotion",
157 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000158 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 "Integral conversion",
160 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000161 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000165 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000166 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000167 "Derived-to-base conversion",
168 "Vector conversion",
169 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor60d62c22008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000190 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000191}
192
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000193/// getRank - Retrieve the rank of this standard conversion sequence
194/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195/// implicit conversions.
196ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
204 return Rank;
205}
206
207/// isPointerConversionToBool - Determines whether this conversion is
208/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000209/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000211bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
215 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000216 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000220 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 return true;
223
224 return false;
225}
226
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000227/// isPointerConversionToVoidPointer - Determines whether this
228/// conversion is a conversion of a pointer to a void pointer. This is
229/// used as part of the ranking of standard conversion sequences (C++
230/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000231bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000232StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000233isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000234 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000235 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000236
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
242
Douglas Gregorf9af5242011-04-15 20:45:44 +0000243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000245 return ToPtrType->getPointeeType()->isVoidType();
246
247 return false;
248}
249
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000250/// DebugPrint - Print this standard conversion sequence to standard
251/// error. Useful for debugging overloading issues.
252void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000265
266 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000268 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000269 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000270 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000271 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000272 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 PrintedSomething = true;
274 }
275
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000285 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000286 }
287}
288
289/// DebugPrint - Print this user-defined conversion sequence to standard
290/// error. Useful for debugging overloading issues.
291void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000292 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000293 if (Before.First || Before.Second || Before.Third) {
294 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000295 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000297 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000299 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000300 After.DebugPrint();
301 }
302}
303
304/// DebugPrint - Print this implicit conversion sequence to standard
305/// error. Useful for debugging overloading issues.
306void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000307 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000308 switch (ConversionKind) {
309 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000310 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000311 Standard.DebugPrint();
312 break;
313 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000314 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000315 UserDefined.DebugPrint();
316 break;
317 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000318 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000319 break;
John McCall1d318332010-01-12 00:44:57 +0000320 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000321 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000322 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000323 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000324 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000325 break;
326 }
327
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000328 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000329}
330
John McCall1d318332010-01-12 00:44:57 +0000331void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
333}
334
335void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
337}
338
339void
340AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
344}
345
Douglas Gregora9333192010-05-08 17:41:32 +0000346namespace {
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
353 };
354}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregora9333192010-05-08 17:41:32 +0000356/// \brief Convert from Sema's representation of template deduction information
357/// to the form used in overload-candidate information.
358OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000359static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000361 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
364 Result.Data = 0;
365 switch (TDK) {
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000370 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
Douglas Gregora9333192010-05-08 17:41:32 +0000372 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000373 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000374 Result.Data = Info.Param.getOpaqueValue();
375 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000376
Douglas Gregora9333192010-05-08 17:41:32 +0000377 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000378 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
384 Result.Data = Saved;
385 break;
386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000387
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000389 Result.Data = Info.take();
390 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregora9333192010-05-08 17:41:32 +0000392 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000393 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396
Douglas Gregora9333192010-05-08 17:41:32 +0000397 return Result;
398}
John McCall1d318332010-01-12 00:44:57 +0000399
Douglas Gregora9333192010-05-08 17:41:32 +0000400void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000407 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000408 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409
Douglas Gregora9333192010-05-08 17:41:32 +0000410 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000411 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000412 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000413 Data = 0;
414 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000415
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
418 Data = 0;
419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000421 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000422 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000423 case Sema::TDK_FailedOverloadResolution:
424 break;
425 }
426}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427
428TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000429OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000435 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000436 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000437
Douglas Gregora9333192010-05-08 17:41:32 +0000438 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000439 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000440 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000441
442 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000443 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000444 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445
Douglas Gregora9333192010-05-08 17:41:32 +0000446 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000447 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000448 case Sema::TDK_FailedOverloadResolution:
449 break;
450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451
Douglas Gregora9333192010-05-08 17:41:32 +0000452 return TemplateParameter();
453}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454
Douglas Gregorec20f462010-05-08 20:07:26 +0000455TemplateArgumentList *
456OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000466 return 0;
467
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000470
Douglas Gregorec20f462010-05-08 20:07:26 +0000471 // Unhandled
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
474 break;
475 }
476
477 return 0;
478}
479
Douglas Gregora9333192010-05-08 17:41:32 +0000480const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000487 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000488 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000489 return 0;
490
Douglas Gregora9333192010-05-08 17:41:32 +0000491 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000492 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000494
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000495 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000496 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000497 case Sema::TDK_FailedOverloadResolution:
498 break;
499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
Douglas Gregora9333192010-05-08 17:41:32 +0000501 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000502}
Douglas Gregora9333192010-05-08 17:41:32 +0000503
504const TemplateArgument *
505OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000512 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000513 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000514 return 0;
515
Douglas Gregora9333192010-05-08 17:41:32 +0000516 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000517 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
519
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000520 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000521 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000522 case Sema::TDK_FailedOverloadResolution:
523 break;
524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525
Douglas Gregora9333192010-05-08 17:41:32 +0000526 return 0;
527}
528
529void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000530 inherited::clear();
531 Functions.clear();
532}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000535// overload of the declarations in Old. This routine returns false if
536// New and Old cannot be overloaded, e.g., if New has the same
537// signature as some function in Old (C++ 1.3.10) or if the Old
538// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000539// it does return false, MatchedDecl will point to the decl that New
540// cannot be overloaded with. This decl may be a UsingShadowDecl on
541// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542//
543// Example: Given the following input:
544//
545// void f(int, float); // #1
546// void f(int, int); // #2
547// int f(int, int); // #3
548//
549// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000550// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551//
John McCall51fa86f2009-12-02 08:47:38 +0000552// When we process #2, Old contains only the FunctionDecl for #1. By
553// comparing the parameter types, we see that #1 and #2 are overloaded
554// (since they have different signatures), so this routine returns
555// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556//
John McCall51fa86f2009-12-02 08:47:38 +0000557// When we process #3, Old is an overload set containing #1 and #2. We
558// compare the signatures of #3 to #1 (they're overloaded, so we do
559// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561// signature), IsOverload returns false and MatchedDecl will be set to
562// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000563//
564// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565// into a class by a using declaration. The rules for whether to hide
566// shadow declarations ignore some properties which otherwise figure
567// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000568Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000569Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000572 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000573 NamedDecl *OldD = *I;
574
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
578
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
582
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
584 }
585
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
593
John McCall51fa86f2009-12-02 08:47:38 +0000594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
598 continue;
599 }
600
John McCall871b2e72009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000603 }
John McCall51fa86f2009-12-02 08:47:38 +0000604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
608 continue;
609 }
610
John McCall871b2e72009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000613 }
John McCalld7945c62010-11-10 03:01:53 +0000614 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
624 } else {
John McCall68263142009-11-18 22:49:29 +0000625 // (C++ 13p1):
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000628 Match = *I;
629 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000630 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000631 }
John McCall68263142009-11-18 22:49:29 +0000632
John McCall871b2e72009-12-09 03:35:25 +0000633 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000634}
635
John McCallad00b772010-06-16 08:42:20 +0000636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000638 // If both of the functions are extern "C", then they are not
639 // overloads.
640 if (Old->isExternC() && New->isExternC())
641 return false;
642
John McCall68263142009-11-18 22:49:29 +0000643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
645
646 // C++ [temp.fct]p2:
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
650 return true;
651
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
655
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
659
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
664 return false;
665
John McCallf4c73712011-01-19 06:33:43 +0000666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000668
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000675 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000676 return true;
677
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
683 // signature.
684 //
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000687 //
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
695 return true;
696
697 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000699 //
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
724 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000725
John McCall68263142009-11-18 22:49:29 +0000726 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000728
John McCall68263142009-11-18 22:49:29 +0000729 // The signatures match; this is not an overload.
730 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000731}
732
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000733/// TryImplicitConversion - Attempt to perform an implicit conversion
734/// from the given expression (Expr) to the given type (ToType). This
735/// function returns an implicit conversion sequence that can be used
736/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000737///
738/// void f(float f);
739/// void g(int i) { f(i); }
740///
741/// this routine would produce an implicit conversion sequence to
742/// describe the initialization of f from i, which will be a standard
743/// conversion sequence containing an lvalue-to-rvalue conversion (C++
744/// 4.1) followed by a floating-integral conversion (C++ 4.9).
745//
746/// Note that this routine only determines how the conversion can be
747/// performed; it does not actually perform the conversion. As such,
748/// it will not produce any diagnostics if no conversion is available,
749/// but will instead return an implicit conversion sequence of kind
750/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000751///
752/// If @p SuppressUserConversions, then user-defined conversions are
753/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000754/// If @p AllowExplicit, then explicit user-defined conversions are
755/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000756static ImplicitConversionSequence
757TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000759 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000760 bool InOverloadResolution,
761 bool CStyle) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000762 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000764 ICS.Standard, CStyle)) {
John McCall1d318332010-01-12 00:44:57 +0000765 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000766 return ICS;
767 }
768
John McCall120d63c2010-08-24 20:38:10 +0000769 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000771 return ICS;
772 }
773
Douglas Gregor604eb652010-08-11 02:15:33 +0000774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000785 ICS.setStandard();
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000796 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000798 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000799
Douglas Gregor604eb652010-08-11 02:15:33 +0000800 return ICS;
801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
Douglas Gregor604eb652010-08-11 02:15:33 +0000803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
805 // we can perform.
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000807 return ICS;
808 }
809
810 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000814 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000815
816 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000817 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000827 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
829 QualType ToCanon
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000831 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000835 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000836 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000837 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000838 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000839 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000840 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000841 ICS.Standard.Second = ICK_Derived_To_Base;
842 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000843 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000844
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000852 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000854 }
John McCallcefd3ad2010-01-13 22:30:33 +0000855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000856 ICS.setAmbiguous();
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
861 if (Cand->Viable)
862 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000863 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000865 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000866
867 return ICS;
868}
869
John McCall120d63c2010-08-24 20:38:10 +0000870bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
872 Expr *Initializer,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000875 bool InOverloadResolution,
876 bool CStyle) {
John McCall120d63c2010-08-24 20:38:10 +0000877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000880 AllowExplicitConversions,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000881 InOverloadResolution,
882 CStyle);
John McCall120d63c2010-08-24 20:38:10 +0000883 if (ICS.isBad()) return true;
884
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
887 return false;
888}
889
Douglas Gregor575c63a2010-04-16 22:27:05 +0000890/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +0000891/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +0000892/// converted expression. Flavor is the kind of conversion we're
893/// performing, used in the error message. If @p AllowExplicit,
894/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +0000895ExprResult
896Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
900}
901
John Wiegley429bb272011-04-08 18:41:53 +0000902ExprResult
903Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
908 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000909 /*InOverloadResolution=*/false,
910 /*CStyle=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000911 return PerformImplicitConversion(From, ToType, ICS, Action);
912}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
914/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +0000915/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
919 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000920
John McCall00ccbef2010-12-21 00:44:39 +0000921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
923 // - a pointer
924 // - a member pointer
925 // - a block pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
940 } else {
941 return false;
942 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000943
John McCall00ccbef2010-12-21 00:44:39 +0000944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
947 return false;
948 }
949
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
953
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
957
958 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000959 return true;
960}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000962/// \brief Determine whether the conversion from FromType to ToType is a valid
963/// vector conversion.
964///
965/// \param ICK Will be set to the vector conversion kind, if this is a vector
966/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000969 // We need at least one of these types to be a vector type to have a vector
970 // conversion.
971 if (!ToType->isVectorType() && !FromType->isVectorType())
972 return false;
973
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
976 return false;
977
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
983 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000984
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000985 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000986 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000987 ICK = ICK_Vector_Splat;
988 return true;
989 }
990 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000991
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
995 // same size
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001000 ICK = ICK_Vector_Conversion;
1001 return true;
1002 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001003 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001004
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001005 return false;
1006}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor60d62c22008-10-31 16:23:19 +00001008/// IsStandardConversion - Determines whether there is a standard
1009/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010/// expression From to the type ToType. Standard conversion sequences
1011/// only consider non-class types; for conversions that involve class
1012/// types, use TryImplicitConversion. If a conversion exists, SCS will
1013/// contain the standard conversion sequence required to perform this
1014/// conversion and this routine will return true. Otherwise, this
1015/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001016static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001018 StandardConversionSequence &SCS,
1019 bool CStyle) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001020 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021
Douglas Gregor60d62c22008-10-31 16:23:19 +00001022 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001023 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001024 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001025 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001026 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001027 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028
Douglas Gregorf9201e02009-02-11 23:02:49 +00001029 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001031 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001032 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001033 return false;
1034
Mike Stump1eb44332009-09-09 15:08:12 +00001035 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001036 }
1037
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1040 // (C++ 4p1).
1041
John McCall120d63c2010-08-24 20:38:10 +00001042 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001046 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001050
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1055 QualType resultTy;
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1061 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001063
Chandler Carruth90434232011-03-29 08:08:18 +00001064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1067 // expression.
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1073 == UO_AddrOf &&
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1080 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001084
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001085 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001086 assert(S.Context.hasSameType(
1087 FromType,
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001089 } else {
1090 return false;
1091 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001096 bool argIsLValue = From->isLValue();
1097 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001098 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001100 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001101
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001106 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001109 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001110
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1113 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001114 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001115
John McCall120d63c2010-08-24 20:38:10 +00001116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001117 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001118 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001126 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001127 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001129 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001130 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001131 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001136 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001137 } else {
1138 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001139 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001141 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001147 // For overloading in C, this can also be a "compatible-type"
1148 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001149 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001150 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001156 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001157 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001158 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001160 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001161 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001162 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001163 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001164 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001177 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001178 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001182 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001195 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001196 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001197 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001198 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001199 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001205 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001206 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001207 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001208 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001210 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001211 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001212 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001213 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001214 SCS.Second = SecondICK;
1215 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001216 } else if (!S.getLangOptions().CPlusPlus &&
1217 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001218 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001219 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001220 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001221 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001222 // Treat a conversion that strips "noreturn" as an identity conversion.
1223 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001224 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1225 InOverloadResolution,
1226 SCS, CStyle)) {
1227 SCS.Second = ICK_TransparentUnionConversion;
1228 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001229 } else {
1230 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001231 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001232 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001233 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001234
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001235 QualType CanonFrom;
1236 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001237 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001238 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001239 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001240 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001241 CanonFrom = S.Context.getCanonicalType(FromType);
1242 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001243 } else {
1244 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001245 SCS.Third = ICK_Identity;
1246
Mike Stump1eb44332009-09-09 15:08:12 +00001247 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001248 // [...] Any difference in top-level cv-qualification is
1249 // subsumed by the initialization itself and does not constitute
1250 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001251 CanonFrom = S.Context.getCanonicalType(FromType);
1252 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001254 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001255 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1256 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001257 FromType = ToType;
1258 CanonFrom = CanonTo;
1259 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001260 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001261 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001262
1263 // If we have not converted the argument type to the parameter type,
1264 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001265 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001266 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001267
Douglas Gregor60d62c22008-10-31 16:23:19 +00001268 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001269}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001270
1271static bool
1272IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1273 QualType &ToType,
1274 bool InOverloadResolution,
1275 StandardConversionSequence &SCS,
1276 bool CStyle) {
1277
1278 const RecordType *UT = ToType->getAsUnionType();
1279 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1280 return false;
1281 // The field to initialize within the transparent union.
1282 RecordDecl *UD = UT->getDecl();
1283 // It's compatible if the expression matches any of the fields.
1284 for (RecordDecl::field_iterator it = UD->field_begin(),
1285 itend = UD->field_end();
1286 it != itend; ++it) {
1287 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1288 ToType = it->getType();
1289 return true;
1290 }
1291 }
1292 return false;
1293}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294
1295/// IsIntegralPromotion - Determines whether the conversion from the
1296/// expression From (whose potentially-adjusted type is FromType) to
1297/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1298/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001299bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001300 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001301 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001302 if (!To) {
1303 return false;
1304 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001305
1306 // An rvalue of type char, signed char, unsigned char, short int, or
1307 // unsigned short int can be converted to an rvalue of type int if
1308 // int can represent all the values of the source type; otherwise,
1309 // the source rvalue can be converted to an rvalue of type unsigned
1310 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001311 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1312 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001313 if (// We can promote any signed, promotable integer type to an int
1314 (FromType->isSignedIntegerType() ||
1315 // We can promote any unsigned integer type whose size is
1316 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001317 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001318 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001319 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001320 }
1321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322 return To->getKind() == BuiltinType::UInt;
1323 }
1324
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001325 // C++0x [conv.prom]p3:
1326 // A prvalue of an unscoped enumeration type whose underlying type is not
1327 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1328 // following types that can represent all the values of the enumeration
1329 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1330 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001331 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001332 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001333 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001334 // with lowest integer conversion rank (4.13) greater than the rank of long
1335 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001336 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001337 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1338 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1339 // provided for a scoped enumeration.
1340 if (FromEnumType->getDecl()->isScoped())
1341 return false;
1342
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001343 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001344 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001345 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001346 return Context.hasSameUnqualifiedType(ToType,
1347 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001348 }
John McCall842aef82009-12-09 09:09:27 +00001349
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001350 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001351 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1352 // to an rvalue a prvalue of the first of the following types that can
1353 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001354 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001355 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001356 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001358 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001360 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 // Determine whether the type we're converting from is signed or
1362 // unsigned.
1363 bool FromIsSigned;
1364 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365
John McCall842aef82009-12-09 09:09:27 +00001366 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1367 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001368
1369 // The types we'll try to promote to, in the appropriate
1370 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001371 QualType PromoteTypes[6] = {
1372 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001373 Context.LongTy, Context.UnsignedLongTy ,
1374 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001375 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001376 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001377 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1378 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001379 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001380 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1381 // We found the type that we can promote to. If this is the
1382 // type we wanted, we have a promotion. Otherwise, no
1383 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001384 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385 }
1386 }
1387 }
1388
1389 // An rvalue for an integral bit-field (9.6) can be converted to an
1390 // rvalue of type int if int can represent all the values of the
1391 // bit-field; otherwise, it can be converted to unsigned int if
1392 // unsigned int can represent all the values of the bit-field. If
1393 // the bit-field is larger yet, no integral promotion applies to
1394 // it. If the bit-field has an enumerated type, it is treated as any
1395 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001396 // FIXME: We should delay checking of bit-fields until we actually perform the
1397 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001398 using llvm::APSInt;
1399 if (From)
1400 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001401 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001402 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001403 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1404 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1405 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregor86f19402008-12-20 23:49:58 +00001407 // Are we promoting to an int from a bitfield that fits in an int?
1408 if (BitWidth < ToSize ||
1409 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1410 return To->getKind() == BuiltinType::Int;
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregor86f19402008-12-20 23:49:58 +00001413 // Are we promoting to an unsigned int from an unsigned bitfield
1414 // that fits into an unsigned int?
1415 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1416 return To->getKind() == BuiltinType::UInt;
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Douglas Gregor86f19402008-12-20 23:49:58 +00001419 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001420 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001423 // An rvalue of type bool can be converted to an rvalue of type int,
1424 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001425 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001426 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001427 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001428
1429 return false;
1430}
1431
1432/// IsFloatingPointPromotion - Determines whether the conversion from
1433/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1434/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001435bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001436 /// An rvalue of type float can be converted to an rvalue of type
1437 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001438 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1439 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001440 if (FromBuiltin->getKind() == BuiltinType::Float &&
1441 ToBuiltin->getKind() == BuiltinType::Double)
1442 return true;
1443
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001444 // C99 6.3.1.5p1:
1445 // When a float is promoted to double or long double, or a
1446 // double is promoted to long double [...].
1447 if (!getLangOptions().CPlusPlus &&
1448 (FromBuiltin->getKind() == BuiltinType::Float ||
1449 FromBuiltin->getKind() == BuiltinType::Double) &&
1450 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1451 return true;
1452 }
1453
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001454 return false;
1455}
1456
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001457/// \brief Determine if a conversion is a complex promotion.
1458///
1459/// A complex promotion is defined as a complex -> complex conversion
1460/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001461/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001462bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001463 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001464 if (!FromComplex)
1465 return false;
1466
John McCall183700f2009-09-21 23:43:11 +00001467 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001468 if (!ToComplex)
1469 return false;
1470
1471 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001472 ToComplex->getElementType()) ||
1473 IsIntegralPromotion(0, FromComplex->getElementType(),
1474 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001475}
1476
Douglas Gregorcb7de522008-11-26 23:31:11 +00001477/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1478/// the pointer type FromPtr to a pointer to type ToPointee, with the
1479/// same type qualifiers as FromPtr has on its pointee type. ToType,
1480/// if non-empty, will be a pointer to ToType that may or may not have
1481/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001482static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001483BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001484 QualType ToPointee, QualType ToType,
1485 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001486 assert((FromPtr->getTypeClass() == Type::Pointer ||
1487 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1488 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001489
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001490 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1491 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1492 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493
1494 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001495 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001496 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001497 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001498
1499 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001500 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001501 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001502 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001503 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001504
1505 // Build a pointer to ToPointee. It has the right qualifiers
1506 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001507 if (isa<ObjCObjectPointerType>(ToType))
1508 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001509 return Context.getPointerType(ToPointee);
1510 }
1511
1512 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001513 QualType QualifiedCanonToPointee
1514 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515
Douglas Gregorda80f742010-12-01 21:43:58 +00001516 if (isa<ObjCObjectPointerType>(ToType))
1517 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1518 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001519}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001520
Mike Stump1eb44332009-09-09 15:08:12 +00001521static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001522 bool InOverloadResolution,
1523 ASTContext &Context) {
1524 // Handle value-dependent integral null pointer constants correctly.
1525 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1526 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001527 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001528 return !InOverloadResolution;
1529
Douglas Gregorce940492009-09-25 04:25:58 +00001530 return Expr->isNullPointerConstant(Context,
1531 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1532 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001533}
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535/// IsPointerConversion - Determines whether the conversion of the
1536/// expression From, which has the (possibly adjusted) type FromType,
1537/// can be converted to the type ToType via a pointer conversion (C++
1538/// 4.10). If so, returns true and places the converted type (that
1539/// might differ from ToType in its cv-qualifiers at some level) into
1540/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001541///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001542/// This routine also supports conversions to and from block pointers
1543/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1544/// pointers to interfaces. FIXME: Once we've determined the
1545/// appropriate overloading rules for Objective-C, we may want to
1546/// split the Objective-C checks into a different routine; however,
1547/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001548/// conversions, so for now they live here. IncompatibleObjC will be
1549/// set if the conversion is an allowed Objective-C conversion that
1550/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001552 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001553 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001554 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001555 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001556 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1557 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001558 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001559
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // Conversion from a null pointer constant to any Objective-C pointer type.
1561 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001562 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001563 ConvertedType = ToType;
1564 return true;
1565 }
1566
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001567 // Blocks: Block pointers can be converted to void*.
1568 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001569 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001570 ConvertedType = ToType;
1571 return true;
1572 }
1573 // Blocks: A null pointer constant can be converted to a block
1574 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001575 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001576 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001581 // If the left-hand-side is nullptr_t, the right side can be a null
1582 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001584 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001585 ConvertedType = ToType;
1586 return true;
1587 }
1588
Ted Kremenek6217b802009-07-29 21:53:49 +00001589 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001590 if (!ToTypePtr)
1591 return false;
1592
1593 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001594 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001595 ConvertedType = ToType;
1596 return true;
1597 }
Sebastian Redl07779722008-10-31 14:43:28 +00001598
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001599 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001600 // , including objective-c pointers.
1601 QualType ToPointeeType = ToTypePtr->getPointeeType();
1602 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001603 ConvertedType = BuildSimilarlyQualifiedPointerType(
1604 FromType->getAs<ObjCObjectPointerType>(),
1605 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001606 ToType, Context);
1607 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001608 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001609 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001610 if (!FromTypePtr)
1611 return false;
1612
1613 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001614
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001616 // pointer conversion, so don't do all of the work below.
1617 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1618 return false;
1619
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620 // An rvalue of type "pointer to cv T," where T is an object type,
1621 // can be converted to an rvalue of type "pointer to cv void" (C++
1622 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001623 if (FromPointeeType->isIncompleteOrObjectType() &&
1624 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001625 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001626 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001627 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001628 return true;
1629 }
1630
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001631 // MSVC allows implicit function to void* type conversion.
1632 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1633 ToPointeeType->isVoidType()) {
1634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1635 ToPointeeType,
1636 ToType, Context);
1637 return true;
1638 }
1639
Douglas Gregorf9201e02009-02-11 23:02:49 +00001640 // When we're overloading in C, we allow a special kind of pointer
1641 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001642 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001643 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001644 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001645 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001646 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001647 return true;
1648 }
1649
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001650 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001651 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001652 // An rvalue of type "pointer to cv D," where D is a class type,
1653 // can be converted to an rvalue of type "pointer to cv B," where
1654 // B is a base class (clause 10) of D. If B is an inaccessible
1655 // (clause 11) or ambiguous (10.2) base class of D, a program that
1656 // necessitates this conversion is ill-formed. The result of the
1657 // conversion is a pointer to the base class sub-object of the
1658 // derived class object. The null pointer value is converted to
1659 // the null pointer value of the destination type.
1660 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001661 // Note that we do not check for ambiguity or inaccessibility
1662 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001663 if (getLangOptions().CPlusPlus &&
1664 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001665 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001666 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001667 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001668 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001669 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001670 ToType, Context);
1671 return true;
1672 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001673
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001674 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1675 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1676 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1677 ToPointeeType,
1678 ToType, Context);
1679 return true;
1680 }
1681
Douglas Gregorc7887512008-12-19 19:13:09 +00001682 return false;
1683}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001684
1685/// \brief Adopt the given qualifiers for the given type.
1686static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1687 Qualifiers TQs = T.getQualifiers();
1688
1689 // Check whether qualifiers already match.
1690 if (TQs == Qs)
1691 return T;
1692
1693 if (Qs.compatiblyIncludes(TQs))
1694 return Context.getQualifiedType(T, Qs);
1695
1696 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1697}
Douglas Gregorc7887512008-12-19 19:13:09 +00001698
1699/// isObjCPointerConversion - Determines whether this is an
1700/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1701/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001702bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001703 QualType& ConvertedType,
1704 bool &IncompatibleObjC) {
1705 if (!getLangOptions().ObjC1)
1706 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001708 // The set of qualifiers on the type we're converting from.
1709 Qualifiers FromQualifiers = FromType.getQualifiers();
1710
Steve Naroff14108da2009-07-10 23:34:53 +00001711 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001712 const ObjCObjectPointerType* ToObjCPtr =
1713 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001714 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001715 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001716
Steve Naroff14108da2009-07-10 23:34:53 +00001717 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001718 // If the pointee types are the same (ignoring qualifications),
1719 // then this is not a pointer conversion.
1720 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1721 FromObjCPtr->getPointeeType()))
1722 return false;
1723
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001724 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00001725 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001726 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001727 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001728 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001729 return true;
1730 }
1731 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001732 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001733 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001734 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001735 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001736 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001737 return true;
1738 }
1739 // Objective C++: We're able to convert from a pointer to an
1740 // interface to a pointer to a different interface.
1741 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001742 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1743 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1744 if (getLangOptions().CPlusPlus && LHS && RHS &&
1745 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1746 FromObjCPtr->getPointeeType()))
1747 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001748 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001749 ToObjCPtr->getPointeeType(),
1750 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001751 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001752 return true;
1753 }
1754
1755 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1756 // Okay: this is some kind of implicit downcast of Objective-C
1757 // interfaces, which is permitted. However, we're going to
1758 // complain about it.
1759 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001760 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001761 ToObjCPtr->getPointeeType(),
1762 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001763 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001764 return true;
1765 }
Mike Stump1eb44332009-09-09 15:08:12 +00001766 }
Steve Naroff14108da2009-07-10 23:34:53 +00001767 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001768 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001769 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001770 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001772 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001773 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001774 // to a block pointer type.
1775 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001777 return true;
1778 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001779 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001780 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001782 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001783 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001784 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001785 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001786 return true;
1787 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001788 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001789 return false;
1790
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001791 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001792 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001793 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001794 else if (const BlockPointerType *FromBlockPtr =
1795 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001796 FromPointeeType = FromBlockPtr->getPointeeType();
1797 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001798 return false;
1799
Douglas Gregorc7887512008-12-19 19:13:09 +00001800 // If we have pointers to pointers, recursively check whether this
1801 // is an Objective-C conversion.
1802 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1803 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1804 IncompatibleObjC)) {
1805 // We always complain about this conversion.
1806 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001807 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001808 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001809 return true;
1810 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001811 // Allow conversion of pointee being objective-c pointer to another one;
1812 // as in I* to id.
1813 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1814 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1815 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1816 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001817 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001818 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001819 return true;
1820 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001821
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001822 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001823 // differences in the argument and result types are in Objective-C
1824 // pointer conversions. If so, we permit the conversion (but
1825 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001826 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001827 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001828 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001829 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001830 if (FromFunctionType && ToFunctionType) {
1831 // If the function types are exactly the same, this isn't an
1832 // Objective-C pointer conversion.
1833 if (Context.getCanonicalType(FromPointeeType)
1834 == Context.getCanonicalType(ToPointeeType))
1835 return false;
1836
1837 // Perform the quick checks that will tell us whether these
1838 // function types are obviously different.
1839 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1840 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1841 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1842 return false;
1843
1844 bool HasObjCConversion = false;
1845 if (Context.getCanonicalType(FromFunctionType->getResultType())
1846 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1847 // Okay, the types match exactly. Nothing to do.
1848 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1849 ToFunctionType->getResultType(),
1850 ConvertedType, IncompatibleObjC)) {
1851 // Okay, we have an Objective-C pointer conversion.
1852 HasObjCConversion = true;
1853 } else {
1854 // Function types are too different. Abort.
1855 return false;
1856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregorc7887512008-12-19 19:13:09 +00001858 // Check argument types.
1859 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1860 ArgIdx != NumArgs; ++ArgIdx) {
1861 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1862 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1863 if (Context.getCanonicalType(FromArgType)
1864 == Context.getCanonicalType(ToArgType)) {
1865 // Okay, the types match exactly. Nothing to do.
1866 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1867 ConvertedType, IncompatibleObjC)) {
1868 // Okay, we have an Objective-C pointer conversion.
1869 HasObjCConversion = true;
1870 } else {
1871 // Argument types are too different. Abort.
1872 return false;
1873 }
1874 }
1875
1876 if (HasObjCConversion) {
1877 // We had an Objective-C conversion. Allow this pointer
1878 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001879 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001880 IncompatibleObjC = true;
1881 return true;
1882 }
1883 }
1884
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001885 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001886}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001887
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001888bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1889 QualType& ConvertedType) {
1890 QualType ToPointeeType;
1891 if (const BlockPointerType *ToBlockPtr =
1892 ToType->getAs<BlockPointerType>())
1893 ToPointeeType = ToBlockPtr->getPointeeType();
1894 else
1895 return false;
1896
1897 QualType FromPointeeType;
1898 if (const BlockPointerType *FromBlockPtr =
1899 FromType->getAs<BlockPointerType>())
1900 FromPointeeType = FromBlockPtr->getPointeeType();
1901 else
1902 return false;
1903 // We have pointer to blocks, check whether the only
1904 // differences in the argument and result types are in Objective-C
1905 // pointer conversions. If so, we permit the conversion.
1906
1907 const FunctionProtoType *FromFunctionType
1908 = FromPointeeType->getAs<FunctionProtoType>();
1909 const FunctionProtoType *ToFunctionType
1910 = ToPointeeType->getAs<FunctionProtoType>();
1911
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001912 if (!FromFunctionType || !ToFunctionType)
1913 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001914
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001915 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001916 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001917
1918 // Perform the quick checks that will tell us whether these
1919 // function types are obviously different.
1920 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1921 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1922 return false;
1923
1924 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1925 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1926 if (FromEInfo != ToEInfo)
1927 return false;
1928
1929 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00001930 if (Context.hasSameType(FromFunctionType->getResultType(),
1931 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001932 // Okay, the types match exactly. Nothing to do.
1933 } else {
1934 QualType RHS = FromFunctionType->getResultType();
1935 QualType LHS = ToFunctionType->getResultType();
1936 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1937 !RHS.hasQualifiers() && LHS.hasQualifiers())
1938 LHS = LHS.getUnqualifiedType();
1939
1940 if (Context.hasSameType(RHS,LHS)) {
1941 // OK exact match.
1942 } else if (isObjCPointerConversion(RHS, LHS,
1943 ConvertedType, IncompatibleObjC)) {
1944 if (IncompatibleObjC)
1945 return false;
1946 // Okay, we have an Objective-C pointer conversion.
1947 }
1948 else
1949 return false;
1950 }
1951
1952 // Check argument types.
1953 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1954 ArgIdx != NumArgs; ++ArgIdx) {
1955 IncompatibleObjC = false;
1956 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1957 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1958 if (Context.hasSameType(FromArgType, ToArgType)) {
1959 // Okay, the types match exactly. Nothing to do.
1960 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1961 ConvertedType, IncompatibleObjC)) {
1962 if (IncompatibleObjC)
1963 return false;
1964 // Okay, we have an Objective-C pointer conversion.
1965 } else
1966 // Argument types are too different. Abort.
1967 return false;
1968 }
1969 ConvertedType = ToType;
1970 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001971}
1972
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001973/// FunctionArgTypesAreEqual - This routine checks two function proto types
1974/// for equlity of their argument types. Caller has already checked that
1975/// they have same number of arguments. This routine assumes that Objective-C
1976/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001977bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCallf4c73712011-01-19 06:33:43 +00001978 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001979 if (!getLangOptions().ObjC1)
1980 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1981 NewType->arg_type_begin());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001982
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001983 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1984 N = NewType->arg_type_begin(),
1985 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1986 QualType ToType = (*O);
1987 QualType FromType = (*N);
1988 if (ToType != FromType) {
1989 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1990 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001991 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1992 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1993 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1994 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001995 continue;
1996 }
John McCallc12c5bb2010-05-15 11:32:37 +00001997 else if (const ObjCObjectPointerType *PTTo =
1998 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002000 FromType->getAs<ObjCObjectPointerType>())
2001 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2002 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002004 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002005 }
2006 }
2007 return true;
2008}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002009
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002010/// CheckPointerConversion - Check the pointer conversion from the
2011/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002012/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002013/// conversions for which IsPointerConversion has already returned
2014/// true. It returns true and produces a diagnostic if there was an
2015/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002016bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002017 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002018 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002019 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002020 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002021 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002022
John McCalldaa8e4e2010-11-15 09:13:47 +00002023 Kind = CK_BitCast;
2024
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002025 if (!IsCStyleOrFunctionalCast &&
2026 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2027 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2028 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002029 PDiag(diag::warn_impcast_bool_to_null_pointer)
2030 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002031
Ted Kremenek6217b802009-07-29 21:53:49 +00002032 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2033 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002034 QualType FromPointeeType = FromPtrType->getPointeeType(),
2035 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002036
Douglas Gregor5fccd362010-03-03 23:55:11 +00002037 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2038 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002039 // We must have a derived-to-base conversion. Check an
2040 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002041 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2042 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002043 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002044 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002045 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002046
Anders Carlsson61faec12009-09-12 04:46:44 +00002047 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002048 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002049 }
2050 }
Mike Stump1eb44332009-09-09 15:08:12 +00002051 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00002052 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002053 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00002054 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002055 // Objective-C++ conversions are always okay.
2056 // FIXME: We should have a different class of conversions for the
2057 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002058 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002059 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00002060 }
Steve Naroff14108da2009-07-10 23:34:53 +00002061 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002062
2063 // We shouldn't fall into this case unless it's valid for other
2064 // reasons.
2065 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2066 Kind = CK_NullToPointer;
2067
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002068 return false;
2069}
2070
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002071/// IsMemberPointerConversion - Determines whether the conversion of the
2072/// expression From, which has the (possibly adjusted) type FromType, can be
2073/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2074/// If so, returns true and places the converted type (that might differ from
2075/// ToType in its cv-qualifiers at some level) into ConvertedType.
2076bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002077 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002078 bool InOverloadResolution,
2079 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002080 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002081 if (!ToTypePtr)
2082 return false;
2083
2084 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002085 if (From->isNullPointerConstant(Context,
2086 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2087 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002088 ConvertedType = ToType;
2089 return true;
2090 }
2091
2092 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002093 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002094 if (!FromTypePtr)
2095 return false;
2096
2097 // A pointer to member of B can be converted to a pointer to member of D,
2098 // where D is derived from B (C++ 4.11p2).
2099 QualType FromClass(FromTypePtr->getClass(), 0);
2100 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002101
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002102 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2103 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2104 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002105 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2106 ToClass.getTypePtr());
2107 return true;
2108 }
2109
2110 return false;
2111}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002113/// CheckMemberPointerConversion - Check the member pointer conversion from the
2114/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002115/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002116/// for which IsMemberPointerConversion has already returned true. It returns
2117/// true and produces a diagnostic if there was an error, or returns false
2118/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002119bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002120 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002121 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002122 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002123 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002124 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002125 if (!FromPtrType) {
2126 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002127 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002128 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002129 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002130 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002131 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002132 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002133
Ted Kremenek6217b802009-07-29 21:53:49 +00002134 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002135 assert(ToPtrType && "No member pointer cast has a target type "
2136 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002137
Sebastian Redl21593ac2009-01-28 18:33:18 +00002138 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2139 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002140
Sebastian Redl21593ac2009-01-28 18:33:18 +00002141 // FIXME: What about dependent types?
2142 assert(FromClass->isRecordType() && "Pointer into non-class.");
2143 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002144
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002146 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002147 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2148 assert(DerivationOkay &&
2149 "Should not have been called if derivation isn't OK.");
2150 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002151
Sebastian Redl21593ac2009-01-28 18:33:18 +00002152 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2153 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002154 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2155 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2156 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2157 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002158 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002159
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002160 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002161 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2162 << FromClass << ToClass << QualType(VBase, 0)
2163 << From->getSourceRange();
2164 return true;
2165 }
2166
John McCall6b2accb2010-02-10 09:31:12 +00002167 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002168 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2169 Paths.front(),
2170 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002171
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002172 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002173 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002174 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002175 return false;
2176}
2177
Douglas Gregor98cd5992008-10-21 23:43:52 +00002178/// IsQualificationConversion - Determines whether the conversion from
2179/// an rvalue of type FromType to ToType is a qualification conversion
2180/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00002181bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002182Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002183 bool CStyle) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002184 FromType = Context.getCanonicalType(FromType);
2185 ToType = Context.getCanonicalType(ToType);
2186
2187 // If FromType and ToType are the same type, this is not a
2188 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002189 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002190 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002191
Douglas Gregor98cd5992008-10-21 23:43:52 +00002192 // (C++ 4.4p4):
2193 // A conversion can add cv-qualifiers at levels other than the first
2194 // in multi-level pointers, subject to the following rules: [...]
2195 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002196 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002197 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002198 // Within each iteration of the loop, we check the qualifiers to
2199 // determine if this still looks like a qualification
2200 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002201 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002202 // until there are no more pointers or pointers-to-members left to
2203 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002204 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002205
Douglas Gregor621c92a2011-04-25 18:40:17 +00002206 Qualifiers FromQuals = FromType.getQualifiers();
2207 Qualifiers ToQuals = ToType.getQualifiers();
2208
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002209 // Allow addition/removal of GC attributes but not changing GC attributes.
2210 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2211 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2212 FromQuals.removeObjCGCAttr();
2213 ToQuals.removeObjCGCAttr();
2214 }
2215
Douglas Gregor98cd5992008-10-21 23:43:52 +00002216 // -- for every j > 0, if const is in cv 1,j then const is in cv
2217 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002218 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002219 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregor98cd5992008-10-21 23:43:52 +00002221 // -- if the cv 1,j and cv 2,j are different, then const is in
2222 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002223 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002224 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002225 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Douglas Gregor98cd5992008-10-21 23:43:52 +00002227 // Keep track of whether all prior cv-qualifiers in the "to" type
2228 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002229 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002230 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002231 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002232
2233 // We are left with FromType and ToType being the pointee types
2234 // after unwrapping the original FromType and ToType the same number
2235 // of types. If we unwrapped any pointers, and if FromType and
2236 // ToType have the same unqualified type (since we checked
2237 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002238 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002239}
2240
Douglas Gregor734d9862009-01-30 23:27:23 +00002241/// Determines whether there is a user-defined conversion sequence
2242/// (C++ [over.ics.user]) that converts expression From to the type
2243/// ToType. If such a conversion exists, User will contain the
2244/// user-defined conversion sequence that performs such a conversion
2245/// and this routine will return true. Otherwise, this routine returns
2246/// false and User is unspecified.
2247///
Douglas Gregor734d9862009-01-30 23:27:23 +00002248/// \param AllowExplicit true if the conversion should consider C++0x
2249/// "explicit" conversion functions as well as non-explicit conversion
2250/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002251static OverloadingResult
2252IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2253 UserDefinedConversionSequence& User,
2254 OverloadCandidateSet& CandidateSet,
2255 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002256 // Whether we will only visit constructors.
2257 bool ConstructorsOnly = false;
2258
2259 // If the type we are conversion to is a class type, enumerate its
2260 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002261 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002262 // C++ [over.match.ctor]p1:
2263 // When objects of class type are direct-initialized (8.5), or
2264 // copy-initialized from an expression of the same or a
2265 // derived class type (8.5), overload resolution selects the
2266 // constructor. [...] For copy-initialization, the candidate
2267 // functions are all the converting constructors (12.3.1) of
2268 // that class. The argument list is the expression-list within
2269 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002270 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002271 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002272 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002273 ConstructorsOnly = true;
2274
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002275 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2276 // RequireCompleteType may have returned true due to some invalid decl
2277 // during template instantiation, but ToType may be complete enough now
2278 // to try to recover.
2279 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002280 // We're not going to find any constructors.
2281 } else if (CXXRecordDecl *ToRecordDecl
2282 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002283 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002284 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002285 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002286 NamedDecl *D = *Con;
2287 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2288
Douglas Gregordec06662009-08-21 18:42:58 +00002289 // Find the constructor (which may be a template).
2290 CXXConstructorDecl *Constructor = 0;
2291 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002292 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002293 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002294 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002295 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2296 else
John McCall9aa472c2010-03-19 07:35:19 +00002297 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002298
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002299 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002300 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002301 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002302 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2303 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002305 /*SuppressUserConversions=*/
2306 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002307 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002308 // Allow one user-defined conversion when user specifies a
2309 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002310 S.AddOverloadCandidate(Constructor, FoundDecl,
2311 &From, 1, CandidateSet,
2312 /*SuppressUserConversions=*/
2313 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002314 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002315 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002316 }
2317 }
2318
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002319 // Enumerate conversion functions, if we're allowed to.
2320 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002321 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2322 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002323 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002324 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002325 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002326 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002327 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2328 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002329 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002330 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002331 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002332 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002333 DeclAccessPair FoundDecl = I.getPair();
2334 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002335 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2336 if (isa<UsingShadowDecl>(D))
2337 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2338
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002339 CXXConversionDecl *Conv;
2340 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002341 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2342 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002343 else
John McCall32daa422010-03-31 01:36:47 +00002344 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002345
2346 if (AllowExplicit || !Conv->isExplicit()) {
2347 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002348 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2349 ActingContext, From, ToType,
2350 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002351 else
John McCall120d63c2010-08-24 20:38:10 +00002352 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2353 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002354 }
2355 }
2356 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002357 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002358
2359 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002360 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002361 case OR_Success:
2362 // Record the standard conversion we used and the conversion function.
2363 if (CXXConstructorDecl *Constructor
2364 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002365 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2366
John McCall120d63c2010-08-24 20:38:10 +00002367 // C++ [over.ics.user]p1:
2368 // If the user-defined conversion is specified by a
2369 // constructor (12.3.1), the initial standard conversion
2370 // sequence converts the source type to the type required by
2371 // the argument of the constructor.
2372 //
2373 QualType ThisType = Constructor->getThisType(S.Context);
2374 if (Best->Conversions[0].isEllipsis())
2375 User.EllipsisConversion = true;
2376 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002377 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002378 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002379 }
John McCall120d63c2010-08-24 20:38:10 +00002380 User.ConversionFunction = Constructor;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002381 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002382 User.After.setAsIdentityConversion();
2383 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2384 User.After.setAllToTypes(ToType);
2385 return OR_Success;
2386 } else if (CXXConversionDecl *Conversion
2387 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002388 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2389
John McCall120d63c2010-08-24 20:38:10 +00002390 // C++ [over.ics.user]p1:
2391 //
2392 // [...] If the user-defined conversion is specified by a
2393 // conversion function (12.3.2), the initial standard
2394 // conversion sequence converts the source type to the
2395 // implicit object parameter of the conversion function.
2396 User.Before = Best->Conversions[0].Standard;
2397 User.ConversionFunction = Conversion;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002398 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002399 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002400
John McCall120d63c2010-08-24 20:38:10 +00002401 // C++ [over.ics.user]p2:
2402 // The second standard conversion sequence converts the
2403 // result of the user-defined conversion to the target type
2404 // for the sequence. Since an implicit conversion sequence
2405 // is an initialization, the special rules for
2406 // initialization by user-defined conversion apply when
2407 // selecting the best user-defined conversion for a
2408 // user-defined conversion sequence (see 13.3.3 and
2409 // 13.3.3.1).
2410 User.After = Best->FinalConversion;
2411 return OR_Success;
2412 } else {
2413 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002414 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002415 }
2416
John McCall120d63c2010-08-24 20:38:10 +00002417 case OR_No_Viable_Function:
2418 return OR_No_Viable_Function;
2419 case OR_Deleted:
2420 // No conversion here! We're done.
2421 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002422
John McCall120d63c2010-08-24 20:38:10 +00002423 case OR_Ambiguous:
2424 return OR_Ambiguous;
2425 }
2426
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002427 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002428}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002429
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002430bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002431Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002432 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002433 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002434 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002435 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002436 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002437 if (OvResult == OR_Ambiguous)
2438 Diag(From->getSourceRange().getBegin(),
2439 diag::err_typecheck_ambiguous_condition)
2440 << From->getType() << ToType << From->getSourceRange();
2441 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2442 Diag(From->getSourceRange().getBegin(),
2443 diag::err_typecheck_nonviable_condition)
2444 << From->getType() << ToType << From->getSourceRange();
2445 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002446 return false;
John McCall120d63c2010-08-24 20:38:10 +00002447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002448 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002449}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002451/// CompareImplicitConversionSequences - Compare two implicit
2452/// conversion sequences to determine whether one is better than the
2453/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002454static ImplicitConversionSequence::CompareKind
2455CompareImplicitConversionSequences(Sema &S,
2456 const ImplicitConversionSequence& ICS1,
2457 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002458{
2459 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2460 // conversion sequences (as defined in 13.3.3.1)
2461 // -- a standard conversion sequence (13.3.3.1.1) is a better
2462 // conversion sequence than a user-defined conversion sequence or
2463 // an ellipsis conversion sequence, and
2464 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2465 // conversion sequence than an ellipsis conversion sequence
2466 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002467 //
John McCall1d318332010-01-12 00:44:57 +00002468 // C++0x [over.best.ics]p10:
2469 // For the purpose of ranking implicit conversion sequences as
2470 // described in 13.3.3.2, the ambiguous conversion sequence is
2471 // treated as a user-defined sequence that is indistinguishable
2472 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002473 if (ICS1.getKindRank() < ICS2.getKindRank())
2474 return ImplicitConversionSequence::Better;
2475 else if (ICS2.getKindRank() < ICS1.getKindRank())
2476 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002477
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002478 // The following checks require both conversion sequences to be of
2479 // the same kind.
2480 if (ICS1.getKind() != ICS2.getKind())
2481 return ImplicitConversionSequence::Indistinguishable;
2482
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002483 // Two implicit conversion sequences of the same form are
2484 // indistinguishable conversion sequences unless one of the
2485 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002486 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002487 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002488 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002489 // User-defined conversion sequence U1 is a better conversion
2490 // sequence than another user-defined conversion sequence U2 if
2491 // they contain the same user-defined conversion function or
2492 // constructor and if the second standard conversion sequence of
2493 // U1 is better than the second standard conversion sequence of
2494 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002495 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002496 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002497 return CompareStandardConversionSequences(S,
2498 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002499 ICS2.UserDefined.After);
2500 }
2501
2502 return ImplicitConversionSequence::Indistinguishable;
2503}
2504
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002505static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2506 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2507 Qualifiers Quals;
2508 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002509 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002510 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002511
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002512 return Context.hasSameUnqualifiedType(T1, T2);
2513}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002514
Douglas Gregorad323a82010-01-27 03:51:04 +00002515// Per 13.3.3.2p3, compare the given standard conversion sequences to
2516// determine if one is a proper subset of the other.
2517static ImplicitConversionSequence::CompareKind
2518compareStandardConversionSubsets(ASTContext &Context,
2519 const StandardConversionSequence& SCS1,
2520 const StandardConversionSequence& SCS2) {
2521 ImplicitConversionSequence::CompareKind Result
2522 = ImplicitConversionSequence::Indistinguishable;
2523
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002524 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002525 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00002526 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2527 return ImplicitConversionSequence::Better;
2528 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2529 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002530
Douglas Gregorad323a82010-01-27 03:51:04 +00002531 if (SCS1.Second != SCS2.Second) {
2532 if (SCS1.Second == ICK_Identity)
2533 Result = ImplicitConversionSequence::Better;
2534 else if (SCS2.Second == ICK_Identity)
2535 Result = ImplicitConversionSequence::Worse;
2536 else
2537 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002538 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002539 return ImplicitConversionSequence::Indistinguishable;
2540
2541 if (SCS1.Third == SCS2.Third) {
2542 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2543 : ImplicitConversionSequence::Indistinguishable;
2544 }
2545
2546 if (SCS1.Third == ICK_Identity)
2547 return Result == ImplicitConversionSequence::Worse
2548 ? ImplicitConversionSequence::Indistinguishable
2549 : ImplicitConversionSequence::Better;
2550
2551 if (SCS2.Third == ICK_Identity)
2552 return Result == ImplicitConversionSequence::Better
2553 ? ImplicitConversionSequence::Indistinguishable
2554 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555
Douglas Gregorad323a82010-01-27 03:51:04 +00002556 return ImplicitConversionSequence::Indistinguishable;
2557}
2558
Douglas Gregor440a4832011-01-26 14:52:12 +00002559/// \brief Determine whether one of the given reference bindings is better
2560/// than the other based on what kind of bindings they are.
2561static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2562 const StandardConversionSequence &SCS2) {
2563 // C++0x [over.ics.rank]p3b4:
2564 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2565 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002567 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002569 // reference*.
2570 //
2571 // FIXME: Rvalue references. We're going rogue with the above edits,
2572 // because the semantics in the current C++0x working paper (N3225 at the
2573 // time of this writing) break the standard definition of std::forward
2574 // and std::reference_wrapper when dealing with references to functions.
2575 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002576 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2577 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2578 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002579
Douglas Gregor440a4832011-01-26 14:52:12 +00002580 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2581 SCS2.IsLvalueReference) ||
2582 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2583 !SCS2.IsLvalueReference);
2584}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002585
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002586/// CompareStandardConversionSequences - Compare two standard
2587/// conversion sequences to determine whether one is better than the
2588/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002589static ImplicitConversionSequence::CompareKind
2590CompareStandardConversionSequences(Sema &S,
2591 const StandardConversionSequence& SCS1,
2592 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002593{
2594 // Standard conversion sequence S1 is a better conversion sequence
2595 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2596
2597 // -- S1 is a proper subsequence of S2 (comparing the conversion
2598 // sequences in the canonical form defined by 13.3.3.1.1,
2599 // excluding any Lvalue Transformation; the identity conversion
2600 // sequence is considered to be a subsequence of any
2601 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002602 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002603 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002604 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002605
2606 // -- the rank of S1 is better than the rank of S2 (by the rules
2607 // defined below), or, if not that,
2608 ImplicitConversionRank Rank1 = SCS1.getRank();
2609 ImplicitConversionRank Rank2 = SCS2.getRank();
2610 if (Rank1 < Rank2)
2611 return ImplicitConversionSequence::Better;
2612 else if (Rank2 < Rank1)
2613 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002614
Douglas Gregor57373262008-10-22 14:17:15 +00002615 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2616 // are indistinguishable unless one of the following rules
2617 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor57373262008-10-22 14:17:15 +00002619 // A conversion that is not a conversion of a pointer, or
2620 // pointer to member, to bool is better than another conversion
2621 // that is such a conversion.
2622 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2623 return SCS2.isPointerConversionToBool()
2624 ? ImplicitConversionSequence::Better
2625 : ImplicitConversionSequence::Worse;
2626
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002627 // C++ [over.ics.rank]p4b2:
2628 //
2629 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002630 // conversion of B* to A* is better than conversion of B* to
2631 // void*, and conversion of A* to void* is better than conversion
2632 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002633 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002634 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002635 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002636 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002637 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2638 // Exactly one of the conversion sequences is a conversion to
2639 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002640 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2641 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002642 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2643 // Neither conversion sequence converts to a void pointer; compare
2644 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002645 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002646 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002647 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002648 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2649 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002650 // Both conversion sequences are conversions to void
2651 // pointers. Compare the source types to determine if there's an
2652 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002653 QualType FromType1 = SCS1.getFromType();
2654 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002655
2656 // Adjust the types we're converting from via the array-to-pointer
2657 // conversion, if we need to.
2658 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002659 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002660 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002661 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002662
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002663 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2664 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002665
John McCall120d63c2010-08-24 20:38:10 +00002666 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002667 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002668 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002669 return ImplicitConversionSequence::Worse;
2670
2671 // Objective-C++: If one interface is more specific than the
2672 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002673 const ObjCObjectPointerType* FromObjCPtr1
2674 = FromType1->getAs<ObjCObjectPointerType>();
2675 const ObjCObjectPointerType* FromObjCPtr2
2676 = FromType2->getAs<ObjCObjectPointerType>();
2677 if (FromObjCPtr1 && FromObjCPtr2) {
2678 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2679 FromObjCPtr2);
2680 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2681 FromObjCPtr1);
2682 if (AssignLeft != AssignRight) {
2683 return AssignLeft? ImplicitConversionSequence::Better
2684 : ImplicitConversionSequence::Worse;
2685 }
Douglas Gregor01919692009-12-13 21:37:05 +00002686 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002687 }
Douglas Gregor57373262008-10-22 14:17:15 +00002688
2689 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2690 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002691 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002692 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002693 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002694
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002695 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002696 // Check for a better reference binding based on the kind of bindings.
2697 if (isBetterReferenceBindingKind(SCS1, SCS2))
2698 return ImplicitConversionSequence::Better;
2699 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2700 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002702 // C++ [over.ics.rank]p3b4:
2703 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2704 // which the references refer are the same type except for
2705 // top-level cv-qualifiers, and the type to which the reference
2706 // initialized by S2 refers is more cv-qualified than the type
2707 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002708 QualType T1 = SCS1.getToType(2);
2709 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002710 T1 = S.Context.getCanonicalType(T1);
2711 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002712 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002713 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2714 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002715 if (UnqualT1 == UnqualT2) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00002716 // If the type is an array type, promote the element qualifiers to the
2717 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002718 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002719 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002720 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002721 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002722 if (T2.isMoreQualifiedThan(T1))
2723 return ImplicitConversionSequence::Better;
2724 else if (T1.isMoreQualifiedThan(T2))
2725 return ImplicitConversionSequence::Worse;
2726 }
2727 }
Douglas Gregor57373262008-10-22 14:17:15 +00002728
2729 return ImplicitConversionSequence::Indistinguishable;
2730}
2731
2732/// CompareQualificationConversions - Compares two standard conversion
2733/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002734/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2735ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002736CompareQualificationConversions(Sema &S,
2737 const StandardConversionSequence& SCS1,
2738 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002739 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002740 // -- S1 and S2 differ only in their qualification conversion and
2741 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2742 // cv-qualification signature of type T1 is a proper subset of
2743 // the cv-qualification signature of type T2, and S1 is not the
2744 // deprecated string literal array-to-pointer conversion (4.2).
2745 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2746 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2747 return ImplicitConversionSequence::Indistinguishable;
2748
2749 // FIXME: the example in the standard doesn't use a qualification
2750 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002751 QualType T1 = SCS1.getToType(2);
2752 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002753 T1 = S.Context.getCanonicalType(T1);
2754 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002755 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002756 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2757 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002758
2759 // If the types are the same, we won't learn anything by unwrapped
2760 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002761 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002762 return ImplicitConversionSequence::Indistinguishable;
2763
Chandler Carruth28e318c2009-12-29 07:16:59 +00002764 // If the type is an array type, promote the element qualifiers to the type
2765 // for comparison.
2766 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002767 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002768 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002769 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002770
Mike Stump1eb44332009-09-09 15:08:12 +00002771 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002772 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002773 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002774 // Within each iteration of the loop, we check the qualifiers to
2775 // determine if this still looks like a qualification
2776 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002777 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002778 // until there are no more pointers or pointers-to-members left
2779 // to unwrap. This essentially mimics what
2780 // IsQualificationConversion does, but here we're checking for a
2781 // strict subset of qualifiers.
2782 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2783 // The qualifiers are the same, so this doesn't tell us anything
2784 // about how the sequences rank.
2785 ;
2786 else if (T2.isMoreQualifiedThan(T1)) {
2787 // T1 has fewer qualifiers, so it could be the better sequence.
2788 if (Result == ImplicitConversionSequence::Worse)
2789 // Neither has qualifiers that are a subset of the other's
2790 // qualifiers.
2791 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Douglas Gregor57373262008-10-22 14:17:15 +00002793 Result = ImplicitConversionSequence::Better;
2794 } else if (T1.isMoreQualifiedThan(T2)) {
2795 // T2 has fewer qualifiers, so it could be the better sequence.
2796 if (Result == ImplicitConversionSequence::Better)
2797 // Neither has qualifiers that are a subset of the other's
2798 // qualifiers.
2799 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Douglas Gregor57373262008-10-22 14:17:15 +00002801 Result = ImplicitConversionSequence::Worse;
2802 } else {
2803 // Qualifiers are disjoint.
2804 return ImplicitConversionSequence::Indistinguishable;
2805 }
2806
2807 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002808 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002809 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002810 }
2811
Douglas Gregor57373262008-10-22 14:17:15 +00002812 // Check that the winning standard conversion sequence isn't using
2813 // the deprecated string literal array to pointer conversion.
2814 switch (Result) {
2815 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002816 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002817 Result = ImplicitConversionSequence::Indistinguishable;
2818 break;
2819
2820 case ImplicitConversionSequence::Indistinguishable:
2821 break;
2822
2823 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002824 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002825 Result = ImplicitConversionSequence::Indistinguishable;
2826 break;
2827 }
2828
2829 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002830}
2831
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002832/// CompareDerivedToBaseConversions - Compares two standard conversion
2833/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002834/// various kinds of derived-to-base conversions (C++
2835/// [over.ics.rank]p4b3). As part of these checks, we also look at
2836/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002837ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002838CompareDerivedToBaseConversions(Sema &S,
2839 const StandardConversionSequence& SCS1,
2840 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002841 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002842 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002843 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002844 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002845
2846 // Adjust the types we're converting from via the array-to-pointer
2847 // conversion, if we need to.
2848 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002849 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002850 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002851 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002852
2853 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002854 FromType1 = S.Context.getCanonicalType(FromType1);
2855 ToType1 = S.Context.getCanonicalType(ToType1);
2856 FromType2 = S.Context.getCanonicalType(FromType2);
2857 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002858
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002859 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002860 //
2861 // If class B is derived directly or indirectly from class A and
2862 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002863 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002864 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002865 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002866 SCS2.Second == ICK_Pointer_Conversion &&
2867 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2868 FromType1->isPointerType() && FromType2->isPointerType() &&
2869 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002870 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002871 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002872 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002873 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002874 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002875 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002876 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002877 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002878
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002879 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002880 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002881 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002882 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002883 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002884 return ImplicitConversionSequence::Worse;
2885 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002886
2887 // -- conversion of B* to A* is better than conversion of C* to A*,
2888 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002889 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002890 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002891 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002892 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00002893 }
2894 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2895 SCS2.Second == ICK_Pointer_Conversion) {
2896 const ObjCObjectPointerType *FromPtr1
2897 = FromType1->getAs<ObjCObjectPointerType>();
2898 const ObjCObjectPointerType *FromPtr2
2899 = FromType2->getAs<ObjCObjectPointerType>();
2900 const ObjCObjectPointerType *ToPtr1
2901 = ToType1->getAs<ObjCObjectPointerType>();
2902 const ObjCObjectPointerType *ToPtr2
2903 = ToType2->getAs<ObjCObjectPointerType>();
2904
2905 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2906 // Apply the same conversion ranking rules for Objective-C pointer types
2907 // that we do for C++ pointers to class types. However, we employ the
2908 // Objective-C pseudo-subtyping relationship used for assignment of
2909 // Objective-C pointer types.
2910 bool FromAssignLeft
2911 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2912 bool FromAssignRight
2913 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2914 bool ToAssignLeft
2915 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2916 bool ToAssignRight
2917 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2918
2919 // A conversion to an a non-id object pointer type or qualified 'id'
2920 // type is better than a conversion to 'id'.
2921 if (ToPtr1->isObjCIdType() &&
2922 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2923 return ImplicitConversionSequence::Worse;
2924 if (ToPtr2->isObjCIdType() &&
2925 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2926 return ImplicitConversionSequence::Better;
2927
2928 // A conversion to a non-id object pointer type is better than a
2929 // conversion to a qualified 'id' type
2930 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2931 return ImplicitConversionSequence::Worse;
2932 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2933 return ImplicitConversionSequence::Better;
2934
2935 // A conversion to an a non-Class object pointer type or qualified 'Class'
2936 // type is better than a conversion to 'Class'.
2937 if (ToPtr1->isObjCClassType() &&
2938 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2939 return ImplicitConversionSequence::Worse;
2940 if (ToPtr2->isObjCClassType() &&
2941 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2942 return ImplicitConversionSequence::Better;
2943
2944 // A conversion to a non-Class object pointer type is better than a
2945 // conversion to a qualified 'Class' type.
2946 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2947 return ImplicitConversionSequence::Worse;
2948 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2949 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Douglas Gregor395cc372011-01-31 18:51:41 +00002951 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2952 if (S.Context.hasSameType(FromType1, FromType2) &&
2953 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2954 (ToAssignLeft != ToAssignRight))
2955 return ToAssignLeft? ImplicitConversionSequence::Worse
2956 : ImplicitConversionSequence::Better;
2957
2958 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2959 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2960 (FromAssignLeft != FromAssignRight))
2961 return FromAssignLeft? ImplicitConversionSequence::Better
2962 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002963 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002964 }
Douglas Gregor395cc372011-01-31 18:51:41 +00002965
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002966 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002967 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2968 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2969 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002970 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002971 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002973 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002975 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002977 ToType2->getAs<MemberPointerType>();
2978 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2979 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2980 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2981 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2982 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2983 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2984 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2985 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002986 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002987 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002988 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002989 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002990 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002991 return ImplicitConversionSequence::Better;
2992 }
2993 // conversion of B::* to C::* is better than conversion of A::* to C::*
2994 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002995 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002996 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002997 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002998 return ImplicitConversionSequence::Worse;
2999 }
3000 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003001
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003002 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003003 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003004 // -- binding of an expression of type C to a reference of type
3005 // B& is better than binding an expression of type C to a
3006 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003007 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3008 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3009 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003010 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003011 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003012 return ImplicitConversionSequence::Worse;
3013 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003014
Douglas Gregor225c41e2008-11-03 19:09:14 +00003015 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003016 // -- binding of an expression of type B to a reference of type
3017 // A& is better than binding an expression of type C to a
3018 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003019 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3020 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3021 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003022 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003023 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003024 return ImplicitConversionSequence::Worse;
3025 }
3026 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003027
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003028 return ImplicitConversionSequence::Indistinguishable;
3029}
3030
Douglas Gregorabe183d2010-04-13 16:31:36 +00003031/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3032/// determine whether they are reference-related,
3033/// reference-compatible, reference-compatible with added
3034/// qualification, or incompatible, for use in C++ initialization by
3035/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3036/// type, and the first type (T1) is the pointee type of the reference
3037/// type being initialized.
3038Sema::ReferenceCompareResult
3039Sema::CompareReferenceRelationship(SourceLocation Loc,
3040 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003041 bool &DerivedToBase,
3042 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003043 assert(!OrigT1->isReferenceType() &&
3044 "T1 must be the pointee type of the reference type");
3045 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3046
3047 QualType T1 = Context.getCanonicalType(OrigT1);
3048 QualType T2 = Context.getCanonicalType(OrigT2);
3049 Qualifiers T1Quals, T2Quals;
3050 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3051 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3052
3053 // C++ [dcl.init.ref]p4:
3054 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3055 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3056 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003057 DerivedToBase = false;
3058 ObjCConversion = false;
3059 if (UnqualT1 == UnqualT2) {
3060 // Nothing to do.
3061 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003062 IsDerivedFrom(UnqualT2, UnqualT1))
3063 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003064 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3065 UnqualT2->isObjCObjectOrInterfaceType() &&
3066 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3067 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003068 else
3069 return Ref_Incompatible;
3070
3071 // At this point, we know that T1 and T2 are reference-related (at
3072 // least).
3073
3074 // If the type is an array type, promote the element qualifiers to the type
3075 // for comparison.
3076 if (isa<ArrayType>(T1) && T1Quals)
3077 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3078 if (isa<ArrayType>(T2) && T2Quals)
3079 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3080
3081 // C++ [dcl.init.ref]p4:
3082 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3083 // reference-related to T2 and cv1 is the same cv-qualification
3084 // as, or greater cv-qualification than, cv2. For purposes of
3085 // overload resolution, cases for which cv1 is greater
3086 // cv-qualification than cv2 are identified as
3087 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003088 //
3089 // Note that we also require equivalence of Objective-C GC and address-space
3090 // qualifiers when performing these computations, so that e.g., an int in
3091 // address space 1 is not reference-compatible with an int in address
3092 // space 2.
3093 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003094 return Ref_Compatible;
3095 else if (T1.isMoreQualifiedThan(T2))
3096 return Ref_Compatible_With_Added_Qualification;
3097 else
3098 return Ref_Related;
3099}
3100
Douglas Gregor604eb652010-08-11 02:15:33 +00003101/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003102/// with DeclType. Return true if something definite is found.
3103static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003104FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3105 QualType DeclType, SourceLocation DeclLoc,
3106 Expr *Init, QualType T2, bool AllowRvalues,
3107 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003108 assert(T2->isRecordType() && "Can only find conversions of record types.");
3109 CXXRecordDecl *T2RecordDecl
3110 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3111
3112 OverloadCandidateSet CandidateSet(DeclLoc);
3113 const UnresolvedSetImpl *Conversions
3114 = T2RecordDecl->getVisibleConversionFunctions();
3115 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3116 E = Conversions->end(); I != E; ++I) {
3117 NamedDecl *D = *I;
3118 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3119 if (isa<UsingShadowDecl>(D))
3120 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3121
3122 FunctionTemplateDecl *ConvTemplate
3123 = dyn_cast<FunctionTemplateDecl>(D);
3124 CXXConversionDecl *Conv;
3125 if (ConvTemplate)
3126 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3127 else
3128 Conv = cast<CXXConversionDecl>(D);
3129
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003130 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003131 // explicit conversions, skip it.
3132 if (!AllowExplicit && Conv->isExplicit())
3133 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134
Douglas Gregor604eb652010-08-11 02:15:33 +00003135 if (AllowRvalues) {
3136 bool DerivedToBase = false;
3137 bool ObjCConversion = false;
3138 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003139 S.CompareReferenceRelationship(
3140 DeclLoc,
3141 Conv->getConversionType().getNonReferenceType()
3142 .getUnqualifiedType(),
3143 DeclType.getNonReferenceType().getUnqualifiedType(),
3144 DerivedToBase, ObjCConversion) ==
3145 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003146 continue;
3147 } else {
3148 // If the conversion function doesn't return a reference type,
3149 // it can't be considered for this conversion. An rvalue reference
3150 // is only acceptable if its referencee is a function type.
3151
3152 const ReferenceType *RefType =
3153 Conv->getConversionType()->getAs<ReferenceType>();
3154 if (!RefType ||
3155 (!RefType->isLValueReferenceType() &&
3156 !RefType->getPointeeType()->isFunctionType()))
3157 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregor604eb652010-08-11 02:15:33 +00003160 if (ConvTemplate)
3161 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003162 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003163 else
3164 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003165 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003166 }
3167
3168 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003169 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003170 case OR_Success:
3171 // C++ [over.ics.ref]p1:
3172 //
3173 // [...] If the parameter binds directly to the result of
3174 // applying a conversion function to the argument
3175 // expression, the implicit conversion sequence is a
3176 // user-defined conversion sequence (13.3.3.1.2), with the
3177 // second standard conversion sequence either an identity
3178 // conversion or, if the conversion function returns an
3179 // entity of a type that is a derived class of the parameter
3180 // type, a derived-to-base Conversion.
3181 if (!Best->FinalConversion.DirectBinding)
3182 return false;
3183
Chandler Carruth25ca4212011-02-25 19:41:05 +00003184 if (Best->Function)
3185 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003186 ICS.setUserDefined();
3187 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3188 ICS.UserDefined.After = Best->FinalConversion;
3189 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00003190 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redl4680bf22010-06-30 18:13:39 +00003191 ICS.UserDefined.EllipsisConversion = false;
3192 assert(ICS.UserDefined.After.ReferenceBinding &&
3193 ICS.UserDefined.After.DirectBinding &&
3194 "Expected a direct reference binding!");
3195 return true;
3196
3197 case OR_Ambiguous:
3198 ICS.setAmbiguous();
3199 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3200 Cand != CandidateSet.end(); ++Cand)
3201 if (Cand->Viable)
3202 ICS.Ambiguous.addConversion(Cand->Function);
3203 return true;
3204
3205 case OR_No_Viable_Function:
3206 case OR_Deleted:
3207 // There was no suitable conversion, or we found a deleted
3208 // conversion; continue with other checks.
3209 return false;
3210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
Eric Christopher1c3d5022010-06-30 18:36:32 +00003212 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003213}
3214
Douglas Gregorabe183d2010-04-13 16:31:36 +00003215/// \brief Compute an implicit conversion sequence for reference
3216/// initialization.
3217static ImplicitConversionSequence
3218TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3219 SourceLocation DeclLoc,
3220 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003221 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003222 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3223
3224 // Most paths end in a failed conversion.
3225 ImplicitConversionSequence ICS;
3226 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3227
3228 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3229 QualType T2 = Init->getType();
3230
3231 // If the initializer is the address of an overloaded function, try
3232 // to resolve the overloaded function. If all goes well, T2 is the
3233 // type of the resulting function.
3234 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3235 DeclAccessPair Found;
3236 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3237 false, Found))
3238 T2 = Fn->getType();
3239 }
3240
3241 // Compute some basic properties of the types and the initializer.
3242 bool isRValRef = DeclType->isRValueReferenceType();
3243 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003244 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003245 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003246 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003247 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3248 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003249
Douglas Gregorabe183d2010-04-13 16:31:36 +00003250
Sebastian Redl4680bf22010-06-30 18:13:39 +00003251 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003252 // A reference to type "cv1 T1" is initialized by an expression
3253 // of type "cv2 T2" as follows:
3254
Sebastian Redl4680bf22010-06-30 18:13:39 +00003255 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003256 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003257 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3258 // reference-compatible with "cv2 T2," or
3259 //
3260 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3261 if (InitCategory.isLValue() &&
3262 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003263 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003264 // When a parameter of reference type binds directly (8.5.3)
3265 // to an argument expression, the implicit conversion sequence
3266 // is the identity conversion, unless the argument expression
3267 // has a type that is a derived class of the parameter type,
3268 // in which case the implicit conversion sequence is a
3269 // derived-to-base Conversion (13.3.3.1).
3270 ICS.setStandard();
3271 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003272 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3273 : ObjCConversion? ICK_Compatible_Conversion
3274 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003275 ICS.Standard.Third = ICK_Identity;
3276 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3277 ICS.Standard.setToType(0, T2);
3278 ICS.Standard.setToType(1, T1);
3279 ICS.Standard.setToType(2, T1);
3280 ICS.Standard.ReferenceBinding = true;
3281 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003282 ICS.Standard.IsLvalueReference = !isRValRef;
3283 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3284 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003285 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003286 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003287
Sebastian Redl4680bf22010-06-30 18:13:39 +00003288 // Nothing more to do: the inaccessibility/ambiguity check for
3289 // derived-to-base conversions is suppressed when we're
3290 // computing the implicit conversion sequence (C++
3291 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003292 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003293 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003294
Sebastian Redl4680bf22010-06-30 18:13:39 +00003295 // -- has a class type (i.e., T2 is a class type), where T1 is
3296 // not reference-related to T2, and can be implicitly
3297 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3298 // is reference-compatible with "cv3 T3" 92) (this
3299 // conversion is selected by enumerating the applicable
3300 // conversion functions (13.3.1.6) and choosing the best
3301 // one through overload resolution (13.3)),
3302 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003304 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003305 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3306 Init, T2, /*AllowRvalues=*/false,
3307 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003308 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003309 }
3310 }
3311
Sebastian Redl4680bf22010-06-30 18:13:39 +00003312 // -- Otherwise, the reference shall be an lvalue reference to a
3313 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003314 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003316 // We actually handle one oddity of C++ [over.ics.ref] at this
3317 // point, which is that, due to p2 (which short-circuits reference
3318 // binding by only attempting a simple conversion for non-direct
3319 // bindings) and p3's strange wording, we allow a const volatile
3320 // reference to bind to an rvalue. Hence the check for the presence
3321 // of "const" rather than checking for "const" being the only
3322 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003323 // This is also the point where rvalue references and lvalue inits no longer
3324 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003325 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003326 return ICS;
3327
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003328 // -- If the initializer expression
3329 //
3330 // -- is an xvalue, class prvalue, array prvalue or function
3331 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3332 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3333 (InitCategory.isXValue() ||
3334 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3335 (InitCategory.isLValue() && T2->isFunctionType()))) {
3336 ICS.setStandard();
3337 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003339 : ObjCConversion? ICK_Compatible_Conversion
3340 : ICK_Identity;
3341 ICS.Standard.Third = ICK_Identity;
3342 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3343 ICS.Standard.setToType(0, T2);
3344 ICS.Standard.setToType(1, T1);
3345 ICS.Standard.setToType(2, T1);
3346 ICS.Standard.ReferenceBinding = true;
3347 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3348 // binding unless we're binding to a class prvalue.
3349 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3350 // allow the use of rvalue references in C++98/03 for the benefit of
3351 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003352 ICS.Standard.DirectBinding =
3353 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003354 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003355 ICS.Standard.IsLvalueReference = !isRValRef;
3356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003359 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003363 // -- has a class type (i.e., T2 is a class type), where T1 is not
3364 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365 // an xvalue, class prvalue, or function lvalue of type
3366 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003367 // "cv3 T3",
3368 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003370 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003372 // class subobject).
3373 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003375 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3376 Init, T2, /*AllowRvalues=*/true,
3377 AllowExplicit)) {
3378 // In the second case, if the reference is an rvalue reference
3379 // and the second standard conversion sequence of the
3380 // user-defined conversion sequence includes an lvalue-to-rvalue
3381 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003383 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3384 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3385
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003386 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregorabe183d2010-04-13 16:31:36 +00003389 // -- Otherwise, a temporary of type "cv1 T1" is created and
3390 // initialized from the initializer expression using the
3391 // rules for a non-reference copy initialization (8.5). The
3392 // reference is then bound to the temporary. If T1 is
3393 // reference-related to T2, cv1 must be the same
3394 // cv-qualification as, or greater cv-qualification than,
3395 // cv2; otherwise, the program is ill-formed.
3396 if (RefRelationship == Sema::Ref_Related) {
3397 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3398 // we would be reference-compatible or reference-compatible with
3399 // added qualification. But that wasn't the case, so the reference
3400 // initialization fails.
3401 return ICS;
3402 }
3403
3404 // If at least one of the types is a class type, the types are not
3405 // related, and we aren't allowed any user conversions, the
3406 // reference binding fails. This case is important for breaking
3407 // recursion, since TryImplicitConversion below will attempt to
3408 // create a temporary through the use of a copy constructor.
3409 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3410 (T1->isRecordType() || T2->isRecordType()))
3411 return ICS;
3412
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003413 // If T1 is reference-related to T2 and the reference is an rvalue
3414 // reference, the initializer expression shall not be an lvalue.
3415 if (RefRelationship >= Sema::Ref_Related &&
3416 isRValRef && Init->Classify(S.Context).isLValue())
3417 return ICS;
3418
Douglas Gregorabe183d2010-04-13 16:31:36 +00003419 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003420 // When a parameter of reference type is not bound directly to
3421 // an argument expression, the conversion sequence is the one
3422 // required to convert the argument expression to the
3423 // underlying type of the reference according to
3424 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3425 // to copy-initializing a temporary of the underlying type with
3426 // the argument expression. Any difference in top-level
3427 // cv-qualification is subsumed by the initialization itself
3428 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003429 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3430 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003431 /*InOverloadResolution=*/false,
3432 /*CStyle=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003433
3434 // Of course, that's still a reference binding.
3435 if (ICS.isStandard()) {
3436 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003437 ICS.Standard.IsLvalueReference = !isRValRef;
3438 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3439 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003440 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003441 } else if (ICS.isUserDefined()) {
3442 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003443 ICS.Standard.IsLvalueReference = !isRValRef;
3444 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3445 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003446 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003447 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003448
Douglas Gregorabe183d2010-04-13 16:31:36 +00003449 return ICS;
3450}
3451
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003452/// TryCopyInitialization - Try to copy-initialize a value of type
3453/// ToType from the expression From. Return the implicit conversion
3454/// sequence required to pass this argument, which may be a bad
3455/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003456/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003457/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003458static ImplicitConversionSequence
3459TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003460 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003461 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003462 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003463 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003464 /*FIXME:*/From->getLocStart(),
3465 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003466 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003467
John McCall120d63c2010-08-24 20:38:10 +00003468 return TryImplicitConversion(S, From, ToType,
3469 SuppressUserConversions,
3470 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003471 InOverloadResolution,
3472 /*CStyle=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003473}
3474
Douglas Gregor96176b32008-11-18 23:14:02 +00003475/// TryObjectArgumentInitialization - Try to initialize the object
3476/// parameter of the given member function (@c Method) from the
3477/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003478static ImplicitConversionSequence
3479TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003480 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003481 CXXMethodDecl *Method,
3482 CXXRecordDecl *ActingContext) {
3483 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003484 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3485 // const volatile object.
3486 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3487 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003488 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003489
3490 // Set up the conversion sequence as a "bad" conversion, to allow us
3491 // to exit early.
3492 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003493
3494 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003495 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003496 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003497 FromType = PT->getPointeeType();
3498
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003499 // When we had a pointer, it's implicitly dereferenced, so we
3500 // better have an lvalue.
3501 assert(FromClassification.isLValue());
3502 }
3503
Anders Carlssona552f7c2009-05-01 18:34:30 +00003504 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003505
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003506 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003508 // parameter is
3509 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003510 // - "lvalue reference to cv X" for functions declared without a
3511 // ref-qualifier or with the & ref-qualifier
3512 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003513 // ref-qualifier
3514 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003516 // cv-qualification on the member function declaration.
3517 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003519 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003520 // (C++ [over.match.funcs]p5). We perform a simplified version of
3521 // reference binding here, that allows class rvalues to bind to
3522 // non-constant references.
3523
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003524 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003525 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00003527 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003528 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003529 ICS.setBad(BadConversionSequence::bad_qualifiers,
3530 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003531 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003532 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003533
3534 // Check that we have either the same type or a derived type. It
3535 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003536 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003537 ImplicitConversionKind SecondKind;
3538 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3539 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003540 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003541 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003542 else {
John McCallb1bdc622010-02-25 01:37:24 +00003543 ICS.setBad(BadConversionSequence::unrelated_class,
3544 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003545 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003546 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003547
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003548 // Check the ref-qualifier.
3549 switch (Method->getRefQualifier()) {
3550 case RQ_None:
3551 // Do nothing; we don't care about lvalueness or rvalueness.
3552 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003554 case RQ_LValue:
3555 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3556 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003558 ImplicitParamType);
3559 return ICS;
3560 }
3561 break;
3562
3563 case RQ_RValue:
3564 if (!FromClassification.isRValue()) {
3565 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003567 ImplicitParamType);
3568 return ICS;
3569 }
3570 break;
3571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Douglas Gregor96176b32008-11-18 23:14:02 +00003573 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003574 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003575 ICS.Standard.setAsIdentityConversion();
3576 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003577 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003578 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003579 ICS.Standard.ReferenceBinding = true;
3580 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00003582 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003583 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3584 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3585 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00003586 return ICS;
3587}
3588
3589/// PerformObjectArgumentInitialization - Perform initialization of
3590/// the implicit object parameter for the given Method with the given
3591/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00003592ExprResult
3593Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003595 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003596 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003597 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003598 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003599 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003601 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00003602 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003603 FromRecordType = PT->getPointeeType();
3604 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003605 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00003606 } else {
3607 FromRecordType = From->getType();
3608 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003609 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00003610 }
3611
John McCall701c89e2009-12-03 04:06:58 +00003612 // Note that we always use the true parent context when performing
3613 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003614 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003615 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3616 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003617 if (ICS.isBad()) {
3618 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3619 Qualifiers FromQs = FromRecordType.getQualifiers();
3620 Qualifiers ToQs = DestType.getQualifiers();
3621 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3622 if (CVR) {
3623 Diag(From->getSourceRange().getBegin(),
3624 diag::err_member_function_call_bad_cvr)
3625 << Method->getDeclName() << FromRecordType << (CVR - 1)
3626 << From->getSourceRange();
3627 Diag(Method->getLocation(), diag::note_previous_decl)
3628 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00003629 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003630 }
3631 }
3632
Douglas Gregor96176b32008-11-18 23:14:02 +00003633 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003634 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003635 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003636 }
Mike Stump1eb44332009-09-09 15:08:12 +00003637
John Wiegley429bb272011-04-08 18:41:53 +00003638 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3639 ExprResult FromRes =
3640 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3641 if (FromRes.isInvalid())
3642 return ExprError();
3643 From = FromRes.take();
3644 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003645
Douglas Gregor5fccd362010-03-03 23:55:11 +00003646 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00003647 From = ImpCastExprToType(From, DestType, CK_NoOp,
3648 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3649 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00003650}
3651
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003652/// TryContextuallyConvertToBool - Attempt to contextually convert the
3653/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003654static ImplicitConversionSequence
3655TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003656 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003657 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003658 // FIXME: Are these flags correct?
3659 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003660 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003661 /*InOverloadResolution=*/false,
3662 /*CStyle=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003663}
3664
3665/// PerformContextuallyConvertToBool - Perform a contextual conversion
3666/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00003667ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00003668 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003669 if (!ICS.isBad())
3670 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003672 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00003673 return Diag(From->getSourceRange().getBegin(),
3674 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003675 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003676 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003677}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003679/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3680/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003681static ImplicitConversionSequence
3682TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3683 QualType Ty = S.Context.getObjCIdType();
3684 return TryImplicitConversion(S, From, Ty,
3685 // FIXME: Are these flags correct?
3686 /*SuppressUserConversions=*/false,
3687 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003688 /*InOverloadResolution=*/false,
3689 /*CStyle=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003690}
John McCall120d63c2010-08-24 20:38:10 +00003691
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003692/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3693/// of the expression From to 'id'.
John Wiegley429bb272011-04-08 18:41:53 +00003694ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003695 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003696 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003697 if (!ICS.isBad())
3698 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00003699 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003700}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003701
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00003703/// enumeration type.
3704///
3705/// This routine will attempt to convert an expression of class type to an
3706/// integral or enumeration type, if that class type only has a single
3707/// conversion to an integral or enumeration type.
3708///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003709/// \param Loc The source location of the construct that requires the
3710/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003711///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003712/// \param FromE The expression we're converting from.
3713///
3714/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3715/// have integral or enumeration type.
3716///
3717/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3718/// incomplete class type.
3719///
3720/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3721/// explicit conversion function (because no implicit conversion functions
3722/// were available). This is a recovery mode.
3723///
3724/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3725/// showing which conversion was picked.
3726///
3727/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3728/// conversion function that could convert to integral or enumeration type.
3729///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003731/// usable conversion function.
3732///
3733/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3734/// function, which may be an extension in this case.
3735///
3736/// \returns The expression, converted to an integral or enumeration type if
3737/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003739Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003740 const PartialDiagnostic &NotIntDiag,
3741 const PartialDiagnostic &IncompleteDiag,
3742 const PartialDiagnostic &ExplicitConvDiag,
3743 const PartialDiagnostic &ExplicitConvNote,
3744 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003745 const PartialDiagnostic &AmbigNote,
3746 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003747 // We can't perform any more checking for type-dependent expressions.
3748 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003749 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750
Douglas Gregorc30614b2010-06-29 23:17:37 +00003751 // If the expression already has integral or enumeration type, we're golden.
3752 QualType T = From->getType();
3753 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003754 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003755
3756 // FIXME: Check for missing '()' if T is a function type?
3757
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758 // 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 +00003759 // expression of integral or enumeration type.
3760 const RecordType *RecordTy = T->getAs<RecordType>();
3761 if (!RecordTy || !getLangOptions().CPlusPlus) {
3762 Diag(Loc, NotIntDiag)
3763 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003764 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003765 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003766
Douglas Gregorc30614b2010-06-29 23:17:37 +00003767 // We must have a complete class type.
3768 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003769 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
Douglas Gregorc30614b2010-06-29 23:17:37 +00003771 // Look for a conversion to an integral or enumeration type.
3772 UnresolvedSet<4> ViableConversions;
3773 UnresolvedSet<4> ExplicitConversions;
3774 const UnresolvedSetImpl *Conversions
3775 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776
Douglas Gregorc30614b2010-06-29 23:17:37 +00003777 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 E = Conversions->end();
3779 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00003780 ++I) {
3781 if (CXXConversionDecl *Conversion
3782 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3783 if (Conversion->getConversionType().getNonReferenceType()
3784 ->isIntegralOrEnumerationType()) {
3785 if (Conversion->isExplicit())
3786 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3787 else
3788 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3789 }
3790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791
Douglas Gregorc30614b2010-06-29 23:17:37 +00003792 switch (ViableConversions.size()) {
3793 case 0:
3794 if (ExplicitConversions.size() == 1) {
3795 DeclAccessPair Found = ExplicitConversions[0];
3796 CXXConversionDecl *Conversion
3797 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
Douglas Gregorc30614b2010-06-29 23:17:37 +00003799 // The user probably meant to invoke the given explicit
3800 // conversion; use it.
3801 QualType ConvTy
3802 = Conversion->getConversionType().getNonReferenceType();
3803 std::string TypeStr;
3804 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805
Douglas Gregorc30614b2010-06-29 23:17:37 +00003806 Diag(Loc, ExplicitConvDiag)
3807 << T << ConvTy
3808 << FixItHint::CreateInsertion(From->getLocStart(),
3809 "static_cast<" + TypeStr + ">(")
3810 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3811 ")");
3812 Diag(Conversion->getLocation(), ExplicitConvNote)
3813 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
3815 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00003816 // explicit conversion function.
3817 if (isSFINAEContext())
3818 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819
Douglas Gregorc30614b2010-06-29 23:17:37 +00003820 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003821 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3822 if (Result.isInvalid())
3823 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003825 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Douglas Gregorc30614b2010-06-29 23:17:37 +00003828 // We'll complain below about a non-integral condition type.
3829 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003830
Douglas Gregorc30614b2010-06-29 23:17:37 +00003831 case 1: {
3832 // Apply this conversion.
3833 DeclAccessPair Found = ViableConversions[0];
3834 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003836 CXXConversionDecl *Conversion
3837 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3838 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003839 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003840 if (ConvDiag.getDiagID()) {
3841 if (isSFINAEContext())
3842 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003844 Diag(Loc, ConvDiag)
3845 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003848 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003849 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003850 if (Result.isInvalid())
3851 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003853 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003854 break;
3855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003856
Douglas Gregorc30614b2010-06-29 23:17:37 +00003857 default:
3858 Diag(Loc, AmbigDiag)
3859 << T << From->getSourceRange();
3860 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3861 CXXConversionDecl *Conv
3862 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3863 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3864 Diag(Conv->getLocation(), AmbigNote)
3865 << ConvTy->isEnumeralType() << ConvTy;
3866 }
John McCall9ae2f072010-08-23 23:25:46 +00003867 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003868 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003869
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003870 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003871 Diag(Loc, NotIntDiag)
3872 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003873
John McCall9ae2f072010-08-23 23:25:46 +00003874 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003875}
3876
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003877/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003878/// candidate functions, using the given function call arguments. If
3879/// @p SuppressUserConversions, then don't allow user-defined
3880/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003881///
3882/// \para PartialOverloading true if we are performing "partial" overloading
3883/// based on an incomplete set of function arguments. This feature is used by
3884/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003885void
3886Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003887 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003888 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003889 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003890 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003891 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003892 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003893 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003894 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003895 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003896 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Douglas Gregor88a35142008-12-22 05:46:06 +00003898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003899 if (!isa<CXXConstructorDecl>(Method)) {
3900 // If we get here, it's because we're calling a member function
3901 // that is named without a member access expression (e.g.,
3902 // "this->f") that was either written explicitly or created
3903 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003904 // function, e.g., X::f(). We use an empty type for the implied
3905 // object argument (C++ [over.call.func]p3), and the acting context
3906 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003907 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003909 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003910 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003911 return;
3912 }
3913 // We treat a constructor like a non-member function, since its object
3914 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003915 }
3916
Douglas Gregorfd476482009-11-13 23:59:09 +00003917 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003918 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003919
Douglas Gregor7edfb692009-11-23 12:27:39 +00003920 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003921 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003922
Douglas Gregor66724ea2009-11-14 01:20:54 +00003923 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3924 // C++ [class.copy]p3:
3925 // A member function template is never instantiated to perform the copy
3926 // of a class object to an object of its class type.
3927 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003929 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003930 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3931 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003932 return;
3933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003934
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003935 // Add this candidate
3936 CandidateSet.push_back(OverloadCandidate());
3937 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003938 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003939 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003940 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003941 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003942 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003943 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003945 unsigned NumArgsInProto = Proto->getNumArgs();
3946
3947 // (C++ 13.3.2p2): A candidate function having fewer than m
3948 // parameters is viable only if it has an ellipsis in its parameter
3949 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003950 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003951 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003952 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003953 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003954 return;
3955 }
3956
3957 // (C++ 13.3.2p2): A candidate function having more than m parameters
3958 // is viable only if the (m+1)st parameter has a default argument
3959 // (8.3.6). For the purposes of overload resolution, the
3960 // parameter list is truncated on the right, so that there are
3961 // exactly m parameters.
3962 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003963 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003964 // Not enough arguments.
3965 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003966 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003967 return;
3968 }
3969
3970 // Determine the implicit conversion sequences for each of the
3971 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003972 Candidate.Conversions.resize(NumArgs);
3973 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3974 if (ArgIdx < NumArgsInProto) {
3975 // (C++ 13.3.2p3): for F to be a viable function, there shall
3976 // exist for each argument an implicit conversion sequence
3977 // (13.3.3.1) that converts that argument to the corresponding
3978 // parameter of F.
3979 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003980 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003981 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003983 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003984 if (Candidate.Conversions[ArgIdx].isBad()) {
3985 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003986 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003987 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003988 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003989 } else {
3990 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3991 // argument for which there is no corresponding parameter is
3992 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003993 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003994 }
3995 }
3996}
3997
Douglas Gregor063daf62009-03-13 18:40:31 +00003998/// \brief Add all of the function declarations in the given function set to
3999/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004000void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004001 Expr **Args, unsigned NumArgs,
4002 OverloadCandidateSet& CandidateSet,
4003 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004004 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004005 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4006 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004007 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004008 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004009 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004010 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004012 CandidateSet, SuppressUserConversions);
4013 else
John McCall9aa472c2010-03-19 07:35:19 +00004014 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004015 SuppressUserConversions);
4016 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004017 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004018 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4019 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004020 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004021 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004022 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004023 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004024 Args[0]->Classify(Context),
4025 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004026 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004027 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004028 else
John McCall9aa472c2010-03-19 07:35:19 +00004029 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004030 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004031 Args, NumArgs, CandidateSet,
4032 SuppressUserConversions);
4033 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004034 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004035}
4036
John McCall314be4e2009-11-17 07:50:12 +00004037/// AddMethodCandidate - Adds a named decl (which is some kind of
4038/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004039void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004040 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004041 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004042 Expr **Args, unsigned NumArgs,
4043 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004044 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004045 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004046 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004047
4048 if (isa<UsingShadowDecl>(Decl))
4049 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050
John McCall314be4e2009-11-17 07:50:12 +00004051 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4052 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4053 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004054 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4055 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004056 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004057 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004058 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004059 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004060 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004061 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004062 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004063 }
4064}
4065
Douglas Gregor96176b32008-11-18 23:14:02 +00004066/// AddMethodCandidate - Adds the given C++ member function to the set
4067/// of candidate functions, using the given function call arguments
4068/// and the object argument (@c Object). For example, in a call
4069/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4070/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4071/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004072/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004073void
John McCall9aa472c2010-03-19 07:35:19 +00004074Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004075 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004076 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004077 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004078 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004079 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004080 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004081 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004082 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004083 assert(!isa<CXXConstructorDecl>(Method) &&
4084 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004085
Douglas Gregor3f396022009-09-28 04:47:19 +00004086 if (!CandidateSet.isNewCandidate(Method))
4087 return;
4088
Douglas Gregor7edfb692009-11-23 12:27:39 +00004089 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004090 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004091
Douglas Gregor96176b32008-11-18 23:14:02 +00004092 // Add this candidate
4093 CandidateSet.push_back(OverloadCandidate());
4094 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004095 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004096 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004097 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004098 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004099 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004100
4101 unsigned NumArgsInProto = Proto->getNumArgs();
4102
4103 // (C++ 13.3.2p2): A candidate function having fewer than m
4104 // parameters is viable only if it has an ellipsis in its parameter
4105 // list (8.3.5).
4106 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4107 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004108 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004109 return;
4110 }
4111
4112 // (C++ 13.3.2p2): A candidate function having more than m parameters
4113 // is viable only if the (m+1)st parameter has a default argument
4114 // (8.3.6). For the purposes of overload resolution, the
4115 // parameter list is truncated on the right, so that there are
4116 // exactly m parameters.
4117 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4118 if (NumArgs < MinRequiredArgs) {
4119 // Not enough arguments.
4120 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004121 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004122 return;
4123 }
4124
4125 Candidate.Viable = true;
4126 Candidate.Conversions.resize(NumArgs + 1);
4127
John McCall701c89e2009-12-03 04:06:58 +00004128 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004129 // The implicit object argument is ignored.
4130 Candidate.IgnoreObjectArgument = true;
4131 else {
4132 // Determine the implicit conversion sequence for the object
4133 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004134 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004135 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4136 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004137 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004139 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004140 return;
4141 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004142 }
4143
4144 // Determine the implicit conversion sequences for each of the
4145 // arguments.
4146 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4147 if (ArgIdx < NumArgsInProto) {
4148 // (C++ 13.3.2p3): for F to be a viable function, there shall
4149 // exist for each argument an implicit conversion sequence
4150 // (13.3.3.1) that converts that argument to the corresponding
4151 // parameter of F.
4152 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004153 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004154 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004155 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00004156 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00004157 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004158 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004159 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004160 break;
4161 }
4162 } else {
4163 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4164 // argument for which there is no corresponding parameter is
4165 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004166 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004167 }
4168 }
4169}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170
Douglas Gregor6b906862009-08-21 00:16:32 +00004171/// \brief Add a C++ member function template as a candidate to the candidate
4172/// set, using template argument deduction to produce an appropriate member
4173/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004174void
Douglas Gregor6b906862009-08-21 00:16:32 +00004175Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004176 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004177 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004178 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004179 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004180 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004181 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004182 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004183 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004184 if (!CandidateSet.isNewCandidate(MethodTmpl))
4185 return;
4186
Douglas Gregor6b906862009-08-21 00:16:32 +00004187 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004188 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004189 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004190 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004191 // candidate functions in the usual way.113) A given name can refer to one
4192 // or more function templates and also to a set of overloaded non-template
4193 // functions. In such a case, the candidate functions generated from each
4194 // function template are combined with the set of non-template candidate
4195 // functions.
John McCall5769d612010-02-08 23:07:23 +00004196 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004197 FunctionDecl *Specialization = 0;
4198 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004199 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004200 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004201 CandidateSet.push_back(OverloadCandidate());
4202 OverloadCandidate &Candidate = CandidateSet.back();
4203 Candidate.FoundDecl = FoundDecl;
4204 Candidate.Function = MethodTmpl->getTemplatedDecl();
4205 Candidate.Viable = false;
4206 Candidate.FailureKind = ovl_fail_bad_deduction;
4207 Candidate.IsSurrogate = false;
4208 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004209 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004211 Info);
4212 return;
4213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Douglas Gregor6b906862009-08-21 00:16:32 +00004215 // Add the function template specialization produced by template argument
4216 // deduction as a candidate.
4217 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004218 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004219 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004220 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004221 ActingContext, ObjectType, ObjectClassification,
4222 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004223}
4224
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004225/// \brief Add a C++ function template specialization as a candidate
4226/// in the candidate set, using template argument deduction to produce
4227/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004228void
Douglas Gregore53060f2009-06-25 22:08:12 +00004229Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004230 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004231 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004232 Expr **Args, unsigned NumArgs,
4233 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004234 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004235 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4236 return;
4237
Douglas Gregore53060f2009-06-25 22:08:12 +00004238 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004239 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004240 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004241 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004242 // candidate functions in the usual way.113) A given name can refer to one
4243 // or more function templates and also to a set of overloaded non-template
4244 // functions. In such a case, the candidate functions generated from each
4245 // function template are combined with the set of non-template candidate
4246 // functions.
John McCall5769d612010-02-08 23:07:23 +00004247 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004248 FunctionDecl *Specialization = 0;
4249 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004250 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004251 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004252 CandidateSet.push_back(OverloadCandidate());
4253 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004254 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004255 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4256 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004257 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004258 Candidate.IsSurrogate = false;
4259 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004260 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004262 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004263 return;
4264 }
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Douglas Gregore53060f2009-06-25 22:08:12 +00004266 // Add the function template specialization produced by template argument
4267 // deduction as a candidate.
4268 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004269 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004270 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004271}
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004273/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004274/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004275/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004276/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004277/// (which may or may not be the same type as the type that the
4278/// conversion function produces).
4279void
4280Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004281 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004282 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004283 Expr *From, QualType ToType,
4284 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004285 assert(!Conversion->getDescribedFunctionTemplate() &&
4286 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004287 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004288 if (!CandidateSet.isNewCandidate(Conversion))
4289 return;
4290
Douglas Gregor7edfb692009-11-23 12:27:39 +00004291 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004292 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004293
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004294 // Add this candidate
4295 CandidateSet.push_back(OverloadCandidate());
4296 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004297 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004298 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004299 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004300 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004301 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004302 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004303 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004304 Candidate.Viable = true;
4305 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004306 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004307
Douglas Gregorbca39322010-08-19 15:37:02 +00004308 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309 // For conversion functions, the function is considered to be a member of
4310 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004311 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004312 //
4313 // Determine the implicit conversion sequence for the implicit
4314 // object parameter.
4315 QualType ImplicitParamType = From->getType();
4316 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4317 ImplicitParamType = FromPtrType->getPointeeType();
4318 CXXRecordDecl *ConversionContext
4319 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004320
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004321 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004322 = TryObjectArgumentInitialization(*this, From->getType(),
4323 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004324 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325
John McCall1d318332010-01-12 00:44:57 +00004326 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004327 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004328 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004329 return;
4330 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004331
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004333 // derived to base as such conversions are given Conversion Rank. They only
4334 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4335 QualType FromCanon
4336 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4337 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4338 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4339 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004340 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004341 return;
4342 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004344 // To determine what the conversion from the result of calling the
4345 // conversion function to the type we're eventually trying to
4346 // convert to (ToType), we need to synthesize a call to the
4347 // conversion function and attempt copy initialization from it. This
4348 // makes sure that we get the right semantics with respect to
4349 // lvalues/rvalues and the type. Fortunately, we can allocate this
4350 // call on the stack and we don't need its arguments to be
4351 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004352 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004353 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004354 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4355 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004356 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004357 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Douglas Gregor7d14d382010-11-13 19:36:57 +00004359 QualType CallResultType
4360 = Conversion->getConversionType().getNonLValueExprType(Context);
4361 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4362 Candidate.Viable = false;
4363 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4364 return;
4365 }
4366
John McCallf89e55a2010-11-18 06:31:45 +00004367 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4368
Mike Stump1eb44332009-09-09 15:08:12 +00004369 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004370 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4371 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00004372 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004373 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004374 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004375 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004376 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004377 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004378
John McCall1d318332010-01-12 00:44:57 +00004379 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004380 case ImplicitConversionSequence::StandardConversion:
4381 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregorc520c842010-04-12 23:42:09 +00004383 // C++ [over.ics.user]p3:
4384 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004385 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00004386 // shall have exact match rank.
4387 if (Conversion->getPrimaryTemplate() &&
4388 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4389 Candidate.Viable = false;
4390 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004392
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004393 // C++0x [dcl.init.ref]p5:
4394 // In the second case, if the reference is an rvalue reference and
4395 // the second standard conversion sequence of the user-defined
4396 // conversion sequence includes an lvalue-to-rvalue conversion, the
4397 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004398 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004399 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4400 Candidate.Viable = false;
4401 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4402 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004403 break;
4404
4405 case ImplicitConversionSequence::BadConversion:
4406 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004407 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004408 break;
4409
4410 default:
Mike Stump1eb44332009-09-09 15:08:12 +00004411 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004412 "Can only end up with a standard conversion sequence or failure");
4413 }
4414}
4415
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004416/// \brief Adds a conversion function template specialization
4417/// candidate to the overload set, using template argument deduction
4418/// to deduce the template arguments of the conversion function
4419/// template from the type that we are converting to (C++
4420/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004421void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004422Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004423 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004424 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004425 Expr *From, QualType ToType,
4426 OverloadCandidateSet &CandidateSet) {
4427 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4428 "Only conversion function templates permitted here");
4429
Douglas Gregor3f396022009-09-28 04:47:19 +00004430 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4431 return;
4432
John McCall5769d612010-02-08 23:07:23 +00004433 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004434 CXXConversionDecl *Specialization = 0;
4435 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004436 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004437 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004438 CandidateSet.push_back(OverloadCandidate());
4439 OverloadCandidate &Candidate = CandidateSet.back();
4440 Candidate.FoundDecl = FoundDecl;
4441 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4442 Candidate.Viable = false;
4443 Candidate.FailureKind = ovl_fail_bad_deduction;
4444 Candidate.IsSurrogate = false;
4445 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004446 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004448 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004449 return;
4450 }
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004452 // Add the conversion function template specialization produced by
4453 // template argument deduction as a candidate.
4454 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004455 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004456 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004457}
4458
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004459/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4460/// converts the given @c Object to a function pointer via the
4461/// conversion function @c Conversion, and then attempts to call it
4462/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4463/// the type of function that we'll eventually be calling.
4464void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004465 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004466 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004467 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004468 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004469 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004470 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004471 if (!CandidateSet.isNewCandidate(Conversion))
4472 return;
4473
Douglas Gregor7edfb692009-11-23 12:27:39 +00004474 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004475 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004476
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004477 CandidateSet.push_back(OverloadCandidate());
4478 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004479 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004480 Candidate.Function = 0;
4481 Candidate.Surrogate = Conversion;
4482 Candidate.Viable = true;
4483 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004484 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004485 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004486 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004487
4488 // Determine the implicit conversion sequence for the implicit
4489 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004490 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004491 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004492 Object->Classify(Context),
4493 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004494 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004495 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004496 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004497 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004498 return;
4499 }
4500
4501 // The first conversion is actually a user-defined conversion whose
4502 // first conversion is ObjectInit's standard conversion (which is
4503 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004504 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004505 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004506 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004507 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor83eecbe2011-01-20 01:32:05 +00004509 = FoundDecl.getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004510 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004511 = Candidate.Conversions[0].UserDefined.Before;
4512 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4513
Mike Stump1eb44332009-09-09 15:08:12 +00004514 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004515 unsigned NumArgsInProto = Proto->getNumArgs();
4516
4517 // (C++ 13.3.2p2): A candidate function having fewer than m
4518 // parameters is viable only if it has an ellipsis in its parameter
4519 // list (8.3.5).
4520 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4521 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004522 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004523 return;
4524 }
4525
4526 // Function types don't have any default arguments, so just check if
4527 // we have enough arguments.
4528 if (NumArgs < NumArgsInProto) {
4529 // Not enough arguments.
4530 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004531 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004532 return;
4533 }
4534
4535 // Determine the implicit conversion sequences for each of the
4536 // arguments.
4537 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4538 if (ArgIdx < NumArgsInProto) {
4539 // (C++ 13.3.2p3): for F to be a viable function, there shall
4540 // exist for each argument an implicit conversion sequence
4541 // (13.3.3.1) that converts that argument to the corresponding
4542 // parameter of F.
4543 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004544 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004545 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004546 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004547 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004548 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004549 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004550 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004551 break;
4552 }
4553 } else {
4554 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4555 // argument for which there is no corresponding parameter is
4556 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004557 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004558 }
4559 }
4560}
4561
Douglas Gregor063daf62009-03-13 18:40:31 +00004562/// \brief Add overload candidates for overloaded operators that are
4563/// member functions.
4564///
4565/// Add the overloaded operator candidates that are member functions
4566/// for the operator Op that was used in an operator expression such
4567/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4568/// CandidateSet will store the added overload candidates. (C++
4569/// [over.match.oper]).
4570void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4571 SourceLocation OpLoc,
4572 Expr **Args, unsigned NumArgs,
4573 OverloadCandidateSet& CandidateSet,
4574 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004575 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4576
4577 // C++ [over.match.oper]p3:
4578 // For a unary operator @ with an operand of a type whose
4579 // cv-unqualified version is T1, and for a binary operator @ with
4580 // a left operand of a type whose cv-unqualified version is T1 and
4581 // a right operand of a type whose cv-unqualified version is T2,
4582 // three sets of candidate functions, designated member
4583 // candidates, non-member candidates and built-in candidates, are
4584 // constructed as follows:
4585 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004586
4587 // -- If T1 is a class type, the set of member candidates is the
4588 // result of the qualified lookup of T1::operator@
4589 // (13.3.1.1.1); otherwise, the set of member candidates is
4590 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004591 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004592 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004593 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004594 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004595
John McCalla24dc2e2009-11-17 02:14:36 +00004596 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4597 LookupQualifiedName(Operators, T1Rec->getDecl());
4598 Operators.suppressDiagnostics();
4599
Mike Stump1eb44332009-09-09 15:08:12 +00004600 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004601 OperEnd = Operators.end();
4602 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004603 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004604 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004606 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004607 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004608 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004609}
4610
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004611/// AddBuiltinCandidate - Add a candidate for a built-in
4612/// operator. ResultTy and ParamTys are the result and parameter types
4613/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004614/// arguments being passed to the candidate. IsAssignmentOperator
4615/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004616/// operator. NumContextualBoolArguments is the number of arguments
4617/// (at the beginning of the argument list) that will be contextually
4618/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004619void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004620 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004621 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004622 bool IsAssignmentOperator,
4623 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004624 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004625 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004626
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004627 // Add this candidate
4628 CandidateSet.push_back(OverloadCandidate());
4629 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004630 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004631 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004632 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004633 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004634 Candidate.BuiltinTypes.ResultTy = ResultTy;
4635 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4636 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4637
4638 // Determine the implicit conversion sequences for each of the
4639 // arguments.
4640 Candidate.Viable = true;
4641 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004642 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004644 // C++ [over.match.oper]p4:
4645 // For the built-in assignment operators, conversions of the
4646 // left operand are restricted as follows:
4647 // -- no temporaries are introduced to hold the left operand, and
4648 // -- no user-defined conversions are applied to the left
4649 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004650 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004651 //
4652 // We block these conversions by turning off user-defined
4653 // conversions, since that is the only way that initialization of
4654 // a reference to a non-class type can occur from something that
4655 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004656 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004657 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004658 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004659 Candidate.Conversions[ArgIdx]
4660 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004661 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004662 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004663 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004664 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004665 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004666 }
John McCall1d318332010-01-12 00:44:57 +00004667 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004668 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004669 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004670 break;
4671 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004672 }
4673}
4674
4675/// BuiltinCandidateTypeSet - A set of types that will be used for the
4676/// candidate operator functions for built-in operators (C++
4677/// [over.built]). The types are separated into pointer types and
4678/// enumeration types.
4679class BuiltinCandidateTypeSet {
4680 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004681 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004682
4683 /// PointerTypes - The set of pointer types that will be used in the
4684 /// built-in candidates.
4685 TypeSet PointerTypes;
4686
Sebastian Redl78eb8742009-04-19 21:53:20 +00004687 /// MemberPointerTypes - The set of member pointer types that will be
4688 /// used in the built-in candidates.
4689 TypeSet MemberPointerTypes;
4690
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004691 /// EnumerationTypes - The set of enumeration types that will be
4692 /// used in the built-in candidates.
4693 TypeSet EnumerationTypes;
4694
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00004696 /// candidates.
4697 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004698
4699 /// \brief A flag indicating non-record types are viable candidates
4700 bool HasNonRecordTypes;
4701
4702 /// \brief A flag indicating whether either arithmetic or enumeration types
4703 /// were present in the candidate set.
4704 bool HasArithmeticOrEnumeralTypes;
4705
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004706 /// \brief A flag indicating whether the nullptr type was present in the
4707 /// candidate set.
4708 bool HasNullPtrType;
4709
Douglas Gregor5842ba92009-08-24 15:23:48 +00004710 /// Sema - The semantic analysis instance where we are building the
4711 /// candidate type set.
4712 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004714 /// Context - The AST context in which we will build the type sets.
4715 ASTContext &Context;
4716
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004717 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4718 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004719 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004720
4721public:
4722 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004723 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004724
Mike Stump1eb44332009-09-09 15:08:12 +00004725 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004726 : HasNonRecordTypes(false),
4727 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004728 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00004729 SemaRef(SemaRef),
4730 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004731
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004732 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004733 SourceLocation Loc,
4734 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004735 bool AllowExplicitConversions,
4736 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004737
4738 /// pointer_begin - First pointer type found;
4739 iterator pointer_begin() { return PointerTypes.begin(); }
4740
Sebastian Redl78eb8742009-04-19 21:53:20 +00004741 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004742 iterator pointer_end() { return PointerTypes.end(); }
4743
Sebastian Redl78eb8742009-04-19 21:53:20 +00004744 /// member_pointer_begin - First member pointer type found;
4745 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4746
4747 /// member_pointer_end - Past the last member pointer type found;
4748 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4749
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004750 /// enumeration_begin - First enumeration type found;
4751 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4752
Sebastian Redl78eb8742009-04-19 21:53:20 +00004753 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004754 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755
Douglas Gregor26bcf672010-05-19 03:21:00 +00004756 iterator vector_begin() { return VectorTypes.begin(); }
4757 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004758
4759 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4760 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004761 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004762};
4763
Sebastian Redl78eb8742009-04-19 21:53:20 +00004764/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004765/// the set of pointer types along with any more-qualified variants of
4766/// that type. For example, if @p Ty is "int const *", this routine
4767/// will add "int const *", "int const volatile *", "int const
4768/// restrict *", and "int const volatile restrict *" to the set of
4769/// pointer types. Returns true if the add of @p Ty itself succeeded,
4770/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004771///
4772/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004773bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004774BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4775 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004776
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004777 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004778 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004779 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004780
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004781 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004782 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004783 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004784 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004785 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004786 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004787 buildObjCPtr = true;
4788 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004789 else
4790 assert(false && "type was not a pointer type!");
4791 }
4792 else
4793 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004794
Sebastian Redla9efada2009-11-18 20:39:26 +00004795 // Don't add qualified variants of arrays. For one, they're not allowed
4796 // (the qualifier would sink to the element type), and for another, the
4797 // only overload situation where it matters is subscript or pointer +- int,
4798 // and those shouldn't have qualifier variants anyway.
4799 if (PointeeTy->isArrayType())
4800 return true;
John McCall0953e762009-09-24 19:53:00 +00004801 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004802 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004803 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004804 bool hasVolatile = VisibleQuals.hasVolatile();
4805 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004806
John McCall0953e762009-09-24 19:53:00 +00004807 // Iterate through all strict supersets of BaseCVR.
4808 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4809 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004810 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4811 // in the types.
4812 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4813 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004814 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004815 if (!buildObjCPtr)
4816 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4817 else
4818 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004819 }
4820
4821 return true;
4822}
4823
Sebastian Redl78eb8742009-04-19 21:53:20 +00004824/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4825/// to the set of pointer types along with any more-qualified variants of
4826/// that type. For example, if @p Ty is "int const *", this routine
4827/// will add "int const *", "int const volatile *", "int const
4828/// restrict *", and "int const volatile restrict *" to the set of
4829/// pointer types. Returns true if the add of @p Ty itself succeeded,
4830/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004831///
4832/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004833bool
4834BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4835 QualType Ty) {
4836 // Insert this type.
4837 if (!MemberPointerTypes.insert(Ty))
4838 return false;
4839
John McCall0953e762009-09-24 19:53:00 +00004840 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4841 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004842
John McCall0953e762009-09-24 19:53:00 +00004843 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004844 // Don't add qualified variants of arrays. For one, they're not allowed
4845 // (the qualifier would sink to the element type), and for another, the
4846 // only overload situation where it matters is subscript or pointer +- int,
4847 // and those shouldn't have qualifier variants anyway.
4848 if (PointeeTy->isArrayType())
4849 return true;
John McCall0953e762009-09-24 19:53:00 +00004850 const Type *ClassTy = PointerTy->getClass();
4851
4852 // Iterate through all strict supersets of the pointee type's CVR
4853 // qualifiers.
4854 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4855 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4856 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
John McCall0953e762009-09-24 19:53:00 +00004858 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00004859 MemberPointerTypes.insert(
4860 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004861 }
4862
4863 return true;
4864}
4865
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004866/// AddTypesConvertedFrom - Add each of the types to which the type @p
4867/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004868/// primarily interested in pointer types and enumeration types. We also
4869/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004870/// AllowUserConversions is true if we should look at the conversion
4871/// functions of a class type, and AllowExplicitConversions if we
4872/// should also include the explicit conversion functions of a class
4873/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004874void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004875BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004876 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004877 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004878 bool AllowExplicitConversions,
4879 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004880 // Only deal with canonical types.
4881 Ty = Context.getCanonicalType(Ty);
4882
4883 // Look through reference types; they aren't part of the type of an
4884 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004885 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004886 Ty = RefTy->getPointeeType();
4887
John McCall3b657512011-01-19 10:06:00 +00004888 // If we're dealing with an array type, decay to the pointer.
4889 if (Ty->isArrayType())
4890 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4891
4892 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004893 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004894
Chandler Carruth6a577462010-12-13 01:44:01 +00004895 // Flag if we ever add a non-record type.
4896 const RecordType *TyRec = Ty->getAs<RecordType>();
4897 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4898
Chandler Carruth6a577462010-12-13 01:44:01 +00004899 // Flag if we encounter an arithmetic type.
4900 HasArithmeticOrEnumeralTypes =
4901 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4902
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004903 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4904 PointerTypes.insert(Ty);
4905 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004906 // Insert our type, and its more-qualified variants, into the set
4907 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004908 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004909 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004910 } else if (Ty->isMemberPointerType()) {
4911 // Member pointers are far easier, since the pointee can't be converted.
4912 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4913 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004914 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004915 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00004916 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004917 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004918 // We treat vector types as arithmetic types in many contexts as an
4919 // extension.
4920 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00004921 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004922 } else if (Ty->isNullPtrType()) {
4923 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00004924 } else if (AllowUserConversions && TyRec) {
4925 // No conversion functions in incomplete types.
4926 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4927 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Chandler Carruth6a577462010-12-13 01:44:01 +00004929 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4930 const UnresolvedSetImpl *Conversions
4931 = ClassDecl->getVisibleConversionFunctions();
4932 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4933 E = Conversions->end(); I != E; ++I) {
4934 NamedDecl *D = I.getDecl();
4935 if (isa<UsingShadowDecl>(D))
4936 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004937
Chandler Carruth6a577462010-12-13 01:44:01 +00004938 // Skip conversion function templates; they don't tell us anything
4939 // about which builtin types we can convert to.
4940 if (isa<FunctionTemplateDecl>(D))
4941 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004942
Chandler Carruth6a577462010-12-13 01:44:01 +00004943 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4944 if (AllowExplicitConversions || !Conv->isExplicit()) {
4945 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4946 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004947 }
4948 }
4949 }
4950}
4951
Douglas Gregor19b7b152009-08-24 13:43:27 +00004952/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4953/// the volatile- and non-volatile-qualified assignment operators for the
4954/// given type to the candidate set.
4955static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4956 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004957 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004958 unsigned NumArgs,
4959 OverloadCandidateSet &CandidateSet) {
4960 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004961
Douglas Gregor19b7b152009-08-24 13:43:27 +00004962 // T& operator=(T&, T)
4963 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4964 ParamTypes[1] = T;
4965 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4966 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004967
Douglas Gregor19b7b152009-08-24 13:43:27 +00004968 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4969 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004970 ParamTypes[0]
4971 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004972 ParamTypes[1] = T;
4973 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004974 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004975 }
4976}
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Sebastian Redl9994a342009-10-25 17:03:50 +00004978/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4979/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004980static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4981 Qualifiers VRQuals;
4982 const RecordType *TyRec;
4983 if (const MemberPointerType *RHSMPType =
4984 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004985 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004986 else
4987 TyRec = ArgExpr->getType()->getAs<RecordType>();
4988 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004989 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004990 VRQuals.addVolatile();
4991 VRQuals.addRestrict();
4992 return VRQuals;
4993 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004994
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004995 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004996 if (!ClassDecl->hasDefinition())
4997 return VRQuals;
4998
John McCalleec51cf2010-01-20 00:46:10 +00004999 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005000 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005001
John McCalleec51cf2010-01-20 00:46:10 +00005002 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005003 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005004 NamedDecl *D = I.getDecl();
5005 if (isa<UsingShadowDecl>(D))
5006 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5007 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005008 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5009 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5010 CanTy = ResTypeRef->getPointeeType();
5011 // Need to go down the pointer/mempointer chain and add qualifiers
5012 // as see them.
5013 bool done = false;
5014 while (!done) {
5015 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5016 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005017 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005018 CanTy->getAs<MemberPointerType>())
5019 CanTy = ResTypeMPtr->getPointeeType();
5020 else
5021 done = true;
5022 if (CanTy.isVolatileQualified())
5023 VRQuals.addVolatile();
5024 if (CanTy.isRestrictQualified())
5025 VRQuals.addRestrict();
5026 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5027 return VRQuals;
5028 }
5029 }
5030 }
5031 return VRQuals;
5032}
John McCall00071ec2010-11-13 05:51:15 +00005033
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005034namespace {
John McCall00071ec2010-11-13 05:51:15 +00005035
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005036/// \brief Helper class to manage the addition of builtin operator overload
5037/// candidates. It provides shared state and utility methods used throughout
5038/// the process, as well as a helper method to add each group of builtin
5039/// operator overloads from the standard to a candidate set.
5040class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005041 // Common instance state available to all overload candidate addition methods.
5042 Sema &S;
5043 Expr **Args;
5044 unsigned NumArgs;
5045 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005046 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruth6d695582010-12-12 10:35:00 +00005047 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5048 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005049
Chandler Carruth6d695582010-12-12 10:35:00 +00005050 // Define some constants used to index and iterate over the arithemetic types
5051 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005052 // The "promoted arithmetic types" are the arithmetic
5053 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005054 static const unsigned FirstIntegralType = 3;
5055 static const unsigned LastIntegralType = 18;
5056 static const unsigned FirstPromotedIntegralType = 3,
5057 LastPromotedIntegralType = 9;
5058 static const unsigned FirstPromotedArithmeticType = 0,
5059 LastPromotedArithmeticType = 9;
5060 static const unsigned NumArithmeticTypes = 18;
5061
Chandler Carruth6d695582010-12-12 10:35:00 +00005062 /// \brief Get the canonical type for a given arithmetic type index.
5063 CanQualType getArithmeticType(unsigned index) {
5064 assert(index < NumArithmeticTypes);
5065 static CanQualType ASTContext::* const
5066 ArithmeticTypes[NumArithmeticTypes] = {
5067 // Start of promoted types.
5068 &ASTContext::FloatTy,
5069 &ASTContext::DoubleTy,
5070 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005071
Chandler Carruth6d695582010-12-12 10:35:00 +00005072 // Start of integral types.
5073 &ASTContext::IntTy,
5074 &ASTContext::LongTy,
5075 &ASTContext::LongLongTy,
5076 &ASTContext::UnsignedIntTy,
5077 &ASTContext::UnsignedLongTy,
5078 &ASTContext::UnsignedLongLongTy,
5079 // End of promoted types.
5080
5081 &ASTContext::BoolTy,
5082 &ASTContext::CharTy,
5083 &ASTContext::WCharTy,
5084 &ASTContext::Char16Ty,
5085 &ASTContext::Char32Ty,
5086 &ASTContext::SignedCharTy,
5087 &ASTContext::ShortTy,
5088 &ASTContext::UnsignedCharTy,
5089 &ASTContext::UnsignedShortTy,
5090 // End of integral types.
5091 // FIXME: What about complex?
5092 };
5093 return S.Context.*ArithmeticTypes[index];
5094 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005095
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005096 /// \brief Gets the canonical type resulting from the usual arithemetic
5097 /// converions for the given arithmetic types.
5098 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5099 // Accelerator table for performing the usual arithmetic conversions.
5100 // The rules are basically:
5101 // - if either is floating-point, use the wider floating-point
5102 // - if same signedness, use the higher rank
5103 // - if same size, use unsigned of the higher rank
5104 // - use the larger type
5105 // These rules, together with the axiom that higher ranks are
5106 // never smaller, are sufficient to precompute all of these results
5107 // *except* when dealing with signed types of higher rank.
5108 // (we could precompute SLL x UI for all known platforms, but it's
5109 // better not to make any assumptions).
5110 enum PromotedType {
5111 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5112 };
5113 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5114 [LastPromotedArithmeticType] = {
5115 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5116 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5117 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5118 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5119 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5120 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5121 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5122 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5123 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5124 };
5125
5126 assert(L < LastPromotedArithmeticType);
5127 assert(R < LastPromotedArithmeticType);
5128 int Idx = ConversionsTable[L][R];
5129
5130 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005131 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005132
5133 // Slow path: we need to compare widths.
5134 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005135 CanQualType LT = getArithmeticType(L),
5136 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005137 unsigned LW = S.Context.getIntWidth(LT),
5138 RW = S.Context.getIntWidth(RT);
5139
5140 // If they're different widths, use the signed type.
5141 if (LW > RW) return LT;
5142 else if (LW < RW) return RT;
5143
5144 // Otherwise, use the unsigned type of the signed type's rank.
5145 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5146 assert(L == SLL || R == SLL);
5147 return S.Context.UnsignedLongLongTy;
5148 }
5149
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005150 /// \brief Helper method to factor out the common pattern of adding overloads
5151 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005152 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5153 bool HasVolatile) {
5154 QualType ParamTypes[2] = {
5155 S.Context.getLValueReferenceType(CandidateTy),
5156 S.Context.IntTy
5157 };
5158
5159 // Non-volatile version.
5160 if (NumArgs == 1)
5161 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5162 else
5163 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5164
5165 // Use a heuristic to reduce number of builtin candidates in the set:
5166 // add volatile version only if there are conversions to a volatile type.
5167 if (HasVolatile) {
5168 ParamTypes[0] =
5169 S.Context.getLValueReferenceType(
5170 S.Context.getVolatileType(CandidateTy));
5171 if (NumArgs == 1)
5172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5173 else
5174 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5175 }
5176 }
5177
5178public:
5179 BuiltinOperatorOverloadBuilder(
5180 Sema &S, Expr **Args, unsigned NumArgs,
5181 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005182 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005183 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5184 OverloadCandidateSet &CandidateSet)
5185 : S(S), Args(Args), NumArgs(NumArgs),
5186 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005187 HasArithmeticOrEnumeralCandidateType(
5188 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005189 CandidateTypes(CandidateTypes),
5190 CandidateSet(CandidateSet) {
5191 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005192 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005193 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005194 assert(getArithmeticType(LastPromotedIntegralType - 1)
5195 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005196 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005197 assert(getArithmeticType(FirstPromotedArithmeticType)
5198 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005199 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005200 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5201 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005202 "Invalid last promoted arithmetic type");
5203 }
5204
5205 // C++ [over.built]p3:
5206 //
5207 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5208 // is either volatile or empty, there exist candidate operator
5209 // functions of the form
5210 //
5211 // VQ T& operator++(VQ T&);
5212 // T operator++(VQ T&, int);
5213 //
5214 // C++ [over.built]p4:
5215 //
5216 // For every pair (T, VQ), where T is an arithmetic type other
5217 // than bool, and VQ is either volatile or empty, there exist
5218 // candidate operator functions of the form
5219 //
5220 // VQ T& operator--(VQ T&);
5221 // T operator--(VQ T&, int);
5222 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005223 if (!HasArithmeticOrEnumeralCandidateType)
5224 return;
5225
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005226 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5227 Arith < NumArithmeticTypes; ++Arith) {
5228 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005229 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005230 VisibleTypeConversionsQuals.hasVolatile());
5231 }
5232 }
5233
5234 // C++ [over.built]p5:
5235 //
5236 // For every pair (T, VQ), where T is a cv-qualified or
5237 // cv-unqualified object type, and VQ is either volatile or
5238 // empty, there exist candidate operator functions of the form
5239 //
5240 // T*VQ& operator++(T*VQ&);
5241 // T*VQ& operator--(T*VQ&);
5242 // T* operator++(T*VQ&, int);
5243 // T* operator--(T*VQ&, int);
5244 void addPlusPlusMinusMinusPointerOverloads() {
5245 for (BuiltinCandidateTypeSet::iterator
5246 Ptr = CandidateTypes[0].pointer_begin(),
5247 PtrEnd = CandidateTypes[0].pointer_end();
5248 Ptr != PtrEnd; ++Ptr) {
5249 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005250 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005251 continue;
5252
5253 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5254 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5255 VisibleTypeConversionsQuals.hasVolatile()));
5256 }
5257 }
5258
5259 // C++ [over.built]p6:
5260 // For every cv-qualified or cv-unqualified object type T, there
5261 // exist candidate operator functions of the form
5262 //
5263 // T& operator*(T*);
5264 //
5265 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005267 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005268 // T& operator*(T*);
5269 void addUnaryStarPointerOverloads() {
5270 for (BuiltinCandidateTypeSet::iterator
5271 Ptr = CandidateTypes[0].pointer_begin(),
5272 PtrEnd = CandidateTypes[0].pointer_end();
5273 Ptr != PtrEnd; ++Ptr) {
5274 QualType ParamTy = *Ptr;
5275 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005276 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5277 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005278
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005279 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5280 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5281 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005282
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005283 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5284 &ParamTy, Args, 1, CandidateSet);
5285 }
5286 }
5287
5288 // C++ [over.built]p9:
5289 // For every promoted arithmetic type T, there exist candidate
5290 // operator functions of the form
5291 //
5292 // T operator+(T);
5293 // T operator-(T);
5294 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005295 if (!HasArithmeticOrEnumeralCandidateType)
5296 return;
5297
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005298 for (unsigned Arith = FirstPromotedArithmeticType;
5299 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005300 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005301 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5302 }
5303
5304 // Extension: We also add these operators for vector types.
5305 for (BuiltinCandidateTypeSet::iterator
5306 Vec = CandidateTypes[0].vector_begin(),
5307 VecEnd = CandidateTypes[0].vector_end();
5308 Vec != VecEnd; ++Vec) {
5309 QualType VecTy = *Vec;
5310 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5311 }
5312 }
5313
5314 // C++ [over.built]p8:
5315 // For every type T, there exist candidate operator functions of
5316 // the form
5317 //
5318 // T* operator+(T*);
5319 void addUnaryPlusPointerOverloads() {
5320 for (BuiltinCandidateTypeSet::iterator
5321 Ptr = CandidateTypes[0].pointer_begin(),
5322 PtrEnd = CandidateTypes[0].pointer_end();
5323 Ptr != PtrEnd; ++Ptr) {
5324 QualType ParamTy = *Ptr;
5325 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5326 }
5327 }
5328
5329 // C++ [over.built]p10:
5330 // For every promoted integral type T, there exist candidate
5331 // operator functions of the form
5332 //
5333 // T operator~(T);
5334 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005335 if (!HasArithmeticOrEnumeralCandidateType)
5336 return;
5337
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005338 for (unsigned Int = FirstPromotedIntegralType;
5339 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005340 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005341 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5342 }
5343
5344 // Extension: We also add this operator for vector types.
5345 for (BuiltinCandidateTypeSet::iterator
5346 Vec = CandidateTypes[0].vector_begin(),
5347 VecEnd = CandidateTypes[0].vector_end();
5348 Vec != VecEnd; ++Vec) {
5349 QualType VecTy = *Vec;
5350 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5351 }
5352 }
5353
5354 // C++ [over.match.oper]p16:
5355 // For every pointer to member type T, there exist candidate operator
5356 // functions of the form
5357 //
5358 // bool operator==(T,T);
5359 // bool operator!=(T,T);
5360 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5361 /// Set of (canonical) types that we've already handled.
5362 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5363
5364 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5365 for (BuiltinCandidateTypeSet::iterator
5366 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5367 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5368 MemPtr != MemPtrEnd;
5369 ++MemPtr) {
5370 // Don't add the same builtin candidate twice.
5371 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5372 continue;
5373
5374 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5375 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5376 CandidateSet);
5377 }
5378 }
5379 }
5380
5381 // C++ [over.built]p15:
5382 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005383 // For every T, where T is an enumeration type, a pointer type, or
5384 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005385 //
5386 // bool operator<(T, T);
5387 // bool operator>(T, T);
5388 // bool operator<=(T, T);
5389 // bool operator>=(T, T);
5390 // bool operator==(T, T);
5391 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005392 void addRelationalPointerOrEnumeralOverloads() {
5393 // C++ [over.built]p1:
5394 // If there is a user-written candidate with the same name and parameter
5395 // types as a built-in candidate operator function, the built-in operator
5396 // function is hidden and is not included in the set of candidate
5397 // functions.
5398 //
5399 // The text is actually in a note, but if we don't implement it then we end
5400 // up with ambiguities when the user provides an overloaded operator for
5401 // an enumeration type. Note that only enumeration types have this problem,
5402 // so we track which enumeration types we've seen operators for. Also, the
5403 // only other overloaded operator with enumeration argumenst, operator=,
5404 // cannot be overloaded for enumeration types, so this is the only place
5405 // where we must suppress candidates like this.
5406 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5407 UserDefinedBinaryOperators;
5408
5409 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5410 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5411 CandidateTypes[ArgIdx].enumeration_end()) {
5412 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5413 CEnd = CandidateSet.end();
5414 C != CEnd; ++C) {
5415 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5416 continue;
5417
5418 QualType FirstParamType =
5419 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5420 QualType SecondParamType =
5421 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5422
5423 // Skip if either parameter isn't of enumeral type.
5424 if (!FirstParamType->isEnumeralType() ||
5425 !SecondParamType->isEnumeralType())
5426 continue;
5427
5428 // Add this operator to the set of known user-defined operators.
5429 UserDefinedBinaryOperators.insert(
5430 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5431 S.Context.getCanonicalType(SecondParamType)));
5432 }
5433 }
5434 }
5435
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005436 /// Set of (canonical) types that we've already handled.
5437 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5438
5439 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5440 for (BuiltinCandidateTypeSet::iterator
5441 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5442 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5443 Ptr != PtrEnd; ++Ptr) {
5444 // Don't add the same builtin candidate twice.
5445 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5446 continue;
5447
5448 QualType ParamTypes[2] = { *Ptr, *Ptr };
5449 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5450 CandidateSet);
5451 }
5452 for (BuiltinCandidateTypeSet::iterator
5453 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5454 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5455 Enum != EnumEnd; ++Enum) {
5456 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5457
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005458 // Don't add the same builtin candidate twice, or if a user defined
5459 // candidate exists.
5460 if (!AddedTypes.insert(CanonType) ||
5461 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5462 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005463 continue;
5464
5465 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005466 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5467 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005468 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005469
5470 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5471 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5472 if (AddedTypes.insert(NullPtrTy) &&
5473 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5474 NullPtrTy))) {
5475 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5477 CandidateSet);
5478 }
5479 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005480 }
5481 }
5482
5483 // C++ [over.built]p13:
5484 //
5485 // For every cv-qualified or cv-unqualified object type T
5486 // there exist candidate operator functions of the form
5487 //
5488 // T* operator+(T*, ptrdiff_t);
5489 // T& operator[](T*, ptrdiff_t); [BELOW]
5490 // T* operator-(T*, ptrdiff_t);
5491 // T* operator+(ptrdiff_t, T*);
5492 // T& operator[](ptrdiff_t, T*); [BELOW]
5493 //
5494 // C++ [over.built]p14:
5495 //
5496 // For every T, where T is a pointer to object type, there
5497 // exist candidate operator functions of the form
5498 //
5499 // ptrdiff_t operator-(T, T);
5500 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5501 /// Set of (canonical) types that we've already handled.
5502 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5503
5504 for (int Arg = 0; Arg < 2; ++Arg) {
5505 QualType AsymetricParamTypes[2] = {
5506 S.Context.getPointerDiffType(),
5507 S.Context.getPointerDiffType(),
5508 };
5509 for (BuiltinCandidateTypeSet::iterator
5510 Ptr = CandidateTypes[Arg].pointer_begin(),
5511 PtrEnd = CandidateTypes[Arg].pointer_end();
5512 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005513 QualType PointeeTy = (*Ptr)->getPointeeType();
5514 if (!PointeeTy->isObjectType())
5515 continue;
5516
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005517 AsymetricParamTypes[Arg] = *Ptr;
5518 if (Arg == 0 || Op == OO_Plus) {
5519 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5520 // T* operator+(ptrdiff_t, T*);
5521 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5522 CandidateSet);
5523 }
5524 if (Op == OO_Minus) {
5525 // ptrdiff_t operator-(T, T);
5526 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5527 continue;
5528
5529 QualType ParamTypes[2] = { *Ptr, *Ptr };
5530 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5531 Args, 2, CandidateSet);
5532 }
5533 }
5534 }
5535 }
5536
5537 // C++ [over.built]p12:
5538 //
5539 // For every pair of promoted arithmetic types L and R, there
5540 // exist candidate operator functions of the form
5541 //
5542 // LR operator*(L, R);
5543 // LR operator/(L, R);
5544 // LR operator+(L, R);
5545 // LR operator-(L, R);
5546 // bool operator<(L, R);
5547 // bool operator>(L, R);
5548 // bool operator<=(L, R);
5549 // bool operator>=(L, R);
5550 // bool operator==(L, R);
5551 // bool operator!=(L, R);
5552 //
5553 // where LR is the result of the usual arithmetic conversions
5554 // between types L and R.
5555 //
5556 // C++ [over.built]p24:
5557 //
5558 // For every pair of promoted arithmetic types L and R, there exist
5559 // candidate operator functions of the form
5560 //
5561 // LR operator?(bool, L, R);
5562 //
5563 // where LR is the result of the usual arithmetic conversions
5564 // between types L and R.
5565 // Our candidates ignore the first parameter.
5566 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005567 if (!HasArithmeticOrEnumeralCandidateType)
5568 return;
5569
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005570 for (unsigned Left = FirstPromotedArithmeticType;
5571 Left < LastPromotedArithmeticType; ++Left) {
5572 for (unsigned Right = FirstPromotedArithmeticType;
5573 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005574 QualType LandR[2] = { getArithmeticType(Left),
5575 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005576 QualType Result =
5577 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005578 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005579 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5580 }
5581 }
5582
5583 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5584 // conditional operator for vector types.
5585 for (BuiltinCandidateTypeSet::iterator
5586 Vec1 = CandidateTypes[0].vector_begin(),
5587 Vec1End = CandidateTypes[0].vector_end();
5588 Vec1 != Vec1End; ++Vec1) {
5589 for (BuiltinCandidateTypeSet::iterator
5590 Vec2 = CandidateTypes[1].vector_begin(),
5591 Vec2End = CandidateTypes[1].vector_end();
5592 Vec2 != Vec2End; ++Vec2) {
5593 QualType LandR[2] = { *Vec1, *Vec2 };
5594 QualType Result = S.Context.BoolTy;
5595 if (!isComparison) {
5596 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5597 Result = *Vec1;
5598 else
5599 Result = *Vec2;
5600 }
5601
5602 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5603 }
5604 }
5605 }
5606
5607 // C++ [over.built]p17:
5608 //
5609 // For every pair of promoted integral types L and R, there
5610 // exist candidate operator functions of the form
5611 //
5612 // LR operator%(L, R);
5613 // LR operator&(L, R);
5614 // LR operator^(L, R);
5615 // LR operator|(L, R);
5616 // L operator<<(L, R);
5617 // L operator>>(L, R);
5618 //
5619 // where LR is the result of the usual arithmetic conversions
5620 // between types L and R.
5621 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005622 if (!HasArithmeticOrEnumeralCandidateType)
5623 return;
5624
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005625 for (unsigned Left = FirstPromotedIntegralType;
5626 Left < LastPromotedIntegralType; ++Left) {
5627 for (unsigned Right = FirstPromotedIntegralType;
5628 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005629 QualType LandR[2] = { getArithmeticType(Left),
5630 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005631 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5632 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005633 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005634 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5635 }
5636 }
5637 }
5638
5639 // C++ [over.built]p20:
5640 //
5641 // For every pair (T, VQ), where T is an enumeration or
5642 // pointer to member type and VQ is either volatile or
5643 // empty, there exist candidate operator functions of the form
5644 //
5645 // VQ T& operator=(VQ T&, T);
5646 void addAssignmentMemberPointerOrEnumeralOverloads() {
5647 /// Set of (canonical) types that we've already handled.
5648 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5649
5650 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5651 for (BuiltinCandidateTypeSet::iterator
5652 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5653 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5654 Enum != EnumEnd; ++Enum) {
5655 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5656 continue;
5657
5658 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5659 CandidateSet);
5660 }
5661
5662 for (BuiltinCandidateTypeSet::iterator
5663 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5664 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5665 MemPtr != MemPtrEnd; ++MemPtr) {
5666 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5667 continue;
5668
5669 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5670 CandidateSet);
5671 }
5672 }
5673 }
5674
5675 // C++ [over.built]p19:
5676 //
5677 // For every pair (T, VQ), where T is any type and VQ is either
5678 // volatile or empty, there exist candidate operator functions
5679 // of the form
5680 //
5681 // T*VQ& operator=(T*VQ&, T*);
5682 //
5683 // C++ [over.built]p21:
5684 //
5685 // For every pair (T, VQ), where T is a cv-qualified or
5686 // cv-unqualified object type and VQ is either volatile or
5687 // empty, there exist candidate operator functions of the form
5688 //
5689 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5690 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5691 void addAssignmentPointerOverloads(bool isEqualOp) {
5692 /// Set of (canonical) types that we've already handled.
5693 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5694
5695 for (BuiltinCandidateTypeSet::iterator
5696 Ptr = CandidateTypes[0].pointer_begin(),
5697 PtrEnd = CandidateTypes[0].pointer_end();
5698 Ptr != PtrEnd; ++Ptr) {
5699 // If this is operator=, keep track of the builtin candidates we added.
5700 if (isEqualOp)
5701 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005702 else if (!(*Ptr)->getPointeeType()->isObjectType())
5703 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005704
5705 // non-volatile version
5706 QualType ParamTypes[2] = {
5707 S.Context.getLValueReferenceType(*Ptr),
5708 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5709 };
5710 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5711 /*IsAssigmentOperator=*/ isEqualOp);
5712
5713 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5714 VisibleTypeConversionsQuals.hasVolatile()) {
5715 // volatile version
5716 ParamTypes[0] =
5717 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5719 /*IsAssigmentOperator=*/isEqualOp);
5720 }
5721 }
5722
5723 if (isEqualOp) {
5724 for (BuiltinCandidateTypeSet::iterator
5725 Ptr = CandidateTypes[1].pointer_begin(),
5726 PtrEnd = CandidateTypes[1].pointer_end();
5727 Ptr != PtrEnd; ++Ptr) {
5728 // Make sure we don't add the same candidate twice.
5729 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5730 continue;
5731
Chandler Carruth6df868e2010-12-12 08:17:55 +00005732 QualType ParamTypes[2] = {
5733 S.Context.getLValueReferenceType(*Ptr),
5734 *Ptr,
5735 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005736
5737 // non-volatile version
5738 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5739 /*IsAssigmentOperator=*/true);
5740
5741 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5742 VisibleTypeConversionsQuals.hasVolatile()) {
5743 // volatile version
5744 ParamTypes[0] =
5745 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005746 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5747 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005748 }
5749 }
5750 }
5751 }
5752
5753 // C++ [over.built]p18:
5754 //
5755 // For every triple (L, VQ, R), where L is an arithmetic type,
5756 // VQ is either volatile or empty, and R is a promoted
5757 // arithmetic type, there exist candidate operator functions of
5758 // the form
5759 //
5760 // VQ L& operator=(VQ L&, R);
5761 // VQ L& operator*=(VQ L&, R);
5762 // VQ L& operator/=(VQ L&, R);
5763 // VQ L& operator+=(VQ L&, R);
5764 // VQ L& operator-=(VQ L&, R);
5765 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005766 if (!HasArithmeticOrEnumeralCandidateType)
5767 return;
5768
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005769 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5770 for (unsigned Right = FirstPromotedArithmeticType;
5771 Right < LastPromotedArithmeticType; ++Right) {
5772 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005773 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005774
5775 // Add this built-in operator as a candidate (VQ is empty).
5776 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005777 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005778 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5779 /*IsAssigmentOperator=*/isEqualOp);
5780
5781 // Add this built-in operator as a candidate (VQ is 'volatile').
5782 if (VisibleTypeConversionsQuals.hasVolatile()) {
5783 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005784 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005785 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005786 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5787 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005788 /*IsAssigmentOperator=*/isEqualOp);
5789 }
5790 }
5791 }
5792
5793 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5794 for (BuiltinCandidateTypeSet::iterator
5795 Vec1 = CandidateTypes[0].vector_begin(),
5796 Vec1End = CandidateTypes[0].vector_end();
5797 Vec1 != Vec1End; ++Vec1) {
5798 for (BuiltinCandidateTypeSet::iterator
5799 Vec2 = CandidateTypes[1].vector_begin(),
5800 Vec2End = CandidateTypes[1].vector_end();
5801 Vec2 != Vec2End; ++Vec2) {
5802 QualType ParamTypes[2];
5803 ParamTypes[1] = *Vec2;
5804 // Add this built-in operator as a candidate (VQ is empty).
5805 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5806 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5807 /*IsAssigmentOperator=*/isEqualOp);
5808
5809 // Add this built-in operator as a candidate (VQ is 'volatile').
5810 if (VisibleTypeConversionsQuals.hasVolatile()) {
5811 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5812 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005813 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5814 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005815 /*IsAssigmentOperator=*/isEqualOp);
5816 }
5817 }
5818 }
5819 }
5820
5821 // C++ [over.built]p22:
5822 //
5823 // For every triple (L, VQ, R), where L is an integral type, VQ
5824 // is either volatile or empty, and R is a promoted integral
5825 // type, there exist candidate operator functions of the form
5826 //
5827 // VQ L& operator%=(VQ L&, R);
5828 // VQ L& operator<<=(VQ L&, R);
5829 // VQ L& operator>>=(VQ L&, R);
5830 // VQ L& operator&=(VQ L&, R);
5831 // VQ L& operator^=(VQ L&, R);
5832 // VQ L& operator|=(VQ L&, R);
5833 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005834 if (!HasArithmeticOrEnumeralCandidateType)
5835 return;
5836
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005837 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5838 for (unsigned Right = FirstPromotedIntegralType;
5839 Right < LastPromotedIntegralType; ++Right) {
5840 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005841 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005842
5843 // Add this built-in operator as a candidate (VQ is empty).
5844 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005845 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005846 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5847 if (VisibleTypeConversionsQuals.hasVolatile()) {
5848 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00005849 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005850 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5851 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5852 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5853 CandidateSet);
5854 }
5855 }
5856 }
5857 }
5858
5859 // C++ [over.operator]p23:
5860 //
5861 // There also exist candidate operator functions of the form
5862 //
5863 // bool operator!(bool);
5864 // bool operator&&(bool, bool);
5865 // bool operator||(bool, bool);
5866 void addExclaimOverload() {
5867 QualType ParamTy = S.Context.BoolTy;
5868 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5869 /*IsAssignmentOperator=*/false,
5870 /*NumContextualBoolArguments=*/1);
5871 }
5872 void addAmpAmpOrPipePipeOverload() {
5873 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5874 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5875 /*IsAssignmentOperator=*/false,
5876 /*NumContextualBoolArguments=*/2);
5877 }
5878
5879 // C++ [over.built]p13:
5880 //
5881 // For every cv-qualified or cv-unqualified object type T there
5882 // exist candidate operator functions of the form
5883 //
5884 // T* operator+(T*, ptrdiff_t); [ABOVE]
5885 // T& operator[](T*, ptrdiff_t);
5886 // T* operator-(T*, ptrdiff_t); [ABOVE]
5887 // T* operator+(ptrdiff_t, T*); [ABOVE]
5888 // T& operator[](ptrdiff_t, T*);
5889 void addSubscriptOverloads() {
5890 for (BuiltinCandidateTypeSet::iterator
5891 Ptr = CandidateTypes[0].pointer_begin(),
5892 PtrEnd = CandidateTypes[0].pointer_end();
5893 Ptr != PtrEnd; ++Ptr) {
5894 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5895 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005896 if (!PointeeType->isObjectType())
5897 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005898
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005899 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5900
5901 // T& operator[](T*, ptrdiff_t)
5902 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5903 }
5904
5905 for (BuiltinCandidateTypeSet::iterator
5906 Ptr = CandidateTypes[1].pointer_begin(),
5907 PtrEnd = CandidateTypes[1].pointer_end();
5908 Ptr != PtrEnd; ++Ptr) {
5909 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5910 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005911 if (!PointeeType->isObjectType())
5912 continue;
5913
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005914 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5915
5916 // T& operator[](ptrdiff_t, T*)
5917 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5918 }
5919 }
5920
5921 // C++ [over.built]p11:
5922 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5923 // C1 is the same type as C2 or is a derived class of C2, T is an object
5924 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5925 // there exist candidate operator functions of the form
5926 //
5927 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5928 //
5929 // where CV12 is the union of CV1 and CV2.
5930 void addArrowStarOverloads() {
5931 for (BuiltinCandidateTypeSet::iterator
5932 Ptr = CandidateTypes[0].pointer_begin(),
5933 PtrEnd = CandidateTypes[0].pointer_end();
5934 Ptr != PtrEnd; ++Ptr) {
5935 QualType C1Ty = (*Ptr);
5936 QualType C1;
5937 QualifierCollector Q1;
5938 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5939 if (!isa<RecordType>(C1))
5940 continue;
5941 // heuristic to reduce number of builtin candidates in the set.
5942 // Add volatile/restrict version only if there are conversions to a
5943 // volatile/restrict type.
5944 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5945 continue;
5946 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5947 continue;
5948 for (BuiltinCandidateTypeSet::iterator
5949 MemPtr = CandidateTypes[1].member_pointer_begin(),
5950 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5951 MemPtr != MemPtrEnd; ++MemPtr) {
5952 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5953 QualType C2 = QualType(mptr->getClass(), 0);
5954 C2 = C2.getUnqualifiedType();
5955 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5956 break;
5957 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5958 // build CV12 T&
5959 QualType T = mptr->getPointeeType();
5960 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5961 T.isVolatileQualified())
5962 continue;
5963 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5964 T.isRestrictQualified())
5965 continue;
5966 T = Q1.apply(S.Context, T);
5967 QualType ResultTy = S.Context.getLValueReferenceType(T);
5968 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5969 }
5970 }
5971 }
5972
5973 // Note that we don't consider the first argument, since it has been
5974 // contextually converted to bool long ago. The candidates below are
5975 // therefore added as binary.
5976 //
5977 // C++ [over.built]p25:
5978 // For every type T, where T is a pointer, pointer-to-member, or scoped
5979 // enumeration type, there exist candidate operator functions of the form
5980 //
5981 // T operator?(bool, T, T);
5982 //
5983 void addConditionalOperatorOverloads() {
5984 /// Set of (canonical) types that we've already handled.
5985 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5986
5987 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5988 for (BuiltinCandidateTypeSet::iterator
5989 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5990 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5991 Ptr != PtrEnd; ++Ptr) {
5992 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5993 continue;
5994
5995 QualType ParamTypes[2] = { *Ptr, *Ptr };
5996 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5997 }
5998
5999 for (BuiltinCandidateTypeSet::iterator
6000 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6001 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6002 MemPtr != MemPtrEnd; ++MemPtr) {
6003 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6004 continue;
6005
6006 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6007 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6008 }
6009
6010 if (S.getLangOptions().CPlusPlus0x) {
6011 for (BuiltinCandidateTypeSet::iterator
6012 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6013 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6014 Enum != EnumEnd; ++Enum) {
6015 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6016 continue;
6017
6018 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6019 continue;
6020
6021 QualType ParamTypes[2] = { *Enum, *Enum };
6022 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6023 }
6024 }
6025 }
6026 }
6027};
6028
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006029} // end anonymous namespace
6030
6031/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6032/// operator overloads to the candidate set (C++ [over.built]), based
6033/// on the operator @p Op and the arguments given. For example, if the
6034/// operator is a binary '+', this routine might add "int
6035/// operator+(int, int)" to cover integer addition.
6036void
6037Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6038 SourceLocation OpLoc,
6039 Expr **Args, unsigned NumArgs,
6040 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006041 // Find all of the types that the arguments can convert to, but only
6042 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006043 // that make use of these types. Also record whether we encounter non-record
6044 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006045 Qualifiers VisibleTypeConversionsQuals;
6046 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006047 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6048 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006049
6050 bool HasNonRecordCandidateType = false;
6051 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006052 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6053 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6054 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6055 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6056 OpLoc,
6057 true,
6058 (Op == OO_Exclaim ||
6059 Op == OO_AmpAmp ||
6060 Op == OO_PipePipe),
6061 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006062 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6063 CandidateTypes[ArgIdx].hasNonRecordTypes();
6064 HasArithmeticOrEnumeralCandidateType =
6065 HasArithmeticOrEnumeralCandidateType ||
6066 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006067 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006068
Chandler Carruth6a577462010-12-13 01:44:01 +00006069 // Exit early when no non-record types have been added to the candidate set
6070 // for any of the arguments to the operator.
6071 if (!HasNonRecordCandidateType)
6072 return;
6073
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006074 // Setup an object to manage the common state for building overloads.
6075 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6076 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006077 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006078 CandidateTypes, CandidateSet);
6079
6080 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006081 switch (Op) {
6082 case OO_None:
6083 case NUM_OVERLOADED_OPERATORS:
6084 assert(false && "Expected an overloaded operator");
6085 break;
6086
Chandler Carruthabb71842010-12-12 08:51:33 +00006087 case OO_New:
6088 case OO_Delete:
6089 case OO_Array_New:
6090 case OO_Array_Delete:
6091 case OO_Call:
6092 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6093 break;
6094
6095 case OO_Comma:
6096 case OO_Arrow:
6097 // C++ [over.match.oper]p3:
6098 // -- For the operator ',', the unary operator '&', or the
6099 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006100 break;
6101
6102 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006103 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006104 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006105 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006106
6107 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006108 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006109 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006110 } else {
6111 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6112 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6113 }
Douglas Gregor74253732008-11-19 15:42:04 +00006114 break;
6115
Chandler Carruthabb71842010-12-12 08:51:33 +00006116 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006117 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006118 OpBuilder.addUnaryStarPointerOverloads();
6119 else
6120 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6121 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006122
Chandler Carruthabb71842010-12-12 08:51:33 +00006123 case OO_Slash:
6124 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006125 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006126
6127 case OO_PlusPlus:
6128 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006129 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6130 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006131 break;
6132
Douglas Gregor19b7b152009-08-24 13:43:27 +00006133 case OO_EqualEqual:
6134 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006135 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006136 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006137
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006138 case OO_Less:
6139 case OO_Greater:
6140 case OO_LessEqual:
6141 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006142 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006143 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6144 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006145
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006146 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006147 case OO_Caret:
6148 case OO_Pipe:
6149 case OO_LessLess:
6150 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006151 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006152 break;
6153
Chandler Carruthabb71842010-12-12 08:51:33 +00006154 case OO_Amp: // '&' is either unary or binary
6155 if (NumArgs == 1)
6156 // C++ [over.match.oper]p3:
6157 // -- For the operator ',', the unary operator '&', or the
6158 // operator '->', the built-in candidates set is empty.
6159 break;
6160
6161 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6162 break;
6163
6164 case OO_Tilde:
6165 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6166 break;
6167
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006168 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006169 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006170 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006171
6172 case OO_PlusEqual:
6173 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006174 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006175 // Fall through.
6176
6177 case OO_StarEqual:
6178 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006179 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006180 break;
6181
6182 case OO_PercentEqual:
6183 case OO_LessLessEqual:
6184 case OO_GreaterGreaterEqual:
6185 case OO_AmpEqual:
6186 case OO_CaretEqual:
6187 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006188 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006189 break;
6190
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006191 case OO_Exclaim:
6192 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006193 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006194
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006195 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006196 case OO_PipePipe:
6197 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006198 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199
6200 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006201 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006202 break;
6203
6204 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006205 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006206 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006207
6208 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006209 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006210 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6211 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006212 }
6213}
6214
Douglas Gregorfa047642009-02-04 00:32:51 +00006215/// \brief Add function candidates found via argument-dependent lookup
6216/// to the set of overloading candidates.
6217///
6218/// This routine performs argument-dependent name lookup based on the
6219/// given function name (which may also be an operator name) and adds
6220/// all of the overload candidates found by ADL to the overload
6221/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006222void
Douglas Gregorfa047642009-02-04 00:32:51 +00006223Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006224 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006225 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006226 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006227 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006228 bool PartialOverloading,
6229 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006230 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006231
John McCalla113e722010-01-26 06:04:06 +00006232 // FIXME: This approach for uniquing ADL results (and removing
6233 // redundant candidates from the set) relies on pointer-equality,
6234 // which means we need to key off the canonical decl. However,
6235 // always going back to the canonical decl might not get us the
6236 // right set of default arguments. What default arguments are
6237 // we supposed to consider on ADL candidates, anyway?
6238
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006239 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006240 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6241 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006242
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006243 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006244 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6245 CandEnd = CandidateSet.end();
6246 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006247 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006248 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006249 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006250 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006251 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006252
6253 // For each of the ADL candidates we found, add it to the overload
6254 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006255 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006256 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006258 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006259 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006260
John McCall9aa472c2010-03-19 07:35:19 +00006261 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006262 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006263 } else
John McCall6e266892010-01-26 03:27:55 +00006264 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006265 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006266 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006267 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006268}
6269
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006270/// isBetterOverloadCandidate - Determines whether the first overload
6271/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006272bool
John McCall120d63c2010-08-24 20:38:10 +00006273isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006274 const OverloadCandidate &Cand1,
6275 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006276 SourceLocation Loc,
6277 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006278 // Define viable functions to be better candidates than non-viable
6279 // functions.
6280 if (!Cand2.Viable)
6281 return Cand1.Viable;
6282 else if (!Cand1.Viable)
6283 return false;
6284
Douglas Gregor88a35142008-12-22 05:46:06 +00006285 // C++ [over.match.best]p1:
6286 //
6287 // -- if F is a static member function, ICS1(F) is defined such
6288 // that ICS1(F) is neither better nor worse than ICS1(G) for
6289 // any function G, and, symmetrically, ICS1(G) is neither
6290 // better nor worse than ICS1(F).
6291 unsigned StartArg = 0;
6292 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6293 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006294
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006295 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006296 // A viable function F1 is defined to be a better function than another
6297 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006298 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006299 unsigned NumArgs = Cand1.Conversions.size();
6300 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6301 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006302 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006303 switch (CompareImplicitConversionSequences(S,
6304 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006305 Cand2.Conversions[ArgIdx])) {
6306 case ImplicitConversionSequence::Better:
6307 // Cand1 has a better conversion sequence.
6308 HasBetterConversion = true;
6309 break;
6310
6311 case ImplicitConversionSequence::Worse:
6312 // Cand1 can't be better than Cand2.
6313 return false;
6314
6315 case ImplicitConversionSequence::Indistinguishable:
6316 // Do nothing.
6317 break;
6318 }
6319 }
6320
Mike Stump1eb44332009-09-09 15:08:12 +00006321 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006322 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006323 if (HasBetterConversion)
6324 return true;
6325
Mike Stump1eb44332009-09-09 15:08:12 +00006326 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006327 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006328 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006329 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6330 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006331
6332 // -- F1 and F2 are function template specializations, and the function
6333 // template for F1 is more specialized than the template for F2
6334 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006335 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006336 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006337 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006338 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006339 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6340 Cand2.Function->getPrimaryTemplate(),
6341 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006342 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006343 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006344 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006345 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006347
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006348 // -- the context is an initialization by user-defined conversion
6349 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6350 // from the return type of F1 to the destination type (i.e.,
6351 // the type of the entity being initialized) is a better
6352 // conversion sequence than the standard conversion sequence
6353 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006354 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006355 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006356 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006357 switch (CompareStandardConversionSequences(S,
6358 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006359 Cand2.FinalConversion)) {
6360 case ImplicitConversionSequence::Better:
6361 // Cand1 has a better conversion sequence.
6362 return true;
6363
6364 case ImplicitConversionSequence::Worse:
6365 // Cand1 can't be better than Cand2.
6366 return false;
6367
6368 case ImplicitConversionSequence::Indistinguishable:
6369 // Do nothing
6370 break;
6371 }
6372 }
6373
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006374 return false;
6375}
6376
Mike Stump1eb44332009-09-09 15:08:12 +00006377/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006378/// within an overload candidate set.
6379///
6380/// \param CandidateSet the set of candidate functions.
6381///
6382/// \param Loc the location of the function name (or operator symbol) for
6383/// which overload resolution occurs.
6384///
Mike Stump1eb44332009-09-09 15:08:12 +00006385/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006386/// function, Best points to the candidate function found.
6387///
6388/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006389OverloadingResult
6390OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006391 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00006392 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006393 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006394 Best = end();
6395 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6396 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006397 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006398 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006399 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006400 }
6401
6402 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006403 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006404 return OR_No_Viable_Function;
6405
6406 // Make sure that this function is better than every other viable
6407 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006408 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006409 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006410 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006411 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006412 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006413 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006414 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006415 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006416 }
Mike Stump1eb44332009-09-09 15:08:12 +00006417
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006418 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006419 if (Best->Function &&
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00006420 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006421 return OR_Deleted;
6422
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006423 return OR_Success;
6424}
6425
John McCall3c80f572010-01-12 02:15:36 +00006426namespace {
6427
6428enum OverloadCandidateKind {
6429 oc_function,
6430 oc_method,
6431 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006432 oc_function_template,
6433 oc_method_template,
6434 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006435 oc_implicit_default_constructor,
6436 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00006437 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006438 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00006439 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006440 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00006441};
6442
John McCall220ccbf2010-01-13 00:25:19 +00006443OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6444 FunctionDecl *Fn,
6445 std::string &Description) {
6446 bool isTemplate = false;
6447
6448 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6449 isTemplate = true;
6450 Description = S.getTemplateArgumentBindingsText(
6451 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6452 }
John McCallb1622a12010-01-06 09:43:14 +00006453
6454 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006455 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006456 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006457
Sebastian Redlf677ea32011-02-05 19:23:19 +00006458 if (Ctor->getInheritedConstructor())
6459 return oc_implicit_inherited_constructor;
6460
Sean Hunt82713172011-05-25 23:16:36 +00006461 if (Ctor->isDefaultConstructor())
6462 return oc_implicit_default_constructor;
6463
6464 if (Ctor->isMoveConstructor())
6465 return oc_implicit_move_constructor;
6466
6467 assert(Ctor->isCopyConstructor() &&
6468 "unexpected sort of implicit constructor");
6469 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006470 }
6471
6472 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6473 // This actually gets spelled 'candidate function' for now, but
6474 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006475 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006476 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006477
Sean Hunt82713172011-05-25 23:16:36 +00006478 if (Meth->isMoveAssignmentOperator())
6479 return oc_implicit_move_assignment;
6480
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006481 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006482 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006483 return oc_implicit_copy_assignment;
6484 }
6485
John McCall220ccbf2010-01-13 00:25:19 +00006486 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006487}
6488
Sebastian Redlf677ea32011-02-05 19:23:19 +00006489void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6490 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6491 if (!Ctor) return;
6492
6493 Ctor = Ctor->getInheritedConstructor();
6494 if (!Ctor) return;
6495
6496 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6497}
6498
John McCall3c80f572010-01-12 02:15:36 +00006499} // end anonymous namespace
6500
6501// Notes the location of an overload candidate.
6502void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006503 std::string FnDesc;
6504 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6505 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6506 << (unsigned) K << FnDesc;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006507 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00006508}
6509
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006510//Notes the location of all overload candidates designated through
6511// OverloadedExpr
6512void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6513 assert(OverloadedExpr->getType() == Context.OverloadTy);
6514
6515 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6516 OverloadExpr *OvlExpr = Ovl.Expression;
6517
6518 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6519 IEnd = OvlExpr->decls_end();
6520 I != IEnd; ++I) {
6521 if (FunctionTemplateDecl *FunTmpl =
6522 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6523 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6524 } else if (FunctionDecl *Fun
6525 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6526 NoteOverloadCandidate(Fun);
6527 }
6528 }
6529}
6530
John McCall1d318332010-01-12 00:44:57 +00006531/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6532/// "lead" diagnostic; it will be given two arguments, the source and
6533/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006534void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6535 Sema &S,
6536 SourceLocation CaretLoc,
6537 const PartialDiagnostic &PDiag) const {
6538 S.Diag(CaretLoc, PDiag)
6539 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006540 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006541 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6542 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006543 }
John McCall81201622010-01-08 04:41:39 +00006544}
6545
John McCall1d318332010-01-12 00:44:57 +00006546namespace {
6547
John McCalladbb8f82010-01-13 09:16:55 +00006548void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6549 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6550 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006551 assert(Cand->Function && "for now, candidate must be a function");
6552 FunctionDecl *Fn = Cand->Function;
6553
6554 // There's a conversion slot for the object argument if this is a
6555 // non-constructor method. Note that 'I' corresponds the
6556 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006557 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006558 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006559 if (I == 0)
6560 isObjectArgument = true;
6561 else
6562 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006563 }
6564
John McCall220ccbf2010-01-13 00:25:19 +00006565 std::string FnDesc;
6566 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6567
John McCalladbb8f82010-01-13 09:16:55 +00006568 Expr *FromExpr = Conv.Bad.FromExpr;
6569 QualType FromTy = Conv.Bad.getFromType();
6570 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006571
John McCall5920dbb2010-02-02 02:42:52 +00006572 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006573 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006574 Expr *E = FromExpr->IgnoreParens();
6575 if (isa<UnaryOperator>(E))
6576 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006577 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006578
6579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6580 << (unsigned) FnKind << FnDesc
6581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6582 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006583 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00006584 return;
6585 }
6586
John McCall258b2032010-01-23 08:10:49 +00006587 // Do some hand-waving analysis to see if the non-viability is due
6588 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006589 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6590 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6591 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6592 CToTy = RT->getPointeeType();
6593 else {
6594 // TODO: detect and diagnose the full richness of const mismatches.
6595 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6596 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6597 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6598 }
6599
6600 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6601 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6602 // It is dumb that we have to do this here.
6603 while (isa<ArrayType>(CFromTy))
6604 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6605 while (isa<ArrayType>(CToTy))
6606 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6607
6608 Qualifiers FromQs = CFromTy.getQualifiers();
6609 Qualifiers ToQs = CToTy.getQualifiers();
6610
6611 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6612 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6613 << (unsigned) FnKind << FnDesc
6614 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6615 << FromTy
6616 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6617 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006618 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006619 return;
6620 }
6621
Douglas Gregor028ea4b2011-04-26 23:16:46 +00006622 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6623 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6624 << (unsigned) FnKind << FnDesc
6625 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6626 << FromTy
6627 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6628 << (unsigned) isObjectArgument << I+1;
6629 MaybeEmitInheritedConstructorNote(S, Fn);
6630 return;
6631 }
6632
John McCall651f3ee2010-01-14 03:28:57 +00006633 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6634 assert(CVR && "unexpected qualifiers mismatch");
6635
6636 if (isObjectArgument) {
6637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6638 << (unsigned) FnKind << FnDesc
6639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6640 << FromTy << (CVR - 1);
6641 } else {
6642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6643 << (unsigned) FnKind << FnDesc
6644 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6645 << FromTy << (CVR - 1) << I+1;
6646 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006647 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006648 return;
6649 }
6650
John McCall258b2032010-01-23 08:10:49 +00006651 // Diagnose references or pointers to incomplete types differently,
6652 // since it's far from impossible that the incompleteness triggered
6653 // the failure.
6654 QualType TempFromTy = FromTy.getNonReferenceType();
6655 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6656 TempFromTy = PTy->getPointeeType();
6657 if (TempFromTy->isIncompleteType()) {
6658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6659 << (unsigned) FnKind << FnDesc
6660 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6661 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006662 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00006663 return;
6664 }
6665
Douglas Gregor85789812010-06-30 23:01:39 +00006666 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006667 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006668 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6669 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6670 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6671 FromPtrTy->getPointeeType()) &&
6672 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6673 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006674 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00006675 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006676 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006677 }
6678 } else if (const ObjCObjectPointerType *FromPtrTy
6679 = FromTy->getAs<ObjCObjectPointerType>()) {
6680 if (const ObjCObjectPointerType *ToPtrTy
6681 = ToTy->getAs<ObjCObjectPointerType>())
6682 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6683 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6684 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6685 FromPtrTy->getPointeeType()) &&
6686 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006687 BaseToDerivedConversion = 2;
6688 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6689 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6690 !FromTy->isIncompleteType() &&
6691 !ToRefTy->getPointeeType()->isIncompleteType() &&
6692 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6693 BaseToDerivedConversion = 3;
6694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006695
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006696 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006697 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006698 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006699 << (unsigned) FnKind << FnDesc
6700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006701 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006702 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006703 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00006704 return;
6705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006706
John McCall651f3ee2010-01-14 03:28:57 +00006707 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00006708 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6709 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006710 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006711 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006712 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00006713}
6714
6715void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6716 unsigned NumFormalArgs) {
6717 // TODO: treat calls to a missing default constructor as a special case
6718
6719 FunctionDecl *Fn = Cand->Function;
6720 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6721
6722 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006723
Douglas Gregor439d3c32011-05-05 00:13:13 +00006724 // With invalid overloaded operators, it's possible that we think we
6725 // have an arity mismatch when it fact it looks like we have the
6726 // right number of arguments, because only overloaded operators have
6727 // the weird behavior of overloading member and non-member functions.
6728 // Just don't report anything.
6729 if (Fn->isInvalidDecl() &&
6730 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6731 return;
6732
John McCalladbb8f82010-01-13 09:16:55 +00006733 // at least / at most / exactly
6734 unsigned mode, modeCount;
6735 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006736 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6737 (Cand->FailureKind == ovl_fail_bad_deduction &&
6738 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006739 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00006740 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00006741 mode = 0; // "at least"
6742 else
6743 mode = 2; // "exactly"
6744 modeCount = MinParams;
6745 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006746 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6747 (Cand->FailureKind == ovl_fail_bad_deduction &&
6748 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006749 if (MinParams != FnTy->getNumArgs())
6750 mode = 1; // "at most"
6751 else
6752 mode = 2; // "exactly"
6753 modeCount = FnTy->getNumArgs();
6754 }
6755
6756 std::string Description;
6757 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6758
6759 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006760 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00006761 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006762 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006763}
6764
John McCall342fec42010-02-01 18:53:26 +00006765/// Diagnose a failed template-argument deduction.
6766void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6767 Expr **Args, unsigned NumArgs) {
6768 FunctionDecl *Fn = Cand->Function; // pattern
6769
Douglas Gregora9333192010-05-08 17:41:32 +00006770 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006771 NamedDecl *ParamD;
6772 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6773 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6774 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006775 switch (Cand->DeductionFailure.Result) {
6776 case Sema::TDK_Success:
6777 llvm_unreachable("TDK_success while diagnosing bad deduction");
6778
6779 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006780 assert(ParamD && "no parameter found for incomplete deduction result");
6781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6782 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006783 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00006784 return;
6785 }
6786
John McCall57e97782010-08-05 09:05:08 +00006787 case Sema::TDK_Underqualified: {
6788 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6789 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6790
6791 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6792
6793 // Param will have been canonicalized, but it should just be a
6794 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00006795 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00006796 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00006797 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00006798 assert(S.Context.hasSameType(Param, NonCanonParam));
6799
6800 // Arg has also been canonicalized, but there's nothing we can do
6801 // about that. It also doesn't matter as much, because it won't
6802 // have any template parameters in it (because deduction isn't
6803 // done on dependent types).
6804 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6805
6806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6807 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006808 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00006809 return;
6810 }
6811
6812 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00006813 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006814 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006815 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006816 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006817 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006818 which = 1;
6819 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006820 which = 2;
6821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006822
Douglas Gregora9333192010-05-08 17:41:32 +00006823 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006824 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00006825 << *Cand->DeductionFailure.getFirstArg()
6826 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006827 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00006828 return;
6829 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006830
Douglas Gregorf1a84452010-05-08 19:15:54 +00006831 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006832 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00006833 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006834 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00006835 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6836 << ParamD->getDeclName();
6837 else {
6838 int index = 0;
6839 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6840 index = TTP->getIndex();
6841 else if (NonTypeTemplateParmDecl *NTTP
6842 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6843 index = NTTP->getIndex();
6844 else
6845 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006846 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00006847 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6848 << (index + 1);
6849 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006850 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00006851 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006852
Douglas Gregora18592e2010-05-08 18:13:28 +00006853 case Sema::TDK_TooManyArguments:
6854 case Sema::TDK_TooFewArguments:
6855 DiagnoseArityMismatch(S, Cand, NumArgs);
6856 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006857
6858 case Sema::TDK_InstantiationDepth:
6859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006860 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00006861 return;
6862
6863 case Sema::TDK_SubstitutionFailure: {
6864 std::string ArgString;
6865 if (TemplateArgumentList *Args
6866 = Cand->DeductionFailure.getTemplateArgumentList())
6867 ArgString = S.getTemplateArgumentBindingsText(
6868 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6869 *Args);
6870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6871 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006872 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00006873 return;
6874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006875
John McCall342fec42010-02-01 18:53:26 +00006876 // TODO: diagnose these individually, then kill off
6877 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006878 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006879 case Sema::TDK_FailedOverloadResolution:
6880 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006881 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00006882 return;
6883 }
6884}
6885
6886/// Generates a 'note' diagnostic for an overload candidate. We've
6887/// already generated a primary error at the call site.
6888///
6889/// It really does need to be a single diagnostic with its caret
6890/// pointed at the candidate declaration. Yes, this creates some
6891/// major challenges of technical writing. Yes, this makes pointing
6892/// out problems with specific arguments quite awkward. It's still
6893/// better than generating twenty screens of text for every failed
6894/// overload.
6895///
6896/// It would be great to be able to express per-candidate problems
6897/// more richly for those diagnostic clients that cared, but we'd
6898/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006899void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6900 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006901 FunctionDecl *Fn = Cand->Function;
6902
John McCall81201622010-01-08 04:41:39 +00006903 // Note deleted candidates, but only if they're viable.
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00006904 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCall220ccbf2010-01-13 00:25:19 +00006905 std::string FnDesc;
6906 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006907
6908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006909 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006910 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00006911 return;
John McCall81201622010-01-08 04:41:39 +00006912 }
6913
John McCall220ccbf2010-01-13 00:25:19 +00006914 // We don't really have anything else to say about viable candidates.
6915 if (Cand->Viable) {
6916 S.NoteOverloadCandidate(Fn);
6917 return;
6918 }
John McCall1d318332010-01-12 00:44:57 +00006919
John McCalladbb8f82010-01-13 09:16:55 +00006920 switch (Cand->FailureKind) {
6921 case ovl_fail_too_many_arguments:
6922 case ovl_fail_too_few_arguments:
6923 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006924
John McCalladbb8f82010-01-13 09:16:55 +00006925 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006926 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6927
John McCall717e8912010-01-23 05:17:32 +00006928 case ovl_fail_trivial_conversion:
6929 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006930 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006931 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006932
John McCallb1bdc622010-02-25 01:37:24 +00006933 case ovl_fail_bad_conversion: {
6934 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6935 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006936 if (Cand->Conversions[I].isBad())
6937 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006938
John McCalladbb8f82010-01-13 09:16:55 +00006939 // FIXME: this currently happens when we're called from SemaInit
6940 // when user-conversion overload fails. Figure out how to handle
6941 // those conditions and diagnose them well.
6942 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006943 }
John McCallb1bdc622010-02-25 01:37:24 +00006944 }
John McCalla1d7d622010-01-08 00:58:21 +00006945}
6946
6947void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6948 // Desugar the type of the surrogate down to a function type,
6949 // retaining as many typedefs as possible while still showing
6950 // the function type (and, therefore, its parameter types).
6951 QualType FnType = Cand->Surrogate->getConversionType();
6952 bool isLValueReference = false;
6953 bool isRValueReference = false;
6954 bool isPointer = false;
6955 if (const LValueReferenceType *FnTypeRef =
6956 FnType->getAs<LValueReferenceType>()) {
6957 FnType = FnTypeRef->getPointeeType();
6958 isLValueReference = true;
6959 } else if (const RValueReferenceType *FnTypeRef =
6960 FnType->getAs<RValueReferenceType>()) {
6961 FnType = FnTypeRef->getPointeeType();
6962 isRValueReference = true;
6963 }
6964 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6965 FnType = FnTypePtr->getPointeeType();
6966 isPointer = true;
6967 }
6968 // Desugar down to a function type.
6969 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6970 // Reconstruct the pointer/reference as appropriate.
6971 if (isPointer) FnType = S.Context.getPointerType(FnType);
6972 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6973 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6974
6975 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6976 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006977 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00006978}
6979
6980void NoteBuiltinOperatorCandidate(Sema &S,
6981 const char *Opc,
6982 SourceLocation OpLoc,
6983 OverloadCandidate *Cand) {
6984 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6985 std::string TypeStr("operator");
6986 TypeStr += Opc;
6987 TypeStr += "(";
6988 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6989 if (Cand->Conversions.size() == 1) {
6990 TypeStr += ")";
6991 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6992 } else {
6993 TypeStr += ", ";
6994 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6995 TypeStr += ")";
6996 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6997 }
6998}
6999
7000void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7001 OverloadCandidate *Cand) {
7002 unsigned NoOperands = Cand->Conversions.size();
7003 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7004 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007005 if (ICS.isBad()) break; // all meaningless after first invalid
7006 if (!ICS.isAmbiguous()) continue;
7007
John McCall120d63c2010-08-24 20:38:10 +00007008 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007009 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007010 }
7011}
7012
John McCall1b77e732010-01-15 23:32:50 +00007013SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7014 if (Cand->Function)
7015 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007016 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007017 return Cand->Surrogate->getLocation();
7018 return SourceLocation();
7019}
7020
John McCallbf65c0b2010-01-12 00:48:53 +00007021struct CompareOverloadCandidatesForDisplay {
7022 Sema &S;
7023 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007024
7025 bool operator()(const OverloadCandidate *L,
7026 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007027 // Fast-path this check.
7028 if (L == R) return false;
7029
John McCall81201622010-01-08 04:41:39 +00007030 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007031 if (L->Viable) {
7032 if (!R->Viable) return true;
7033
7034 // TODO: introduce a tri-valued comparison for overload
7035 // candidates. Would be more worthwhile if we had a sort
7036 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007037 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7038 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007039 } else if (R->Viable)
7040 return false;
John McCall81201622010-01-08 04:41:39 +00007041
John McCall1b77e732010-01-15 23:32:50 +00007042 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007043
John McCall1b77e732010-01-15 23:32:50 +00007044 // Criteria by which we can sort non-viable candidates:
7045 if (!L->Viable) {
7046 // 1. Arity mismatches come after other candidates.
7047 if (L->FailureKind == ovl_fail_too_many_arguments ||
7048 L->FailureKind == ovl_fail_too_few_arguments)
7049 return false;
7050 if (R->FailureKind == ovl_fail_too_many_arguments ||
7051 R->FailureKind == ovl_fail_too_few_arguments)
7052 return true;
John McCall81201622010-01-08 04:41:39 +00007053
John McCall717e8912010-01-23 05:17:32 +00007054 // 2. Bad conversions come first and are ordered by the number
7055 // of bad conversions and quality of good conversions.
7056 if (L->FailureKind == ovl_fail_bad_conversion) {
7057 if (R->FailureKind != ovl_fail_bad_conversion)
7058 return true;
7059
7060 // If there's any ordering between the defined conversions...
7061 // FIXME: this might not be transitive.
7062 assert(L->Conversions.size() == R->Conversions.size());
7063
7064 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007065 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7066 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007067 switch (CompareImplicitConversionSequences(S,
7068 L->Conversions[I],
7069 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007070 case ImplicitConversionSequence::Better:
7071 leftBetter++;
7072 break;
7073
7074 case ImplicitConversionSequence::Worse:
7075 leftBetter--;
7076 break;
7077
7078 case ImplicitConversionSequence::Indistinguishable:
7079 break;
7080 }
7081 }
7082 if (leftBetter > 0) return true;
7083 if (leftBetter < 0) return false;
7084
7085 } else if (R->FailureKind == ovl_fail_bad_conversion)
7086 return false;
7087
John McCall1b77e732010-01-15 23:32:50 +00007088 // TODO: others?
7089 }
7090
7091 // Sort everything else by location.
7092 SourceLocation LLoc = GetLocationForCandidate(L);
7093 SourceLocation RLoc = GetLocationForCandidate(R);
7094
7095 // Put candidates without locations (e.g. builtins) at the end.
7096 if (LLoc.isInvalid()) return false;
7097 if (RLoc.isInvalid()) return true;
7098
7099 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007100 }
7101};
7102
John McCall717e8912010-01-23 05:17:32 +00007103/// CompleteNonViableCandidate - Normally, overload resolution only
7104/// computes up to the first
7105void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7106 Expr **Args, unsigned NumArgs) {
7107 assert(!Cand->Viable);
7108
7109 // Don't do anything on failures other than bad conversion.
7110 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7111
7112 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007113 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007114 unsigned ConvCount = Cand->Conversions.size();
7115 while (true) {
7116 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7117 ConvIdx++;
7118 if (Cand->Conversions[ConvIdx - 1].isBad())
7119 break;
7120 }
7121
7122 if (ConvIdx == ConvCount)
7123 return;
7124
John McCallb1bdc622010-02-25 01:37:24 +00007125 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7126 "remaining conversion is initialized?");
7127
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007128 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007129 // operation somehow.
7130 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007131
7132 const FunctionProtoType* Proto;
7133 unsigned ArgIdx = ConvIdx;
7134
7135 if (Cand->IsSurrogate) {
7136 QualType ConvType
7137 = Cand->Surrogate->getConversionType().getNonReferenceType();
7138 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7139 ConvType = ConvPtrType->getPointeeType();
7140 Proto = ConvType->getAs<FunctionProtoType>();
7141 ArgIdx--;
7142 } else if (Cand->Function) {
7143 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7144 if (isa<CXXMethodDecl>(Cand->Function) &&
7145 !isa<CXXConstructorDecl>(Cand->Function))
7146 ArgIdx--;
7147 } else {
7148 // Builtin binary operator with a bad first conversion.
7149 assert(ConvCount <= 3);
7150 for (; ConvIdx != ConvCount; ++ConvIdx)
7151 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007152 = TryCopyInitialization(S, Args[ConvIdx],
7153 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007154 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00007155 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00007156 return;
7157 }
7158
7159 // Fill in the rest of the conversions.
7160 unsigned NumArgsInProto = Proto->getNumArgs();
7161 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7162 if (ArgIdx < NumArgsInProto)
7163 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007164 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007165 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00007166 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00007167 else
7168 Cand->Conversions[ConvIdx].setEllipsis();
7169 }
7170}
7171
John McCalla1d7d622010-01-08 00:58:21 +00007172} // end anonymous namespace
7173
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007174/// PrintOverloadCandidates - When overload resolution fails, prints
7175/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00007176/// set.
John McCall120d63c2010-08-24 20:38:10 +00007177void OverloadCandidateSet::NoteCandidates(Sema &S,
7178 OverloadCandidateDisplayKind OCD,
7179 Expr **Args, unsigned NumArgs,
7180 const char *Opc,
7181 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00007182 // Sort the candidates by viability and position. Sorting directly would
7183 // be prohibitive, so we make a set of pointers and sort those.
7184 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00007185 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7186 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00007187 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00007188 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00007189 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00007190 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007191 if (Cand->Function || Cand->IsSurrogate)
7192 Cands.push_back(Cand);
7193 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7194 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00007195 }
7196 }
7197
John McCallbf65c0b2010-01-12 00:48:53 +00007198 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00007199 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007200
John McCall1d318332010-01-12 00:44:57 +00007201 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00007202
John McCall81201622010-01-08 04:41:39 +00007203 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00007204 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007205 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00007206 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7207 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00007208
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007209 // Set an arbitrary limit on the number of candidate functions we'll spam
7210 // the user with. FIXME: This limit should depend on details of the
7211 // candidate list.
7212 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7213 break;
7214 }
7215 ++CandsShown;
7216
John McCalla1d7d622010-01-08 00:58:21 +00007217 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00007218 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00007219 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00007220 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007221 else {
7222 assert(Cand->Viable &&
7223 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00007224 // Generally we only see ambiguities including viable builtin
7225 // operators if overload resolution got screwed up by an
7226 // ambiguous user-defined conversion.
7227 //
7228 // FIXME: It's quite possible for different conversions to see
7229 // different ambiguities, though.
7230 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00007231 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00007232 ReportedAmbiguousConversions = true;
7233 }
John McCalla1d7d622010-01-08 00:58:21 +00007234
John McCall1d318332010-01-12 00:44:57 +00007235 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00007236 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007237 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007238 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007239
7240 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00007241 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007242}
7243
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007244// [PossiblyAFunctionType] --> [Return]
7245// NonFunctionType --> NonFunctionType
7246// R (A) --> R(A)
7247// R (*)(A) --> R (A)
7248// R (&)(A) --> R (A)
7249// R (S::*)(A) --> R (A)
7250QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7251 QualType Ret = PossiblyAFunctionType;
7252 if (const PointerType *ToTypePtr =
7253 PossiblyAFunctionType->getAs<PointerType>())
7254 Ret = ToTypePtr->getPointeeType();
7255 else if (const ReferenceType *ToTypeRef =
7256 PossiblyAFunctionType->getAs<ReferenceType>())
7257 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00007258 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007259 PossiblyAFunctionType->getAs<MemberPointerType>())
7260 Ret = MemTypePtr->getPointeeType();
7261 Ret =
7262 Context.getCanonicalType(Ret).getUnqualifiedType();
7263 return Ret;
7264}
Douglas Gregor904eed32008-11-10 20:40:00 +00007265
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007266// A helper class to help with address of function resolution
7267// - allows us to avoid passing around all those ugly parameters
7268class AddressOfFunctionResolver
7269{
7270 Sema& S;
7271 Expr* SourceExpr;
7272 const QualType& TargetType;
7273 QualType TargetFunctionType; // Extracted function type from target type
7274
7275 bool Complain;
7276 //DeclAccessPair& ResultFunctionAccessPair;
7277 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007278
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007279 bool TargetTypeIsNonStaticMemberFunction;
7280 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007281
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007282 OverloadExpr::FindResult OvlExprInfo;
7283 OverloadExpr *OvlExpr;
7284 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCall9aa472c2010-03-19 07:35:19 +00007285 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007286
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007287public:
7288 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7289 const QualType& TargetType, bool Complain)
7290 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7291 Complain(Complain), Context(S.getASTContext()),
7292 TargetTypeIsNonStaticMemberFunction(
7293 !!TargetType->getAs<MemberPointerType>()),
7294 FoundNonTemplateFunction(false),
7295 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7296 OvlExpr(OvlExprInfo.Expression)
7297 {
7298 ExtractUnqualifiedFunctionTypeFromTargetType();
7299
7300 if (!TargetFunctionType->isFunctionType()) {
7301 if (OvlExpr->hasExplicitTemplateArgs()) {
7302 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00007303 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007304 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00007305
7306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7307 if (!Method->isStatic()) {
7308 // If the target type is a non-function type and the function
7309 // found is a non-static member function, pretend as if that was
7310 // the target, it's the only possible type to end up with.
7311 TargetTypeIsNonStaticMemberFunction = true;
7312
7313 // And skip adding the function if its not in the proper form.
7314 // We'll diagnose this due to an empty set of functions.
7315 if (!OvlExprInfo.HasFormOfMemberPointer)
7316 return;
7317 }
7318 }
7319
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007320 Matches.push_back(std::make_pair(dap,Fn));
7321 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00007322 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007323 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00007324 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007325
7326 if (OvlExpr->hasExplicitTemplateArgs())
7327 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00007328
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007329 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7330 // C++ [over.over]p4:
7331 // If more than one function is selected, [...]
7332 if (Matches.size() > 1) {
7333 if (FoundNonTemplateFunction)
7334 EliminateAllTemplateMatches();
7335 else
7336 EliminateAllExceptMostSpecializedTemplate();
7337 }
7338 }
7339 }
7340
7341private:
7342 bool isTargetTypeAFunction() const {
7343 return TargetFunctionType->isFunctionType();
7344 }
7345
7346 // [ToType] [Return]
7347
7348 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7349 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7350 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7351 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7352 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7353 }
7354
7355 // return true if any matching specializations were found
7356 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7357 const DeclAccessPair& CurAccessFunPair) {
7358 if (CXXMethodDecl *Method
7359 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7360 // Skip non-static function templates when converting to pointer, and
7361 // static when converting to member pointer.
7362 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7363 return false;
7364 }
7365 else if (TargetTypeIsNonStaticMemberFunction)
7366 return false;
7367
7368 // C++ [over.over]p2:
7369 // If the name is a function template, template argument deduction is
7370 // done (14.8.2.2), and if the argument deduction succeeds, the
7371 // resulting template argument list is used to generate a single
7372 // function template specialization, which is added to the set of
7373 // overloaded functions considered.
7374 FunctionDecl *Specialization = 0;
7375 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7376 if (Sema::TemplateDeductionResult Result
7377 = S.DeduceTemplateArguments(FunctionTemplate,
7378 &OvlExplicitTemplateArgs,
7379 TargetFunctionType, Specialization,
7380 Info)) {
7381 // FIXME: make a note of the failed deduction for diagnostics.
7382 (void)Result;
7383 return false;
7384 }
7385
7386 // Template argument deduction ensures that we have an exact match.
7387 // This function template specicalization works.
7388 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7389 assert(TargetFunctionType
7390 == Context.getCanonicalType(Specialization->getType()));
7391 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7392 return true;
7393 }
7394
7395 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7396 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00007397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00007398 // Skip non-static functions when converting to pointer, and static
7399 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007400 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7401 return false;
7402 }
7403 else if (TargetTypeIsNonStaticMemberFunction)
7404 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00007405
Chandler Carruthbd647292009-12-29 06:17:27 +00007406 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00007407 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007408 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7409 FunDecl->getType()) ||
7410 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor43c79c22009-12-09 00:47:37 +00007411 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007412 Matches.push_back(std::make_pair(CurAccessFunPair,
7413 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00007414 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007415 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00007416 }
Mike Stump1eb44332009-09-09 15:08:12 +00007417 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007418
7419 return false;
7420 }
7421
7422 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7423 bool Ret = false;
7424
7425 // If the overload expression doesn't have the form of a pointer to
7426 // member, don't try to convert it to a pointer-to-member type.
7427 if (IsInvalidFormOfPointerToMemberFunction())
7428 return false;
7429
7430 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7431 E = OvlExpr->decls_end();
7432 I != E; ++I) {
7433 // Look through any using declarations to find the underlying function.
7434 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7435
7436 // C++ [over.over]p3:
7437 // Non-member functions and static member functions match
7438 // targets of type "pointer-to-function" or "reference-to-function."
7439 // Nonstatic member functions match targets of
7440 // type "pointer-to-member-function."
7441 // Note that according to DR 247, the containing class does not matter.
7442 if (FunctionTemplateDecl *FunctionTemplate
7443 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7444 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7445 Ret = true;
7446 }
7447 // If we have explicit template arguments supplied, skip non-templates.
7448 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7449 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7450 Ret = true;
7451 }
7452 assert(Ret || Matches.empty());
7453 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00007454 }
7455
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007456 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007457 // [...] and any given function template specialization F1 is
7458 // eliminated if the set contains a second function template
7459 // specialization whose function template is more specialized
7460 // than the function template of F1 according to the partial
7461 // ordering rules of 14.5.5.2.
7462
7463 // The algorithm specified above is quadratic. We instead use a
7464 // two-pass algorithm (similar to the one used to identify the
7465 // best viable function in an overload set) that identifies the
7466 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00007467
7468 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7469 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7470 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007471
John McCallc373d482010-01-27 01:50:18 +00007472 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007473 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7474 TPOC_Other, 0, SourceExpr->getLocStart(),
7475 S.PDiag(),
7476 S.PDiag(diag::err_addr_ovl_ambiguous)
7477 << Matches[0].second->getDeclName(),
7478 S.PDiag(diag::note_ovl_candidate)
7479 << (unsigned) oc_function_template,
7480 Complain);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007481
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007482 if (Result != MatchesCopy.end()) {
7483 // Make it the first and only element
7484 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7485 Matches[0].second = cast<FunctionDecl>(*Result);
7486 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00007487 }
7488 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007489
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007490 void EliminateAllTemplateMatches() {
7491 // [...] any function template specializations in the set are
7492 // eliminated if the set also contains a non-template function, [...]
7493 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7494 if (Matches[I].second->getPrimaryTemplate() == 0)
7495 ++I;
7496 else {
7497 Matches[I] = Matches[--N];
7498 Matches.set_size(N);
7499 }
7500 }
7501 }
7502
7503public:
7504 void ComplainNoMatchesFound() const {
7505 assert(Matches.empty());
7506 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7507 << OvlExpr->getName() << TargetFunctionType
7508 << OvlExpr->getSourceRange();
7509 S.NoteAllOverloadCandidates(OvlExpr);
7510 }
7511
7512 bool IsInvalidFormOfPointerToMemberFunction() const {
7513 return TargetTypeIsNonStaticMemberFunction &&
7514 !OvlExprInfo.HasFormOfMemberPointer;
7515 }
7516
7517 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7518 // TODO: Should we condition this on whether any functions might
7519 // have matched, or is it more appropriate to do that in callers?
7520 // TODO: a fixit wouldn't hurt.
7521 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7522 << TargetType << OvlExpr->getSourceRange();
7523 }
7524
7525 void ComplainOfInvalidConversion() const {
7526 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7527 << OvlExpr->getName() << TargetType;
7528 }
7529
7530 void ComplainMultipleMatchesFound() const {
7531 assert(Matches.size() > 1);
7532 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7533 << OvlExpr->getName()
7534 << OvlExpr->getSourceRange();
7535 S.NoteAllOverloadCandidates(OvlExpr);
7536 }
7537
7538 int getNumMatches() const { return Matches.size(); }
7539
7540 FunctionDecl* getMatchingFunctionDecl() const {
7541 if (Matches.size() != 1) return 0;
7542 return Matches[0].second;
7543 }
7544
7545 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7546 if (Matches.size() != 1) return 0;
7547 return &Matches[0].first;
7548 }
7549};
7550
7551/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7552/// an overloaded function (C++ [over.over]), where @p From is an
7553/// expression with overloaded function type and @p ToType is the type
7554/// we're trying to resolve to. For example:
7555///
7556/// @code
7557/// int f(double);
7558/// int f(int);
7559///
7560/// int (*pfd)(double) = f; // selects f(double)
7561/// @endcode
7562///
7563/// This routine returns the resulting FunctionDecl if it could be
7564/// resolved, and NULL otherwise. When @p Complain is true, this
7565/// routine will emit diagnostics if there is an error.
7566FunctionDecl *
7567Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7568 bool Complain,
7569 DeclAccessPair &FoundResult) {
7570
7571 assert(AddressOfExpr->getType() == Context.OverloadTy);
7572
7573 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7574 int NumMatches = Resolver.getNumMatches();
7575 FunctionDecl* Fn = 0;
7576 if ( NumMatches == 0 && Complain) {
7577 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7578 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7579 else
7580 Resolver.ComplainNoMatchesFound();
7581 }
7582 else if (NumMatches > 1 && Complain)
7583 Resolver.ComplainMultipleMatchesFound();
7584 else if (NumMatches == 1) {
7585 Fn = Resolver.getMatchingFunctionDecl();
7586 assert(Fn);
7587 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7588 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00007589 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007590 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00007591 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007592
7593 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00007594}
7595
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007596/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00007597/// resolve that overloaded function expression down to a single function.
7598///
7599/// This routine can only resolve template-ids that refer to a single function
7600/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007601/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00007602/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00007603FunctionDecl *
7604Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7605 bool Complain,
7606 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007607 // C++ [over.over]p1:
7608 // [...] [Note: any redundant set of parentheses surrounding the
7609 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00007610 // C++ [over.over]p1:
7611 // [...] The overloaded function name can be preceded by the &
7612 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007613
Douglas Gregor4b52e252009-12-21 23:17:24 +00007614 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00007615 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00007616 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00007617
7618 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00007619 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007620
Douglas Gregor4b52e252009-12-21 23:17:24 +00007621 // Look through all of the overloaded functions, searching for one
7622 // whose type matches exactly.
7623 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00007624 for (UnresolvedSetIterator I = ovl->decls_begin(),
7625 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007626 // C++0x [temp.arg.explicit]p3:
7627 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007628 // where deduction is not done, if a template argument list is
7629 // specified and it, along with any default template arguments,
7630 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00007631 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00007632 FunctionTemplateDecl *FunctionTemplate
7633 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007634
Douglas Gregor4b52e252009-12-21 23:17:24 +00007635 // C++ [over.over]p2:
7636 // If the name is a function template, template argument deduction is
7637 // done (14.8.2.2), and if the argument deduction succeeds, the
7638 // resulting template argument list is used to generate a single
7639 // function template specialization, which is added to the set of
7640 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00007641 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00007642 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007643 if (TemplateDeductionResult Result
7644 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7645 Specialization, Info)) {
7646 // FIXME: make a note of the failed deduction for diagnostics.
7647 (void)Result;
7648 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007649 }
7650
John McCall864c0412011-04-26 20:42:42 +00007651 assert(Specialization && "no specialization and no error?");
7652
Douglas Gregor4b52e252009-12-21 23:17:24 +00007653 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007654 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007655 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00007656 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7657 << ovl->getName();
7658 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007659 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00007660 return 0;
John McCall864c0412011-04-26 20:42:42 +00007661 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007662
John McCall864c0412011-04-26 20:42:42 +00007663 Matched = Specialization;
7664 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00007665 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007666
Douglas Gregor4b52e252009-12-21 23:17:24 +00007667 return Matched;
7668}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007669
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007670
7671
7672
7673// Resolve and fix an overloaded expression that
7674// can be resolved because it identifies a single function
7675// template specialization
7676// Last three arguments should only be supplied if Complain = true
7677ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall864c0412011-04-26 20:42:42 +00007678 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007679 const SourceRange& OpRangeForComplaining,
7680 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00007681 unsigned DiagIDForComplaining) {
7682 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007683
John McCall864c0412011-04-26 20:42:42 +00007684 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007685
John McCall864c0412011-04-26 20:42:42 +00007686 DeclAccessPair found;
7687 ExprResult SingleFunctionExpression;
7688 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7689 ovl.Expression, /*complain*/ false, &found)) {
7690 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7691 return ExprError();
7692
7693 // It is only correct to resolve to an instance method if we're
7694 // resolving a form that's permitted to be a pointer to member.
7695 // Otherwise we'll end up making a bound member expression, which
7696 // is illegal in all the contexts we resolve like this.
7697 if (!ovl.HasFormOfMemberPointer &&
7698 isa<CXXMethodDecl>(fn) &&
7699 cast<CXXMethodDecl>(fn)->isInstance()) {
7700 if (complain) {
7701 Diag(ovl.Expression->getExprLoc(),
7702 diag::err_invalid_use_of_bound_member_func)
7703 << ovl.Expression->getSourceRange();
7704 // TODO: I believe we only end up here if there's a mix of
7705 // static and non-static candidates (otherwise the expression
7706 // would have 'bound member' type, not 'overload' type).
7707 // Ideally we would note which candidate was chosen and why
7708 // the static candidates were rejected.
7709 }
7710
Douglas Gregordb2eae62011-03-16 19:16:25 +00007711 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007712 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00007713
John McCall864c0412011-04-26 20:42:42 +00007714 // Fix the expresion to refer to 'fn'.
7715 SingleFunctionExpression =
7716 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7717
7718 // If desired, do function-to-pointer decay.
7719 if (doFunctionPointerConverion)
7720 SingleFunctionExpression =
7721 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7722 }
7723
7724 if (!SingleFunctionExpression.isUsable()) {
7725 if (complain) {
7726 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7727 << ovl.Expression->getName()
7728 << DestTypeForComplaining
7729 << OpRangeForComplaining
7730 << ovl.Expression->getQualifierLoc().getSourceRange();
7731 NoteAllOverloadCandidates(SrcExpr);
7732 }
7733 return ExprError();
7734 }
7735
7736 return SingleFunctionExpression;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007737}
7738
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007739/// \brief Add a single candidate to the overload set.
7740static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00007741 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00007742 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007743 Expr **Args, unsigned NumArgs,
7744 OverloadCandidateSet &CandidateSet,
7745 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00007746 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00007747 if (isa<UsingShadowDecl>(Callee))
7748 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7749
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007750 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00007751 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00007752 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007753 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007754 return;
John McCallba135432009-11-21 08:51:07 +00007755 }
7756
7757 if (FunctionTemplateDecl *FuncTemplate
7758 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00007759 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7760 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007761 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00007762 return;
7763 }
7764
7765 assert(false && "unhandled case in overloaded call candidate");
7766
7767 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007768}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007769
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007770/// \brief Add the overload candidates named by callee and/or found by argument
7771/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00007772void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007773 Expr **Args, unsigned NumArgs,
7774 OverloadCandidateSet &CandidateSet,
7775 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00007776
7777#ifndef NDEBUG
7778 // Verify that ArgumentDependentLookup is consistent with the rules
7779 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007780 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007781 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7782 // and let Y be the lookup set produced by argument dependent
7783 // lookup (defined as follows). If X contains
7784 //
7785 // -- a declaration of a class member, or
7786 //
7787 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00007788 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007789 //
7790 // -- a declaration that is neither a function or a function
7791 // template
7792 //
7793 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00007794
John McCall3b4294e2009-12-16 12:17:52 +00007795 if (ULE->requiresADL()) {
7796 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7797 E = ULE->decls_end(); I != E; ++I) {
7798 assert(!(*I)->getDeclContext()->isRecord());
7799 assert(isa<UsingShadowDecl>(*I) ||
7800 !(*I)->getDeclContext()->isFunctionOrMethod());
7801 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00007802 }
7803 }
7804#endif
7805
John McCall3b4294e2009-12-16 12:17:52 +00007806 // It would be nice to avoid this copy.
7807 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00007808 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00007809 if (ULE->hasExplicitTemplateArgs()) {
7810 ULE->copyTemplateArgumentsInto(TABuffer);
7811 ExplicitTemplateArgs = &TABuffer;
7812 }
7813
7814 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7815 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00007816 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007817 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007818 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00007819
John McCall3b4294e2009-12-16 12:17:52 +00007820 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00007821 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7822 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007823 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007824 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007825 PartialOverloading,
7826 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007827}
John McCall578b69b2009-12-16 08:11:27 +00007828
Richard Smithf50e88a2011-06-05 22:42:48 +00007829/// Attempt to recover from an ill-formed use of a non-dependent name in a
7830/// template, where the non-dependent name was declared after the template
7831/// was defined. This is common in code written for a compilers which do not
7832/// correctly implement two-stage name lookup.
7833///
7834/// Returns true if a viable candidate was found and a diagnostic was issued.
7835static bool
7836DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
7837 const CXXScopeSpec &SS, LookupResult &R,
7838 TemplateArgumentListInfo *ExplicitTemplateArgs,
7839 Expr **Args, unsigned NumArgs) {
7840 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
7841 return false;
7842
7843 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
7844 SemaRef.LookupQualifiedName(R, DC);
7845
7846 if (!R.empty()) {
7847 R.suppressDiagnostics();
7848
7849 if (isa<CXXRecordDecl>(DC)) {
7850 // Don't diagnose names we find in classes; we get much better
7851 // diagnostics for these from DiagnoseEmptyLookup.
7852 R.clear();
7853 return false;
7854 }
7855
7856 OverloadCandidateSet Candidates(FnLoc);
7857 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7858 AddOverloadedCallCandidate(SemaRef, I.getPair(),
7859 ExplicitTemplateArgs, Args, NumArgs,
7860 Candidates, false);
7861
7862 OverloadCandidateSet::iterator Best;
7863 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success)
7864 // No viable functions. Don't bother the user with notes for functions
7865 // which don't work and shouldn't be found anyway.
7866 return false;
7867
7868 // Find the namespaces where ADL would have looked, and suggest
7869 // declaring the function there instead.
7870 Sema::AssociatedNamespaceSet AssociatedNamespaces;
7871 Sema::AssociatedClassSet AssociatedClasses;
7872 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
7873 AssociatedNamespaces,
7874 AssociatedClasses);
7875 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00007876 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00007877 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00007878 for (Sema::AssociatedNamespaceSet::iterator
7879 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00007880 end = AssociatedNamespaces.end(); it != end; ++it) {
7881 if (!Std->Encloses(*it))
7882 SuggestedNamespaces.insert(*it);
7883 }
Richard Smithf50e88a2011-06-05 22:42:48 +00007884 }
7885
7886 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
7887 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00007888 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00007889 SemaRef.Diag(Best->Function->getLocation(),
7890 diag::note_not_found_by_two_phase_lookup)
7891 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00007892 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00007893 SemaRef.Diag(Best->Function->getLocation(),
7894 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00007895 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00007896 } else {
7897 // FIXME: It would be useful to list the associated namespaces here,
7898 // but the diagnostics infrastructure doesn't provide a way to produce
7899 // a localized representation of a list of items.
7900 SemaRef.Diag(Best->Function->getLocation(),
7901 diag::note_not_found_by_two_phase_lookup)
7902 << R.getLookupName() << 2;
7903 }
7904
7905 // Try to recover by calling this function.
7906 return true;
7907 }
7908
7909 R.clear();
7910 }
7911
7912 return false;
7913}
7914
7915/// Attempt to recover from ill-formed use of a non-dependent operator in a
7916/// template, where the non-dependent operator was declared after the template
7917/// was defined.
7918///
7919/// Returns true if a viable candidate was found and a diagnostic was issued.
7920static bool
7921DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
7922 SourceLocation OpLoc,
7923 Expr **Args, unsigned NumArgs) {
7924 DeclarationName OpName =
7925 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
7926 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
7927 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
7928 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
7929}
7930
John McCall578b69b2009-12-16 08:11:27 +00007931/// Attempts to recover from a call where no functions were found.
7932///
7933/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00007934static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007935BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00007936 UnresolvedLookupExpr *ULE,
7937 SourceLocation LParenLoc,
7938 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00007939 SourceLocation RParenLoc,
7940 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00007941
7942 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00007943 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00007944
John McCall3b4294e2009-12-16 12:17:52 +00007945 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00007946 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00007947 if (ULE->hasExplicitTemplateArgs()) {
7948 ULE->copyTemplateArgumentsInto(TABuffer);
7949 ExplicitTemplateArgs = &TABuffer;
7950 }
7951
John McCall578b69b2009-12-16 08:11:27 +00007952 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7953 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00007954 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
7955 ExplicitTemplateArgs, Args, NumArgs) &&
7956 (!EmptyLookup ||
7957 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)))
John McCallf312b1e2010-08-26 23:41:50 +00007958 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00007959
John McCall3b4294e2009-12-16 12:17:52 +00007960 assert(!R.empty() && "lookup results empty despite recovery");
7961
7962 // Build an implicit member call if appropriate. Just drop the
7963 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00007964 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007965 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00007966 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7967 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00007968 else if (ExplicitTemplateArgs)
7969 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7970 else
7971 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7972
7973 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007974 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007975
7976 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00007977 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00007978 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00007979 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00007980 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007981}
Douglas Gregord7a95972010-06-08 17:35:15 +00007982
Douglas Gregorf6b89692008-11-26 05:54:23 +00007983/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00007984/// (which eventually refers to the declaration Func) and the call
7985/// arguments Args/NumArgs, attempt to resolve the function call down
7986/// to a specific function. If overload resolution succeeds, returns
7987/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00007988/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00007989/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00007990ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007991Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00007992 SourceLocation LParenLoc,
7993 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00007994 SourceLocation RParenLoc,
7995 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00007996#ifndef NDEBUG
7997 if (ULE->requiresADL()) {
7998 // To do ADL, we must have found an unqualified name.
7999 assert(!ULE->getQualifier() && "qualified name with ADL");
8000
8001 // We don't perform ADL for implicit declarations of builtins.
8002 // Verify that this was correctly set up.
8003 FunctionDecl *F;
8004 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8005 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8006 F->getBuiltinID() && F->isImplicit())
8007 assert(0 && "performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008008
John McCall3b4294e2009-12-16 12:17:52 +00008009 // We don't perform ADL in C.
8010 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008011 } else
8012 assert(!ULE->isStdAssociatedNamespace() &&
8013 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008014#endif
8015
John McCall5769d612010-02-08 23:07:23 +00008016 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008017
John McCall3b4294e2009-12-16 12:17:52 +00008018 // Add the functions denoted by the callee to the set of candidate
8019 // functions, including those from argument-dependent lookup.
8020 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008021
8022 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008023 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8024 // out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00008025 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008026 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008027 RParenLoc, /*EmptyLookup=*/true);
John McCall578b69b2009-12-16 08:11:27 +00008028
Douglas Gregorf6b89692008-11-26 05:54:23 +00008029 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008030 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008031 case OR_Success: {
8032 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008033 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008034 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008035 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8036 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008037 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008038 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8039 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008040 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008041
Richard Smithf50e88a2011-06-05 22:42:48 +00008042 case OR_No_Viable_Function: {
8043 // Try to recover by looking for viable functions which the user might
8044 // have meant to call.
8045 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8046 Args, NumArgs, RParenLoc,
8047 /*EmptyLookup=*/false);
8048 if (!Recovery.isInvalid())
8049 return Recovery;
8050
Chris Lattner4330d652009-02-17 07:29:20 +00008051 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008052 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008053 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008054 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008055 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008056 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008057
8058 case OR_Ambiguous:
8059 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008060 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008061 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008062 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008063
8064 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008065 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008066 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8067 << Best->Function->isDeleted()
8068 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008069 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008070 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008071 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8072 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008073 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00008074 }
8075
Douglas Gregorff331c12010-07-25 18:17:45 +00008076 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00008077 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00008078}
8079
John McCall6e266892010-01-26 03:27:55 +00008080static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00008081 return Functions.size() > 1 ||
8082 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8083}
8084
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008085/// \brief Create a unary operation that may resolve to an overloaded
8086/// operator.
8087///
8088/// \param OpLoc The location of the operator itself (e.g., '*').
8089///
8090/// \param OpcIn The UnaryOperator::Opcode that describes this
8091/// operator.
8092///
8093/// \param Functions The set of non-member functions that will be
8094/// considered by overload resolution. The caller needs to build this
8095/// set based on the context using, e.g.,
8096/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8097/// set should not contain any member functions; those will be added
8098/// by CreateOverloadedUnaryOp().
8099///
8100/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008101ExprResult
John McCall6e266892010-01-26 03:27:55 +00008102Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8103 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00008104 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008105 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008106
8107 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8108 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8109 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00008110 // TODO: provide better source location info.
8111 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008112
John Wiegley429bb272011-04-08 18:41:53 +00008113 if (Input->getObjectKind() == OK_ObjCProperty) {
8114 ExprResult Result = ConvertPropertyForRValue(Input);
8115 if (Result.isInvalid())
8116 return ExprError();
8117 Input = Result.take();
8118 }
John McCall0e800c92010-12-04 08:14:53 +00008119
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008120 Expr *Args[2] = { Input, 0 };
8121 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00008122
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008123 // For post-increment and post-decrement, add the implicit '0' as
8124 // the second argument, so that we know this is a post-increment or
8125 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00008126 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008127 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008128 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8129 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008130 NumArgs = 2;
8131 }
8132
8133 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008134 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00008135 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008136 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008137 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008138 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008139 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008140
John McCallc373d482010-01-27 01:50:18 +00008141 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00008142 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008143 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008144 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008145 /*ADL*/ true, IsOverloaded(Fns),
8146 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008147 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008148 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008149 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008150 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008151 OpLoc));
8152 }
8153
8154 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008155 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008156
8157 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008158 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008159
8160 // Add operator candidates that are member functions.
8161 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8162
John McCall6e266892010-01-26 03:27:55 +00008163 // Add candidates from ADL.
8164 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00008165 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00008166 /*ExplicitTemplateArgs*/ 0,
8167 CandidateSet);
8168
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008169 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008170 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008171
8172 // Perform overload resolution.
8173 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008174 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008175 case OR_Success: {
8176 // We found a built-in operator or an overloaded operator.
8177 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00008178
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008179 if (FnDecl) {
8180 // We matched an overloaded operator. Build a call to that
8181 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00008182
Chandler Carruth25ca4212011-02-25 19:41:05 +00008183 MarkDeclarationReferenced(OpLoc, FnDecl);
8184
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008185 // Convert the arguments.
8186 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00008187 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008188
John Wiegley429bb272011-04-08 18:41:53 +00008189 ExprResult InputRes =
8190 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8191 Best->FoundDecl, Method);
8192 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008193 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008194 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008195 } else {
8196 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008197 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00008198 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008199 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00008200 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008201 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00008202 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00008203 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008204 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008205 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008206 }
8207
John McCallb697e082010-05-06 18:15:07 +00008208 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8209
John McCallf89e55a2010-11-18 06:31:45 +00008210 // Determine the result type.
8211 QualType ResultTy = FnDecl->getResultType();
8212 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8213 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00008214
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008215 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008216 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8217 if (FnExpr.isInvalid())
8218 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00008219
Eli Friedman4c3b8962009-11-18 03:58:17 +00008220 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00008221 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008222 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008223 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00008224
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008225 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00008226 FnDecl))
8227 return ExprError();
8228
John McCall9ae2f072010-08-23 23:25:46 +00008229 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008230 } else {
8231 // We matched a built-in operator. Convert the arguments, then
8232 // break out so that we will build the appropriate built-in
8233 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008234 ExprResult InputRes =
8235 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8236 Best->Conversions[0], AA_Passing);
8237 if (InputRes.isInvalid())
8238 return ExprError();
8239 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008240 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008241 }
John Wiegley429bb272011-04-08 18:41:53 +00008242 }
8243
8244 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00008245 // This is an erroneous use of an operator which can be overloaded by
8246 // a non-member function. Check for non-member operators which were
8247 // defined too late to be candidates.
8248 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8249 // FIXME: Recover by calling the found function.
8250 return ExprError();
8251
John Wiegley429bb272011-04-08 18:41:53 +00008252 // No viable function; fall through to handling this as a
8253 // built-in operator, which will produce an error message for us.
8254 break;
8255
8256 case OR_Ambiguous:
8257 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8258 << UnaryOperator::getOpcodeStr(Opc)
8259 << Input->getType()
8260 << Input->getSourceRange();
8261 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8262 Args, NumArgs,
8263 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8264 return ExprError();
8265
8266 case OR_Deleted:
8267 Diag(OpLoc, diag::err_ovl_deleted_oper)
8268 << Best->Function->isDeleted()
8269 << UnaryOperator::getOpcodeStr(Opc)
8270 << getDeletedOrUnavailableSuffix(Best->Function)
8271 << Input->getSourceRange();
8272 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8273 return ExprError();
8274 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008275
8276 // Either we found no viable overloaded operator or we matched a
8277 // built-in operator. In either case, fall through to trying to
8278 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00008279 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008280}
8281
Douglas Gregor063daf62009-03-13 18:40:31 +00008282/// \brief Create a binary operation that may resolve to an overloaded
8283/// operator.
8284///
8285/// \param OpLoc The location of the operator itself (e.g., '+').
8286///
8287/// \param OpcIn The BinaryOperator::Opcode that describes this
8288/// operator.
8289///
8290/// \param Functions The set of non-member functions that will be
8291/// considered by overload resolution. The caller needs to build this
8292/// set based on the context using, e.g.,
8293/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8294/// set should not contain any member functions; those will be added
8295/// by CreateOverloadedBinOp().
8296///
8297/// \param LHS Left-hand argument.
8298/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008299ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00008300Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00008301 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00008302 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00008303 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00008304 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008305 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00008306
8307 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8308 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8309 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8310
8311 // If either side is type-dependent, create an appropriate dependent
8312 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008313 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00008314 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008315 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008316 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00008317 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008318 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00008319 Context.DependentTy,
8320 VK_RValue, OK_Ordinary,
8321 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008322
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008323 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8324 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008325 VK_LValue,
8326 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008327 Context.DependentTy,
8328 Context.DependentTy,
8329 OpLoc));
8330 }
John McCall6e266892010-01-26 03:27:55 +00008331
8332 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00008333 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008334 // TODO: provide better source location info in DNLoc component.
8335 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00008336 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00008337 = UnresolvedLookupExpr::Create(Context, NamingClass,
8338 NestedNameSpecifierLoc(), OpNameInfo,
8339 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008340 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00008341 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00008342 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00008343 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008344 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00008345 OpLoc));
8346 }
8347
John McCall0e800c92010-12-04 08:14:53 +00008348 // Always do property rvalue conversions on the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008349 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8350 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8351 if (Result.isInvalid())
8352 return ExprError();
8353 Args[1] = Result.take();
8354 }
John McCall0e800c92010-12-04 08:14:53 +00008355
8356 // The LHS is more complicated.
8357 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8358
8359 // There's a tension for assignment operators between primitive
8360 // property assignment and the overloaded operators.
8361 if (BinaryOperator::isAssignmentOp(Opc)) {
8362 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8363
8364 // Is the property "logically" settable?
8365 bool Settable = (PRE->isExplicitProperty() ||
8366 PRE->getImplicitPropertySetter());
8367
8368 // To avoid gratuitously inventing semantics, use the primitive
8369 // unless it isn't. Thoughts in case we ever really care:
8370 // - If the property isn't logically settable, we have to
8371 // load and hope.
8372 // - If the property is settable and this is simple assignment,
8373 // we really should use the primitive.
8374 // - If the property is settable, then we could try overloading
8375 // on a generic lvalue of the appropriate type; if it works
8376 // out to a builtin candidate, we would do that same operation
8377 // on the property, and otherwise just error.
8378 if (Settable)
8379 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8380 }
8381
John Wiegley429bb272011-04-08 18:41:53 +00008382 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8383 if (Result.isInvalid())
8384 return ExprError();
8385 Args[0] = Result.take();
John McCall0e800c92010-12-04 08:14:53 +00008386 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008387
Sebastian Redl275c2b42009-11-18 23:10:33 +00008388 // If this is the assignment operator, we only perform overload resolution
8389 // if the left-hand side is a class or enumeration type. This is actually
8390 // a hack. The standard requires that we do overload resolution between the
8391 // various built-in candidates, but as DR507 points out, this can lead to
8392 // problems. So we do it this way, which pretty much follows what GCC does.
8393 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00008394 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008395 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008396
John McCall0e800c92010-12-04 08:14:53 +00008397 // If this is the .* operator, which is not overloadable, just
8398 // create a built-in binary operator.
8399 if (Opc == BO_PtrMemD)
8400 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8401
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008402 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008403 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008404
8405 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008406 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00008407
8408 // Add operator candidates that are member functions.
8409 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8410
John McCall6e266892010-01-26 03:27:55 +00008411 // Add candidates from ADL.
8412 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8413 Args, 2,
8414 /*ExplicitTemplateArgs*/ 0,
8415 CandidateSet);
8416
Douglas Gregor063daf62009-03-13 18:40:31 +00008417 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008418 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00008419
8420 // Perform overload resolution.
8421 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008422 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00008423 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00008424 // We found a built-in operator or an overloaded operator.
8425 FunctionDecl *FnDecl = Best->Function;
8426
8427 if (FnDecl) {
8428 // We matched an overloaded operator. Build a call to that
8429 // operator.
8430
Chandler Carruth25ca4212011-02-25 19:41:05 +00008431 MarkDeclarationReferenced(OpLoc, FnDecl);
8432
Douglas Gregor063daf62009-03-13 18:40:31 +00008433 // Convert the arguments.
8434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00008435 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00008436 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008437
Chandler Carruth6df868e2010-12-12 08:17:55 +00008438 ExprResult Arg1 =
8439 PerformCopyInitialization(
8440 InitializedEntity::InitializeParameter(Context,
8441 FnDecl->getParamDecl(0)),
8442 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008443 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008444 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008445
John Wiegley429bb272011-04-08 18:41:53 +00008446 ExprResult Arg0 =
8447 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8448 Best->FoundDecl, Method);
8449 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008450 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008451 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008452 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008453 } else {
8454 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00008455 ExprResult Arg0 = PerformCopyInitialization(
8456 InitializedEntity::InitializeParameter(Context,
8457 FnDecl->getParamDecl(0)),
8458 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008459 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008460 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008461
Chandler Carruth6df868e2010-12-12 08:17:55 +00008462 ExprResult Arg1 =
8463 PerformCopyInitialization(
8464 InitializedEntity::InitializeParameter(Context,
8465 FnDecl->getParamDecl(1)),
8466 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008467 if (Arg1.isInvalid())
8468 return ExprError();
8469 Args[0] = LHS = Arg0.takeAs<Expr>();
8470 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008471 }
8472
John McCallb697e082010-05-06 18:15:07 +00008473 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8474
John McCallf89e55a2010-11-18 06:31:45 +00008475 // Determine the result type.
8476 QualType ResultTy = FnDecl->getResultType();
8477 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8478 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00008479
8480 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008481 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8482 if (FnExpr.isInvalid())
8483 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00008484
John McCall9ae2f072010-08-23 23:25:46 +00008485 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008486 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008487 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008488
8489 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008490 FnDecl))
8491 return ExprError();
8492
John McCall9ae2f072010-08-23 23:25:46 +00008493 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00008494 } else {
8495 // We matched a built-in operator. Convert the arguments, then
8496 // break out so that we will build the appropriate built-in
8497 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008498 ExprResult ArgsRes0 =
8499 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8500 Best->Conversions[0], AA_Passing);
8501 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008502 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008503 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008504
John Wiegley429bb272011-04-08 18:41:53 +00008505 ExprResult ArgsRes1 =
8506 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8507 Best->Conversions[1], AA_Passing);
8508 if (ArgsRes1.isInvalid())
8509 return ExprError();
8510 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008511 break;
8512 }
8513 }
8514
Douglas Gregor33074752009-09-30 21:46:01 +00008515 case OR_No_Viable_Function: {
8516 // C++ [over.match.oper]p9:
8517 // If the operator is the operator , [...] and there are no
8518 // viable functions, then the operator is assumed to be the
8519 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00008520 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00008521 break;
8522
Chandler Carruth6df868e2010-12-12 08:17:55 +00008523 // For class as left operand for assignment or compound assigment
8524 // operator do not fall through to handling in built-in, but report that
8525 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00008526 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008527 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00008528 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00008529 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8530 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008531 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00008532 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00008533 // This is an erroneous use of an operator which can be overloaded by
8534 // a non-member function. Check for non-member operators which were
8535 // defined too late to be candidates.
8536 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8537 // FIXME: Recover by calling the found function.
8538 return ExprError();
8539
Douglas Gregor33074752009-09-30 21:46:01 +00008540 // No viable function; try to create a built-in operation, which will
8541 // produce an error. Then, show the non-viable candidates.
8542 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00008543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008544 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00008545 "C++ binary operator overloading is missing candidates!");
8546 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00008547 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8548 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00008549 return move(Result);
8550 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008551
8552 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008553 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00008554 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00008555 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008556 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008557 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8558 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008559 return ExprError();
8560
8561 case OR_Deleted:
8562 Diag(OpLoc, diag::err_ovl_deleted_oper)
8563 << Best->Function->isDeleted()
8564 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008565 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008566 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008567 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00008568 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00008569 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008570
Douglas Gregor33074752009-09-30 21:46:01 +00008571 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008572 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008573}
8574
John McCall60d7b3a2010-08-24 06:29:42 +00008575ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00008576Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8577 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008578 Expr *Base, Expr *Idx) {
8579 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00008580 DeclarationName OpName =
8581 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8582
8583 // If either side is type-dependent, create an appropriate dependent
8584 // expression.
8585 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8586
John McCallc373d482010-01-27 01:50:18 +00008587 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008588 // CHECKME: no 'operator' keyword?
8589 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8590 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00008591 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008592 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008593 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008594 /*ADL*/ true, /*Overloaded*/ false,
8595 UnresolvedSetIterator(),
8596 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00008597 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00008598
Sebastian Redlf322ed62009-10-29 20:17:01 +00008599 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8600 Args, 2,
8601 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008602 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008603 RLoc));
8604 }
8605
John Wiegley429bb272011-04-08 18:41:53 +00008606 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8607 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8608 if (Result.isInvalid())
8609 return ExprError();
8610 Args[0] = Result.take();
8611 }
8612 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8613 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8614 if (Result.isInvalid())
8615 return ExprError();
8616 Args[1] = Result.take();
8617 }
John McCall0e800c92010-12-04 08:14:53 +00008618
Sebastian Redlf322ed62009-10-29 20:17:01 +00008619 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008620 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008621
8622 // Subscript can only be overloaded as a member function.
8623
8624 // Add operator candidates that are member functions.
8625 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8626
8627 // Add builtin operator candidates.
8628 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8629
8630 // Perform overload resolution.
8631 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008632 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00008633 case OR_Success: {
8634 // We found a built-in operator or an overloaded operator.
8635 FunctionDecl *FnDecl = Best->Function;
8636
8637 if (FnDecl) {
8638 // We matched an overloaded operator. Build a call to that
8639 // operator.
8640
Chandler Carruth25ca4212011-02-25 19:41:05 +00008641 MarkDeclarationReferenced(LLoc, FnDecl);
8642
John McCall9aa472c2010-03-19 07:35:19 +00008643 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008644 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00008645
Sebastian Redlf322ed62009-10-29 20:17:01 +00008646 // Convert the arguments.
8647 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00008648 ExprResult Arg0 =
8649 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8650 Best->FoundDecl, Method);
8651 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008652 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008653 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008654
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008655 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008656 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008657 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008658 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008659 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008660 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008661 Owned(Args[1]));
8662 if (InputInit.isInvalid())
8663 return ExprError();
8664
8665 Args[1] = InputInit.takeAs<Expr>();
8666
Sebastian Redlf322ed62009-10-29 20:17:01 +00008667 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00008668 QualType ResultTy = FnDecl->getResultType();
8669 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8670 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008671
8672 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008673 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8674 if (FnExpr.isInvalid())
8675 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008676
John McCall9ae2f072010-08-23 23:25:46 +00008677 CXXOperatorCallExpr *TheCall =
8678 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00008679 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00008680 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008681
John McCall9ae2f072010-08-23 23:25:46 +00008682 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008683 FnDecl))
8684 return ExprError();
8685
John McCall9ae2f072010-08-23 23:25:46 +00008686 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008687 } else {
8688 // We matched a built-in operator. Convert the arguments, then
8689 // break out so that we will build the appropriate built-in
8690 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008691 ExprResult ArgsRes0 =
8692 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8693 Best->Conversions[0], AA_Passing);
8694 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008695 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008696 Args[0] = ArgsRes0.take();
8697
8698 ExprResult ArgsRes1 =
8699 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8700 Best->Conversions[1], AA_Passing);
8701 if (ArgsRes1.isInvalid())
8702 return ExprError();
8703 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008704
8705 break;
8706 }
8707 }
8708
8709 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00008710 if (CandidateSet.empty())
8711 Diag(LLoc, diag::err_ovl_no_oper)
8712 << Args[0]->getType() << /*subscript*/ 0
8713 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8714 else
8715 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8716 << Args[0]->getType()
8717 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008718 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8719 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00008720 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008721 }
8722
8723 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008724 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008725 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00008726 << Args[0]->getType() << Args[1]->getType()
8727 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008728 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8729 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008730 return ExprError();
8731
8732 case OR_Deleted:
8733 Diag(LLoc, diag::err_ovl_deleted_oper)
8734 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008735 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00008736 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008737 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8738 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008739 return ExprError();
8740 }
8741
8742 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00008743 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008744}
8745
Douglas Gregor88a35142008-12-22 05:46:06 +00008746/// BuildCallToMemberFunction - Build a call to a member
8747/// function. MemExpr is the expression that refers to the member
8748/// function (and includes the object parameter), Args/NumArgs are the
8749/// arguments to the function call (not including the object
8750/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00008751/// expression refers to a non-static member function or an overloaded
8752/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00008753ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00008754Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8755 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00008756 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00008757 assert(MemExprE->getType() == Context.BoundMemberTy ||
8758 MemExprE->getType() == Context.OverloadTy);
8759
Douglas Gregor88a35142008-12-22 05:46:06 +00008760 // Dig out the member expression. This holds both the object
8761 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00008762 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008763
John McCall864c0412011-04-26 20:42:42 +00008764 // Determine whether this is a call to a pointer-to-member function.
8765 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8766 assert(op->getType() == Context.BoundMemberTy);
8767 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8768
8769 QualType fnType =
8770 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8771
8772 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8773 QualType resultType = proto->getCallResultType(Context);
8774 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8775
8776 // Check that the object type isn't more qualified than the
8777 // member function we're calling.
8778 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8779
8780 QualType objectType = op->getLHS()->getType();
8781 if (op->getOpcode() == BO_PtrMemI)
8782 objectType = objectType->castAs<PointerType>()->getPointeeType();
8783 Qualifiers objectQuals = objectType.getQualifiers();
8784
8785 Qualifiers difference = objectQuals - funcQuals;
8786 difference.removeObjCGCAttr();
8787 difference.removeAddressSpace();
8788 if (difference) {
8789 std::string qualsString = difference.getAsString();
8790 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8791 << fnType.getUnqualifiedType()
8792 << qualsString
8793 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
8794 }
8795
8796 CXXMemberCallExpr *call
8797 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8798 resultType, valueKind, RParenLoc);
8799
8800 if (CheckCallReturnType(proto->getResultType(),
8801 op->getRHS()->getSourceRange().getBegin(),
8802 call, 0))
8803 return ExprError();
8804
8805 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
8806 return ExprError();
8807
8808 return MaybeBindToTemporary(call);
8809 }
8810
John McCall129e2df2009-11-30 22:42:35 +00008811 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00008812 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00008813 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008814 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00008815 if (isa<MemberExpr>(NakedMemExpr)) {
8816 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00008817 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00008818 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00008819 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00008820 } else {
8821 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008822 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008823
John McCall701c89e2009-12-03 04:06:58 +00008824 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008825 Expr::Classification ObjectClassification
8826 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8827 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00008828
Douglas Gregor88a35142008-12-22 05:46:06 +00008829 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00008830 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00008831
John McCallaa81e162009-12-01 22:10:20 +00008832 // FIXME: avoid copy.
8833 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8834 if (UnresExpr->hasExplicitTemplateArgs()) {
8835 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8836 TemplateArgs = &TemplateArgsBuffer;
8837 }
8838
John McCall129e2df2009-11-30 22:42:35 +00008839 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8840 E = UnresExpr->decls_end(); I != E; ++I) {
8841
John McCall701c89e2009-12-03 04:06:58 +00008842 NamedDecl *Func = *I;
8843 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8844 if (isa<UsingShadowDecl>(Func))
8845 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8846
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008847
Francois Pichetdbee3412011-01-18 05:04:39 +00008848 // Microsoft supports direct constructor calls.
8849 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8850 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8851 CandidateSet);
8852 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008853 // If explicit template arguments were provided, we can't call a
8854 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00008855 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008856 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008857
John McCall9aa472c2010-03-19 07:35:19 +00008858 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008859 ObjectClassification,
8860 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008861 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008862 } else {
John McCall129e2df2009-11-30 22:42:35 +00008863 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00008864 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008865 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008866 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00008867 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008868 }
Douglas Gregordec06662009-08-21 18:42:58 +00008869 }
Mike Stump1eb44332009-09-09 15:08:12 +00008870
John McCall129e2df2009-11-30 22:42:35 +00008871 DeclarationName DeclName = UnresExpr->getMemberName();
8872
Douglas Gregor88a35142008-12-22 05:46:06 +00008873 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008874 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00008875 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00008876 case OR_Success:
8877 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00008878 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00008879 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00008880 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008881 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00008882 break;
8883
8884 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00008885 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00008886 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008887 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008888 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008889 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008890 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008891
8892 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00008893 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008894 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008895 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008896 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008897 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008898
8899 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00008900 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008901 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008902 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008903 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008904 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008905 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008906 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008907 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008908 }
8909
John McCall6bb80172010-03-30 21:47:33 +00008910 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00008911
John McCallaa81e162009-12-01 22:10:20 +00008912 // If overload resolution picked a static member, build a
8913 // non-member call based on that function.
8914 if (Method->isStatic()) {
8915 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8916 Args, NumArgs, RParenLoc);
8917 }
8918
John McCall129e2df2009-11-30 22:42:35 +00008919 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00008920 }
8921
John McCallf89e55a2010-11-18 06:31:45 +00008922 QualType ResultType = Method->getResultType();
8923 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8924 ResultType = ResultType.getNonLValueExprType(Context);
8925
Douglas Gregor88a35142008-12-22 05:46:06 +00008926 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008927 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00008928 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008929 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00008930
Anders Carlssoneed3e692009-10-10 00:06:20 +00008931 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008932 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00008933 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00008934 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008935
Douglas Gregor88a35142008-12-22 05:46:06 +00008936 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00008937 // We only need to do this if there was actually an overload; otherwise
8938 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00008939 if (!Method->isStatic()) {
8940 ExprResult ObjectArg =
8941 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8942 FoundDecl, Method);
8943 if (ObjectArg.isInvalid())
8944 return ExprError();
8945 MemExpr->setBase(ObjectArg.take());
8946 }
Douglas Gregor88a35142008-12-22 05:46:06 +00008947
8948 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00008949 const FunctionProtoType *Proto =
8950 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00008951 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00008952 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00008953 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008954
John McCall9ae2f072010-08-23 23:25:46 +00008955 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00008956 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00008957
Anders Carlsson2174d4c2011-05-06 14:25:31 +00008958 if ((isa<CXXConstructorDecl>(CurContext) ||
8959 isa<CXXDestructorDecl>(CurContext)) &&
8960 TheCall->getMethodDecl()->isPure()) {
8961 const CXXMethodDecl *MD = TheCall->getMethodDecl();
8962
8963 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()))
8964 Diag(MemExpr->getLocStart(),
8965 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
8966 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
8967 << MD->getParent()->getDeclName();
8968
8969 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
8970 }
John McCall9ae2f072010-08-23 23:25:46 +00008971 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00008972}
8973
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008974/// BuildCallToObjectOfClassType - Build a call to an object of class
8975/// type (C++ [over.call.object]), which can end up invoking an
8976/// overloaded function call operator (@c operator()) or performing a
8977/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00008978ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00008979Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00008980 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008981 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008982 SourceLocation RParenLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00008983 ExprResult Object = Owned(Obj);
8984 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8985 Object = ConvertPropertyForRValue(Object.take());
8986 if (Object.isInvalid())
8987 return ExprError();
8988 }
John McCall0e800c92010-12-04 08:14:53 +00008989
John Wiegley429bb272011-04-08 18:41:53 +00008990 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8991 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00008992
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008993 // C++ [over.call.object]p1:
8994 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00008995 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008996 // candidate functions includes at least the function call
8997 // operators of T. The function call operators of T are obtained by
8998 // ordinary lookup of the name operator() in the context of
8999 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009000 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009001 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009002
John Wiegley429bb272011-04-08 18:41:53 +00009003 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009004 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009005 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009006 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009007
John McCalla24dc2e2009-11-17 02:14:36 +00009008 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9009 LookupQualifiedName(R, Record->getDecl());
9010 R.suppressDiagnostics();
9011
Douglas Gregor593564b2009-11-15 07:48:03 +00009012 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009013 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009014 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9015 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009016 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009017 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009018
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009019 // C++ [over.call.object]p2:
9020 // In addition, for each conversion function declared in T of the
9021 // form
9022 //
9023 // operator conversion-type-id () cv-qualifier;
9024 //
9025 // where cv-qualifier is the same cv-qualification as, or a
9026 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009027 // denotes the type "pointer to function of (P1,...,Pn) returning
9028 // R", or the type "reference to pointer to function of
9029 // (P1,...,Pn) returning R", or the type "reference to function
9030 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009031 // is also considered as a candidate function. Similarly,
9032 // surrogate call functions are added to the set of candidate
9033 // functions for each conversion function declared in an
9034 // accessible base class provided the function is not hidden
9035 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009036 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009037 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009038 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009039 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009040 NamedDecl *D = *I;
9041 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9042 if (isa<UsingShadowDecl>(D))
9043 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009044
Douglas Gregor4a27d702009-10-21 06:18:39 +00009045 // Skip over templated conversion functions; they aren't
9046 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009047 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009048 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009049
John McCall701c89e2009-12-03 04:06:58 +00009050 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00009051
Douglas Gregor4a27d702009-10-21 06:18:39 +00009052 // Strip the reference type (if any) and then the pointer type (if
9053 // any) to get down to what might be a function type.
9054 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9055 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9056 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009057
Douglas Gregor4a27d702009-10-21 06:18:39 +00009058 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00009059 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley429bb272011-04-08 18:41:53 +00009060 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009061 }
Mike Stump1eb44332009-09-09 15:08:12 +00009062
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009063 // Perform overload resolution.
9064 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009065 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009066 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009067 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009068 // Overload resolution succeeded; we'll build the appropriate call
9069 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009070 break;
9071
9072 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009073 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009074 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9075 << Object.get()->getType() << /*call*/ 1
9076 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009077 else
John Wiegley429bb272011-04-08 18:41:53 +00009078 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009079 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009080 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009081 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009082 break;
9083
9084 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00009085 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009086 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009087 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009088 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009089 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009090
9091 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00009092 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009093 diag::err_ovl_deleted_object_call)
9094 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00009095 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009096 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00009097 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009098 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009099 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009100 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009101
Douglas Gregorff331c12010-07-25 18:17:45 +00009102 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009103 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009104
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009105 if (Best->Function == 0) {
9106 // Since there is no function declaration, this is one of the
9107 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00009108 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009109 = cast<CXXConversionDecl>(
9110 Best->Conversions[0].UserDefined.ConversionFunction);
9111
John Wiegley429bb272011-04-08 18:41:53 +00009112 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009113 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009114
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009115 // We selected one of the surrogate functions that converts the
9116 // object parameter to a function pointer. Perform the conversion
9117 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009118
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00009119 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00009120 // and then call it.
John Wiegley429bb272011-04-08 18:41:53 +00009121 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009122 if (Call.isInvalid())
9123 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009124
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009125 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00009126 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009127 }
9128
Chandler Carruth25ca4212011-02-25 19:41:05 +00009129 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009130 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009131 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009132
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009133 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9134 // that calls this method, using Object for the implicit object
9135 // parameter and passing along the remaining arguments.
9136 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00009137 const FunctionProtoType *Proto =
9138 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009139
9140 unsigned NumArgsInProto = Proto->getNumArgs();
9141 unsigned NumArgsToCheck = NumArgs;
9142
9143 // Build the full argument list for the method call (the
9144 // implicit object parameter is placed at the beginning of the
9145 // list).
9146 Expr **MethodArgs;
9147 if (NumArgs < NumArgsInProto) {
9148 NumArgsToCheck = NumArgsInProto;
9149 MethodArgs = new Expr*[NumArgsInProto + 1];
9150 } else {
9151 MethodArgs = new Expr*[NumArgs + 1];
9152 }
John Wiegley429bb272011-04-08 18:41:53 +00009153 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009154 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9155 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00009156
John Wiegley429bb272011-04-08 18:41:53 +00009157 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9158 if (NewFn.isInvalid())
9159 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009160
9161 // Once we've built TheCall, all of the expressions are properly
9162 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00009163 QualType ResultTy = Method->getResultType();
9164 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9165 ResultTy = ResultTy.getNonLValueExprType(Context);
9166
John McCall9ae2f072010-08-23 23:25:46 +00009167 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009168 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +00009169 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00009170 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009171 delete [] MethodArgs;
9172
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009173 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00009174 Method))
9175 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009176
Douglas Gregor518fda12009-01-13 05:10:00 +00009177 // We may have default arguments. If so, we need to allocate more
9178 // slots in the call for them.
9179 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00009180 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00009181 else if (NumArgs > NumArgsInProto)
9182 NumArgsToCheck = NumArgsInProto;
9183
Chris Lattner312531a2009-04-12 08:11:20 +00009184 bool IsError = false;
9185
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009186 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +00009187 ExprResult ObjRes =
9188 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9189 Best->FoundDecl, Method);
9190 if (ObjRes.isInvalid())
9191 IsError = true;
9192 else
9193 Object = move(ObjRes);
9194 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +00009195
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009196 // Check the argument types.
9197 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009198 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00009199 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009200 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00009201
Douglas Gregor518fda12009-01-13 05:10:00 +00009202 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00009203
John McCall60d7b3a2010-08-24 06:29:42 +00009204 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00009205 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009206 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00009207 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00009208 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009209
Anders Carlsson3faa4862010-01-29 18:43:53 +00009210 IsError |= InputInit.isInvalid();
9211 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009212 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00009213 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00009214 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9215 if (DefArg.isInvalid()) {
9216 IsError = true;
9217 break;
9218 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009219
Douglas Gregord47c47d2009-11-09 19:27:57 +00009220 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009221 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009222
9223 TheCall->setArg(i + 1, Arg);
9224 }
9225
9226 // If this is a variadic call, handle args passed through "...".
9227 if (Proto->isVariadic()) {
9228 // Promote the arguments (C99 6.5.2.2p7).
9229 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +00009230 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9231 IsError |= Arg.isInvalid();
9232 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009233 }
9234 }
9235
Chris Lattner312531a2009-04-12 08:11:20 +00009236 if (IsError) return true;
9237
John McCall9ae2f072010-08-23 23:25:46 +00009238 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00009239 return true;
9240
John McCall182f7092010-08-24 06:09:16 +00009241 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009242}
9243
Douglas Gregor8ba10742008-11-20 16:27:02 +00009244/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00009245/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00009246/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00009247ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009248Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00009249 assert(Base->getType()->isRecordType() &&
9250 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00009251
John Wiegley429bb272011-04-08 18:41:53 +00009252 if (Base->getObjectKind() == OK_ObjCProperty) {
9253 ExprResult Result = ConvertPropertyForRValue(Base);
9254 if (Result.isInvalid())
9255 return ExprError();
9256 Base = Result.take();
9257 }
John McCall0e800c92010-12-04 08:14:53 +00009258
John McCall5769d612010-02-08 23:07:23 +00009259 SourceLocation Loc = Base->getExprLoc();
9260
Douglas Gregor8ba10742008-11-20 16:27:02 +00009261 // C++ [over.ref]p1:
9262 //
9263 // [...] An expression x->m is interpreted as (x.operator->())->m
9264 // for a class object x of type T if T::operator->() exists and if
9265 // the operator is selected as the best match function by the
9266 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00009267 DeclarationName OpName =
9268 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00009269 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00009270 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009271
John McCall5769d612010-02-08 23:07:23 +00009272 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00009273 PDiag(diag::err_typecheck_incomplete_tag)
9274 << Base->getSourceRange()))
9275 return ExprError();
9276
John McCalla24dc2e2009-11-17 02:14:36 +00009277 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9278 LookupQualifiedName(R, BaseRecord->getDecl());
9279 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00009280
9281 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00009282 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009283 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9284 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00009285 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00009286
9287 // Perform overload resolution.
9288 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009289 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00009290 case OR_Success:
9291 // Overload resolution succeeded; we'll build the call below.
9292 break;
9293
9294 case OR_No_Viable_Function:
9295 if (CandidateSet.empty())
9296 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009297 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009298 else
9299 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009300 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009301 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009302 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009303
9304 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009305 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9306 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009307 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009308 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009309
9310 case OR_Deleted:
9311 Diag(OpLoc, diag::err_ovl_deleted_oper)
9312 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009313 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009314 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009315 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009316 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009317 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009318 }
9319
Chandler Carruth25ca4212011-02-25 19:41:05 +00009320 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +00009321 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009322 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00009323
Douglas Gregor8ba10742008-11-20 16:27:02 +00009324 // Convert the object parameter.
9325 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009326 ExprResult BaseResult =
9327 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9328 Best->FoundDecl, Method);
9329 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009330 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009331 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00009332
Douglas Gregor8ba10742008-11-20 16:27:02 +00009333 // Build the operator call.
John Wiegley429bb272011-04-08 18:41:53 +00009334 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9335 if (FnExpr.isInvalid())
9336 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009337
John McCallf89e55a2010-11-18 06:31:45 +00009338 QualType ResultTy = Method->getResultType();
9339 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9340 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00009341 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009342 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009343 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00009344
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009345 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009346 Method))
9347 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +00009348
9349 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00009350}
9351
Douglas Gregor904eed32008-11-10 20:40:00 +00009352/// FixOverloadedFunctionReference - E is an expression that refers to
9353/// a C++ overloaded function (possibly with some parentheses and
9354/// perhaps a '&' around it). We have resolved the overloaded function
9355/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00009356/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00009357Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00009358 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00009359 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009360 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9361 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009362 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009363 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009364
Douglas Gregor699ee522009-11-20 19:42:02 +00009365 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009366 }
9367
Douglas Gregor699ee522009-11-20 19:42:02 +00009368 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009369 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9370 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009371 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00009372 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00009373 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00009374 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00009375 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009376 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009377
9378 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +00009379 ICE->getCastKind(),
9380 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00009381 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009382 }
9383
Douglas Gregor699ee522009-11-20 19:42:02 +00009384 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00009385 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00009386 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00009387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9388 if (Method->isStatic()) {
9389 // Do nothing: static member functions aren't any different
9390 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00009391 } else {
John McCallf7a1a742009-11-24 19:00:30 +00009392 // Fix the sub expression, which really has to be an
9393 // UnresolvedLookupExpr holding an overloaded member function
9394 // or template.
John McCall6bb80172010-03-30 21:47:33 +00009395 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9396 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00009397 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009398 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00009399
John McCallba135432009-11-21 08:51:07 +00009400 assert(isa<DeclRefExpr>(SubExpr)
9401 && "fixed to something other than a decl ref");
9402 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9403 && "fixed to a member ref with no nested name qualifier");
9404
9405 // We have taken the address of a pointer to member
9406 // function. Perform the computation here so that we get the
9407 // appropriate pointer to member type.
9408 QualType ClassType
9409 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9410 QualType MemPtrType
9411 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9412
John McCallf89e55a2010-11-18 06:31:45 +00009413 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9414 VK_RValue, OK_Ordinary,
9415 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00009416 }
9417 }
John McCall6bb80172010-03-30 21:47:33 +00009418 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9419 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009420 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009421 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009422
John McCall2de56d12010-08-25 11:45:40 +00009423 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00009424 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00009425 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00009426 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009427 }
John McCallba135432009-11-21 08:51:07 +00009428
9429 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00009430 // FIXME: avoid copy.
9431 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00009432 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00009433 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9434 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00009435 }
9436
John McCallba135432009-11-21 08:51:07 +00009437 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009438 ULE->getQualifierLoc(),
John McCallba135432009-11-21 08:51:07 +00009439 Fn,
9440 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009441 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009442 VK_LValue,
Chandler Carruth3aa81402011-05-01 23:48:14 +00009443 Found.getDecl(),
John McCallaa81e162009-12-01 22:10:20 +00009444 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00009445 }
9446
John McCall129e2df2009-11-30 22:42:35 +00009447 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00009448 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00009449 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9450 if (MemExpr->hasExplicitTemplateArgs()) {
9451 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9452 TemplateArgs = &TemplateArgsBuffer;
9453 }
John McCalld5532b62009-11-23 01:53:49 +00009454
John McCallaa81e162009-12-01 22:10:20 +00009455 Expr *Base;
9456
John McCallf89e55a2010-11-18 06:31:45 +00009457 // If we're filling in a static method where we used to have an
9458 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00009459 if (MemExpr->isImplicitAccess()) {
9460 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9461 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009462 MemExpr->getQualifierLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009463 Fn,
9464 MemExpr->getMemberLoc(),
9465 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009466 VK_LValue,
Chandler Carruth3aa81402011-05-01 23:48:14 +00009467 Found.getDecl(),
John McCallaa81e162009-12-01 22:10:20 +00009468 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00009469 } else {
9470 SourceLocation Loc = MemExpr->getMemberLoc();
9471 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +00009472 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +00009473 Base = new (Context) CXXThisExpr(Loc,
9474 MemExpr->getBaseType(),
9475 /*isImplicit=*/true);
9476 }
John McCallaa81e162009-12-01 22:10:20 +00009477 } else
John McCall3fa5cae2010-10-26 07:05:15 +00009478 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00009479
John McCallf5307512011-04-27 00:36:17 +00009480 ExprValueKind valueKind;
9481 QualType type;
9482 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9483 valueKind = VK_LValue;
9484 type = Fn->getType();
9485 } else {
9486 valueKind = VK_RValue;
9487 type = Context.BoundMemberTy;
9488 }
9489
John McCallaa81e162009-12-01 22:10:20 +00009490 return MemberExpr::Create(Context, Base,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009491 MemExpr->isArrow(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00009492 MemExpr->getQualifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009493 Fn,
John McCall6bb80172010-03-30 21:47:33 +00009494 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00009495 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00009496 TemplateArgs,
John McCallf5307512011-04-27 00:36:17 +00009497 type, valueKind, OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00009498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009499
John McCall3fa5cae2010-10-26 07:05:15 +00009500 llvm_unreachable("Invalid reference to overloaded function");
9501 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00009502}
9503
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009504ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +00009505 DeclAccessPair Found,
9506 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00009507 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00009508}
9509
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009510} // end namespace clang